繁体   English   中英

将带图像的html转换为ms.word

[英]Convert html with image to ms.word

我有如下的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.包含的doc文件中没有图像

通常,header()函数只重定向并强制下载特定的应用程序,但带有图像的word文件无法正常工作它只是从源读取而不是永久的doc文件...

尝试在.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, '">';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM