Export images from html to word

3

Starting with my previous question , I would like to know how I can export an image of html to Word, or at least know if it is possible or not.

I have the following table:

 <table id="test" class="table table-striped table-custom table-responsive">            
            <tbody id="tablabody">              
                <tr>
                    <td style="width:33.333333%">
                        <table class="table table-striped table-custom table-responsive">            
                            <tbody>             
                                <tr>
                                    <td><img src="/html/images/chico64.png" /></td>                 
                                </tr>
                                <tr>
                                    <td>Nombre: IKER</td>
                                    <td>Apellido: IKER</td>
                                </tr>
                            </tbody>
                        </table>                    
                    </td>
                    <td style="width:33.333333%">
                        <table class="table table-striped table-custom table-responsive">            
                            <tbody>             
                                <tr>
                                    <td><img src="/html/images/chico64.png" /></td>                 
                                </tr>
                                <tr>
                                    <td>Nombre: ANDONI</td>
                                    <td>Apellido: ANDONI</td>
                                </tr>
                            </tbody>
                        </table>                    
                    </td>
                    <td style="width:33.333333%">
                        <table class="table table-striped table-custom table-responsive">            
                            <tbody>             
                                <tr>
                                    <td><img src="/html/images/chica64.png" /></td>                 
                                </tr>
                                <tr>
                                    <td>Nombre: ERIKA</td>
                                    <td>Apellido: ERIKA</td>
                                </tr>
                            </tbody>
                        </table>                    
                    </td>                                       
                </tr>
            </tbody>
        </table>

I export it with a button that calls the following method:

function creaWord(){    
var html = document.getElementById("test").outerHTML;
  var blob = new Blob(['\ufeff', html], {
    type: 'application/msword'
  });
  var href = URL.createObjectURL(blob);
  var a = document.createElement('a');
  a.href = href;
  a.download = "documento.doc";
  document.body.appendChild(a);
  if (navigator.msSaveOrOpenBlob) {
    navigator.msSaveOrOpenBlob(blob, 'documento.doc');
  } else {
    a.click();
  }
  document.body.removeChild(a);
}

This correctly exports to me the format of the table, but the images are exported to me in this way. I do not even know if you can export images to Word in this way. But at least clarify whether it is possible or not, and if possible as it should be.

Edition

There is a jsfiddle that uses an external library and exports images. At first it may be a valid solution but I would like to do it without using external libraries.

On the other hand, I have seen that in this jsfiddle it converts the image to base64 but I have tried to do the same (without using the library) to see if it was coding but it still does not work.

Edition 2

After seeing the low quality of my results with javascript I'm trying to do it with php.

The first thing I've done is that the button calls the next php page.

<?php
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=documento.doc");

echo "<html>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">
<style> 
@page
{
    size:21cm 29.7cmt;  /* A4 */
    margin:1cm 1cm 1cm 1cm; /* Margins: 2.5 cm on each side */
    mso-page-orientation: portrait; 
}
@page Section1 { }
div.Section1 { page:Section1; }
p.MsoHeader, p.MsoFooter { border: 1px solid black; }
</style>
<body>
<div class=Section1>
<table id='test' style='  border: 1px solid black;'>            
    <tr>
        <td class='col-4' style='  border: 1px solid black;'>
            <div class='row' style='  border: 1px solid black;'>
                <div class='col-6' style='  border: 1px solid black;'>
                    <img id='img-0' src='/html/images/chico64.png' />
                </div>
                <div class='col-6' style='  border: 1px solid black;'>
                    <h1>1</h1>
                </div>
            </div>
            <div class='row' style='  border: 1px solid black;'>
                <div class='col-12' style='  border: 1px solid black;'>
                    Carrero Gomez, Iker
                </div>                      
            </div>
        </td>   
    </tr>
</table>
</div>
</body>
</html>";
?>

