2012-09-04 35 views
1

我有如下的HTML代码:与图像将HTML转换成ms.word

file.html

<body> 
    <h1>TEST</h1> 
    <p>this is test</p> 
    <table> 
     <tr> 
      <td>1</td> 
      <td>2</td> 
     </tr> 
     <tr> 
      <td>3</td> 
      <td>4</td> 
     </tr> 
     <tr> 
      <td>5</td> 
      <td><img src="../../../wamp/www/html2doc/SGEPP.jpg"></td> 
     </tr> 
    </table> 

html2doc.php

<?php 
     $handle = fopen("doc2html.html","r"); 
     $contents = ''; 
       while (!feof($handle)) { 
       $contents .= fread($handle, 8192); 
       } 
       header("Content-type: application/vnd.ms-word"); 
       header("Content-Disposition: attachment;Filename=html2word.doc"); 
       echo $contents; 
?> 

概率lems:

当我转换它时,我得到html2word.doc,但我只能从html文件中获取所有文本。对于html文件中的图像我无法得到它,它缺少图像。所以我想要得到所有来自html和图像的数据也。我该如何解决这个问题?任何人都可以帮助我,谢谢。

+2

您不能以这种方式将html转换为word文档。您所做的只是输出带有.doc扩展名的html文件,而word会为您解释。编写包含嵌入式图像等的文档文档是一个不平凡的问题。您可能会发现http://www.phplivedocx.org/或http://stackoverflow.com/questions/188452/reading-writing-a-ms-word-file-in-php有帮助。 – mjec

+0

我想添加@mjec注释,您忘记在'img'元素的末尾添加'/' ''是正确的html – shnisaka

+0

如果您可以使用Java,那么您可以使用docx4j将XHTML到DOCX。 – JasonPlutext

回答

2

我在一个星期前处理了这个脚本(html2doc)。 因此请注意,您不要将图像保存在*.doc文件中。它们只能像链接到服务器一样插入。所以解决方法是在src标签中写绝对路径。你可以逐行阅读你的HTML页面。因此,请尝试在每行中查找您的img标签,并用新的替换src。

$handle = fopen("html2doc.html","r"); 
$contents = ''; 
while (!feof($handle)) { 
    $str = fread($handle, 8192); 
    $str = str_replace('src="../../../','src="http://'.$_SERVER['SERVER_NAME'].'/path/to/imgages/',$str); 
    $contents .= $str; 
} 
header("Content-type: application/vnd.ms-word"); 
header("Content-Disposition: attachment;Filename=html2word.doc"); 
echo $contents; 



// Output: 
<body> 
<h1>TEST</h1> 
<p>this is test</p> 
<table> 
    <tr> 
     <td>1</td> 
     <td>2</td> 
    </tr> 
    <tr> 
     <td>3</td> 
     <td>4</td> 
    </tr> 
    <tr> 
     <td>5</td> 
     <td><img src="http://www.temp.com/path/to/imgages/wamp/www/html2doc/SGEPP.jpg" /></td> 
    </tr> 
</table> 

所以现在图像有路径,MS Word可以很好地读取并显示图像。但要记住:
1 u需要互联网连接来显示图像
2.删除(或不可用的服务器)图像会让他们在所有生成的文档不可
3.存在doc文件没有图像包含

+0

有没有办法将图像插入Word文档?我试图base64编码图像在这里:http://stackoverflow.com/questions/21308421/why-cant-my-php-generated-word-document-be-打开,但不幸的是它没有工作:( – user2718671

+0

到目前为止据我所知,只有在docx格式可能是。 – StasGrin

0

一般而言,header()函数只能重定向并强制下载特定的应用程序,但与图片的Word文件正确,它只是从源不是一个永久性的doc文件读取不工作... .jpg.png等之后

0

尝试添加随机查询例如: example.com/photo.jpg?ts=12345