本文實例講述了php轉換上傳word文件為PDF的方法。分享給大家供大家參考,具體如下:
以前用過office組件轉換上傳文件word同時轉換為html文件,這次要將word文件轉換為pdf格式,網上的方法很多,也很麻煩,也不想在服務器上再安裝第三方軟件,花了好幾天的時間,終于在一個網站上,發現在了原來用COM組件,在轉換為html文件的同時,也能轉換為pdf格式,而自己服務器上已經安裝了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');//轉換成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);//轉換為pdf模式// quit the Word process$word->Quit(false);// clean upunset($word);
以上代碼的原始地址:http://stackoverflow.com/questions/5538584/convert-word-doc-docx-and-excel-xls-xlsx-to-pdf-with-php
我把以上的代碼做成了一個函數,代碼如下:
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程序設計有所幫助。
新聞熱點
疑難解答
圖片精選