php轉換上傳word文件爲PDF的方法【基於COM組件】

這篇文章主要介紹了php轉換上傳word文件爲PDF的方法,結合實例形式分析了php基於COM組件針對word文件的格式轉換相關操作技巧,需要的朋友可以參考下

本文實例講述了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 up
unset($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相關內容感興趣的讀者可查看本站專題:《php操作office文檔技巧總結(包括word,excel,access,ppt)》、《PHP數組(Array)操作技巧大全》、《PHP數據結構與算法教程》、《php程序設計算法總結》、《PHP數學運算技巧總結》、《php正則表達式用法總結》、《php字符串(string)用法總結》及《php常見數據庫操作技巧彙總

希望本文所述對大家PHP程序設計有所幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章