本文實例講述了php轉(zhuǎn)換上傳word文件為PDF的方法。分享給大家供大家參考,具體如下:
以前用過office組件轉(zhuǎn)換上傳文件word同時轉(zhuǎn)換為html文件,這次要將word文件轉(zhuǎn)換為pdf格式,網(wǎng)上的方法很多,也很麻煩,也不想在服務器上再安裝第三方軟件,花了好幾天的時間,終于在一個網(wǎng)站上,發(fā)現(xiàn)在了原來用COM組件,在轉(zhuǎn)換為html文件的同時,也能轉(zhuǎn)換為pdf格式,而自己服務器上已經(jīng)安裝了office2010,這樣只需要改寫一下以前的幾行代碼就可以,代碼如下:
$word = new COM("Word.Application") or die ("Could not initialise Object."); // set it to 1 to see the MS Word window (the actual opening of the document) $word->Visible = 0; // recommend to set to 0, disables alerts like "Do you want MS Word to be the default .. etc" $word->DisplayAlerts = 0; // open the word 2007-2013 document $word->Documents->Open('yourdocument.docx');//這個是絕對文件地址,如c:\www\1.txt這樣的地址才通過 // save it as word 2003 $word->ActiveDocument->SaveAs('newdocument.doc');//轉(zhuǎn)換成doc格式 // convert word 2007-2013 to PDF $word->ActiveDocument->ExportAsFixedFormat('yourdocument.pdf', 17, false, 0, 0, 0, 0, 7, true, true, 2, true, true, false);//轉(zhuǎn)換為pdf模式 // quit the Word process $word->Quit(false); // clean up unset($word);
以上代碼的原始地址:http://stackoverflow.com/questions/5538584/convert-word-doc-docx-and-excel-xls-xlsx-to-pdf-with-php
我把以上的代碼做成了一個函數(shù),代碼如下:
function word2pdf($lastfnamedoc,$lastfnamepdf) { $word = new COM("Word.Application") or die ("Could not initialise Object."); // set it to 1 to see the MS Word window (the actual opening of the document) $word->Visible = 0; // recommend to set to 0, disables alerts like "Do you want MS Word to be the default .. etc" $word->DisplayAlerts = 0; // open the word 2007-2013 document // $word->Documents->Open('3.docx'); // $wordname='D:/www/fa/3.doc'; $word->Documents->Open($lastfnamedoc); // save it as word 2003 // $word->ActiveDocument->SaveAs('4.doc'); // convert word 2007-2013 to PDF // $pdfname='D:/www/fa/3.pdf'; $word->ActiveDocument->ExportAsFixedFormat($lastfnamepdf, 17, false, 0, 0, 0, 0, 7, true, true, 2, true, true, false); // quit the Word process $word->Quit(false); // clean up unset($word); }
我的是doc文件直接換pdf文件,代碼是文件的地址我服務器的全是絕對地址,否則文件通不過!
更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php操作office文檔技巧總結(jié)(包括word,excel,access,ppt)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設計算法總結(jié)》、《PHP數(shù)學運算技巧總結(jié)》、《php正則表達式用法總結(jié)》、《php字符串(string)用法總結(jié)》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。