So far everything works relatively well but I have two problems.

  • The word opens with the web design view, I would like to know how to avoid this and that it opens like a normal word.
  • Images are still not exported.
  • The documentation to know what styles I should apply I am using this page but I still think that Some, like the page break, do not work for me.

        
    asked by Lombarda Arda 26.04.2017 в 15:05
    source

    2 answers

    2

    One way to do this is by converting the images to base64. If the images are on your server you will not have problems with CORS (cross-origin resource sharing).

    I gave an id to the images

    ...<img id="img-0" src="/html/images/chico64.png" />...
    ...<img id="img-1" src="/html/images/chico64.png" />...
    ...<img id="img-2" src="/html/images/chica64.png" />...
    

    This is the function that converts the link with the image to base64:

    function imgUrlABase64(url, callback) {
        var xhr = new XMLHttpRequest();
        xhr.onload = function() {
        var reader = new FileReader();
        reader.onloadend = function() {
          callback(reader.result);
        }
        reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.send();
    }
    

    I modified your creaWord function to replace the src of the image to base64. Simply replace the link in the src with the base64 encoding. See to see that the .replace finds and replaces the src correctly. Make sure that urlBase + document.getElementById("img-0") is the link to the image.

    function creaWord(){        
        var html = document.getElementById("test").outerHTML;
    
        // -----------------------------------------------
        // CONVERTIR IMG SRC A BASE64
        var urlBase = window.location.href;
        var imgs = document.querySelectorAll('[id^=img-]');
        for (var i in imgs){
            imgUrlABase64(document.getElementById("img-0").src, 
                function(dataURL){
                    html = html.replace(urlBase + document.getElementById("img-"+i), dataURL); 
                }
            );
        }
        // -----------------------------------------------
    
    
        var blob = new Blob(['\ufeff', html], {
            type: 'application/msword'
        });
        var href = URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = href;
        a.download = "documento.doc";
        document.body.appendChild(a);
        if (navigator.msSaveOrOpenBlob) {
            navigator.msSaveOrOpenBlob(blob, 'documento.doc');
        } else {
            a.click();
        }
        document.body.removeChild(a);
    }
    

    If the images are not on your server, see if any of these other solutions help you: link

    EDIT 2

    This is the answer using PHP with the OP solution in your Edition 2 and the style required for the document to be opened in Word as text and not as Web Layout.

    <?php
        header("Content-type: application/vnd.ms-word");
        header("Content-Disposition: attachment;Filename=documento.doc");
    
        echo "<html 
                xmlns:o='urn:schemas-microsoft-com:office:office'
                xmlns:w='urn:schemas-microsoft-com:office:word' 
                xmlns='http://www.w3.org/TR/REC-html40'>
        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">
        <head>
            <!--[if gte mso 9]>
                <xml>
                <w:WordDocument>
                <w:View>Print</w:View>
                <w:Zoom>90</w:Zoom> 
                <w:DoNotOptimizeForBrowser/>
                </w:WordDocument>
                </xml>
            <![endif]-->
        <style> 
        @page
        {
            size:21cm 29.7cmt;  /* A4 */
            margin:1cm 1cm 1cm 1cm; /* Margins: 2.5 cm on each side */
            mso-page-orientation: portrait; 
        }
        @page Section1 {
            size:21cm 29.7cm;  /* A4 */
            margin:1cm 1cm 1cm 1cm; /* Margins: 2.5 cm on each side */
            mso-header-margin: 2cm;
            mso-footer-margin: 2cm;
            mso-paper-source:0;
            mso-page-orientation: portrait; 
        }
        div.Section1 { page:Section1; }
        p.MsoHeader, p.MsoFooter { border: 1px solid black; }
        </style>
        </head>
        <body>
        <div class=Section1>
        <table id='test' style='  border: 1px solid black;'>            
            <tr>
                <td class='col-4' style='  border: 1px solid black;'>
                    <div class='row' style='  border: 1px solid black;'>
                        <div class='col-6' style='  border: 1px solid black;'>
                            <img id='img-0' src='http://".$_SERVER['SERVER_NAME']."/html/images/chico64.png' />
                        </div>
                        <div class='col-6' style='  border: 1px solid black;'>
                            <h1>1</h1>
                        </div>
                    </div>
                    <div class='row' style='  border: 1px solid black;'>
                        <div class='col-12' style='  border: 1px solid black;'>
                            Carrero Gomez, Iker
                        </div>                      
                    </div>
                </td>   
            </tr>
        </table>
        </div>
        </body>
        </html>";
    ?>
    
        
    answered by 26.04.2017 / 17:25
    source
    0

    For now I have managed to fix the problem of the images, but the problem remains that word opens the document in the view I do not want.

    The problem of the images was simpler than it seemed at first, I had tried to convert them and insert them in different ways.

    In the end I solved it by changing what was originally this line.

    <img id='img-0' src='/html/images/chico64.png' />

    to this

    <img id='img-0' src='http://".$_SERVER['SERVER_NAME']."/html/images/chico64.png' />

        
    answered by 02.05.2017 в 12:01