Frage

In my xampp htdocs folder I got two files: An image and a php script. I tried to create a word document with an image. This is the code I used:

$image = 'img.png';
$imageData = base64_encode(file_get_contents($image));
$src = 'data: '. mime_content_type($image).';base64,'.$imageData;

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

echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<h1>bla</h1>";
echo "<b>My first document</b>";
echo '<img src="',$src,'">';
echo "</body>";
echo "</html>";

Well actually I don't have Microsoft Word installed on my PC but it should work with Libre Office too. I also tried http://www.viewdocsonline.com but it didn't work. First I tried it with a way too big image and I thought that was causing the problem but it doesn't even work with a small image. The File is just loading all the time but can't be opened. The file size seems to be right - it's 52kb - so the image seems to be in the document.

But what could cause the error? How to find out and how to debug?

War es hilfreich?

Lösung

Word can't read Html, at least not if you specify the .doc extension.

You should use a Docx generator if you want to work with the latest version of Word (since 2007), or doc if you want to create a document readable from word 2003.

http://www.phpdocx.com/ works great for that (https://phpword.codeplex.com/ too, but isn't well supported)

Andere Tipps

Alright – with the help of edi9999 and his awesome library I was able to create a docx document with my text variables and my image.

Here is the code I used: Javascript:

/*** importing all necessary scripts ***/
<script type="text/javascript" src="docxtemplater-master/libs/base64.js"></script>
<script type="text/javascript" src="docxtemplater-master/libs/jszip/jszip.js"></script>
<script type="text/javascript" src="docxtemplater-master/libs/jszip/jszip-load.js"></script>
<script type="text/javascript" src="docxtemplater-master/libs/jszip/jszip-inflate.js"></script>
<script type="text/javascript" src="docxtemplater-master/js/docxgen.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
/*** my JSON object with the variables for setTemplateVars() ***/
<script type="text/javascript">
            var JSON = { "articles": [
                { "title": "test-title", "first_name": "Paul", "last_name": "Alan", "phone": "555-nose", "fileName": "abc" },
                { "title": "test-title2", "first_name": "John", "last_name": "Doe", "phone": "555-abcd", "fileName": "bcd" }
            ]
            };
</script>
<script type="text/javascript">
var xhrDoc = new XMLHttpRequest();
xhrDoc.open('GET', 'Example.docx', true);
if (xhrDoc.overrideMimeType) {
    xhrDoc.overrideMimeType('text/plain; charset=x-user-defined');
}

xhrDoc.onreadystatechange = function (e) {
    if (this.readyState == 4 && this.status == 200) {
       window.docData = this.response;
    }
};
xhrDoc.send();


var xhrImage = new XMLHttpRequest();
xhrImage.open('GET', 'dog.jpg', true);
            if (xhrImage.overrideMimeType) {
                xhrImage.overrideMimeType('text/plain; charset=x-user-defined');
            }

            xhrImage.onreadystatechange = function (e) {
                if (this.readyState == 4 && this.status == 200) {
                    window.imgData = this.response;
                }
            };
            xhrImage.send();

generateDoc = function (docData) {
            var doc = new DocxGen(docData)

            doc.setTemplateVars(
                { "first_name": JSON.articles[0]["first_name"],
                    "last_name": JSON.articles[0]["last_name"],
                    "phone": JSON.articles[0]["phone"],
                    "fileName": JSON.articles[0]["fileName"]
                }
              )
            doc.applyTemplateVars()
            imageList = doc.getImageList()
            console.log(imageList);
            doc.setImage(imageList[0].path, imgData);
            doc.output()
        }

</script>

HTML:

<button class="download_doc" onClick="generateDoc(window.docData)">download word docx with image</button>

Word template:

{phone}
Product name: {first_name}
Product reference : {last_name}
*in the middle is an image*
Blabla: {fileName}
*here is another image*

Well the content makes no sense of course but it works. But still there are some questions left (especially to edi9999 and I hope you could answer them for me please :) ):

1. The images has to be on the same server and you have to use a relative path, right? Link's didn't seem to work. I tried xhrImage.open('GET', 'http://link-to-an-image.com/image.jpg', true); but without success. Is it somehow possible to use external links to images?

2. There is an 304 error ("Not modified") in the console behind the GET Requests. Is that normal?

3. Does the image that shall replace the image in the word document have to be the same size (or at least the same aspect ratio) or are there any option variables that could make the replacement more flexible? For example: if I wanna have the image displayed over the full width in the word document and got a replacement image with a different aspect ratio, would it be possible to keep that aspect ratio and just increase the height of the image in the word document?

4. How to use more than one image for replacement? With xhrImage.open('GET', 'dog.jpg', true); only one image is opened. How to add more images to the "imageList" and how to determine the order?

5. The library is based on prototype and normally it's causing errors to use both (jQuery + Prototype) frameworks in one document. But I tried to use a jQuery function and it worked. Have you ever had any problems with using your library and jQuery in one document?

Found another solution: With this library: https://github.com/PHPOffice/PHPWord

it's quite easy to create a docx file with formatted text and an image.

Here's the code that worked for me:

require_once('PHPWord-master/Classes/PHPWord.php');
$PHPWord = new PHPWord();
$section = $PHPWord->createSection();
$my_text='Hello world! I am formatted.';
$section->addText($my_text, array('name'=>'Tahoma', 'size'=>16, 'bold'=>true));
$section->addText(''); // adding some white space because the marginTop attribute of the image doesn't work
$filename="Jellyfish.jpg";
$size = getimagesize($filename);
$width="560"; //full width in a word document if image is 96dpi
$height=560/intval($size[0])*intval($size[1]);
$section->addImage(
$filename,
array(
    'width' => $width,
    'height' => $height,
    'align' => 'center'
)
);
$section->addText('blabla');
$filename="dog.jpg";
$size = getimagesize($filename);
$height=560/intval($size[0])*intval($size[1]);
$section->addImage(
$filename,
array(
    'width' => $width,
    'height' => $height,
    'align' => 'center'
)
);
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('helloWorld.docx');
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top