html轉 PDF 用MPDF ,Word轉Html 純PHP的方法暫未找到Word直接轉PDF的方法 可以使用 LibreOffice 6.1 (Liunx,win) 皆可使用
文件又大轉換又要快就用 https://gitee.com/bandung/Execl_WordTOPDF.git 吧
Html轉成PDF
MPDF 6.0 下載地址
https://files.cnblogs.com/files/wlphp/mpdf.rar (復制到瀏覽器下載)
MPDF6.0 沒有用命名空間,7.0 開始使用
require APP_PATH.'Lib/ORG/mpdf/mpdf/mpdf.php'; try{ $mpdf=new \mPDF('zh-cn','A4', 0, '宋體', 0, 0); $html=file_get_contents("index.html"); $html = str_replace('margin-left:100px;', '', $html);// es //7.0 寫法 // $mpdf = new \mPDF(['utf-8', 'A4', 16, '', 10, 10, 15, 1]);
$mpdf->SetDisplayMode('fullpage'); $mpdf->autoScriptToLang = true; $mpdf->autoLangToFont = true; $mpdf->WriteHTML($html); $mpdf->Output(); //直接輸出到頁面
$fileName=APP_PATH.'File/'.uniqid().'.pdf'; //保存到文件
$mpdf->Output($fileName); }catch (Exception $e){ return false; }
樣式保存的還是可以的,但是要注意css 里面如果body 有左邊距,右邊距的都得刪掉,不然樣式就亂了,速度非常尷尬!!
Html轉word
生成的文件得是docx,不然PHPWod讀取會失敗
/** * @param $form * @param $to * html轉word文檔 */
public function htmlToWord($form,$to){ $path=APP_PATH."/File/old.html"; $isHave=file_exists($path); if(empty($isHave)){ $this->error("文件不存在!"); } $zhi=file_get_contents($path); //把左邊距替換掉
$str1 = str_replace('margin-left:100px;', '', $zhi);// es
echo $str1; $this->make($zhi); } private function make($html){ $wordname=uniqid().'.docx'; ob_start(); echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">'; @header('Content-type:application/word'); header('Content-Disposition: attachment; filename='.$wordname.''); @readfile($wordname); ob_flush();//每次執行前刷新緩存
flush(); }
Word轉Html
//如果用的框架支持命名空間
直接去github上 按照Composer 使用 https://github.com/PHPOffice/PHPWord
如果用的不支持命名空間 如TP3.1 還想用最新的PHPWord
下載Composer的命名
http://ys-c.ys168.com/601902945/TjRTkMn7W334U6IGMP65/vendor.rar.
require進來,其實用了這個的話laravel支持的composer安裝的庫基本也支持了
/** * @param $from * @return bool|string * word轉成Html文件 */
public function wordToHtml($from) { try{ $phpWord = \PhpOffice\PhpWord\IOFactory::load($from); $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, "HTML"); $fileName=uniqid().".html"; $xmlWriter->save(APP_PATH.'File/'.$fileName); return $fileName; }catch (Exception $e){ return false; } }
LibreOffice 轉換用法
自行百度安裝 200多MB
//速度很快執行完基本就轉換完成了,然后
exec("soffice --headless --convert-to html fuck2.doc php.html");
soffice --headless --convert-to html("想要轉換成的文件類型") fuck2.doc("源文件") php.html("轉換成的文件")
這個支持的類型就多了,可以直接把word轉成pdf,但是樣式很成問題。。。
!!!