2012-09-04 34 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