我有如下的html代码:
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;
?>
问题:
当我转换它时,我得到了html2word.doc,但我只能从html文件中获得所有文本。对于html文件中的图像,我无法获得它,它缺少图像。所以我想从html和图像中获取所有数据。我该如何解决这个问题?谁来帮我,谢谢。
我一周前处理过这个脚本(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.您需要连接互联网才能显示图像
2.删除(或服务器不可用)图像将使其在所有生成的文档中不可用
3.包含的文档文件中没有图像
通常,header()函数只重定向并强制下载特定的应用程序,但带有图像的word文件无法正常工作,它只是从源读取而不是永久的文档文件。。。
尝试在.jpg
或.png
之后添加一个随机查询,例如:example.com/photo.jpg?ts=12345
。
我发现Word支持数据uri,您可以将图像转换为base64。
// A few settings
$image = 'cricci.jpg';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
// Echo out a sample image
echo '<img src="', $src, '">';