php 上传word文件 Word文件转 PDF

以前用过office组件转换上传文件word同时转换为html文件,这次要将word文件转换为pdf格式,网上的方法很多,也很麻烦,也不想在服务器上再安装第三方软件,花了好几天的时间,终于在一个网站上,发现在了原来用COM组件,在转换为html文件的同时,也能转换为pdf格式,而自己服务器上已经安装了office2010,这样只需要改写一下以前的几行代码就可以,代码如下:

 1 $word = new COM("Word.Application") or die ("Could not initialise Object.");  
 2 // set it to 1 to see the MS Word window (the actual opening of the document)  
 3 $word->Visible = 0;  
 4 // recommend to set to 0, disables alerts like "Do you want MS Word to be the default .. etc"  
 5 $word->DisplayAlerts = 0;  
 6 // open the word 2007-2013 document   
 7 $word->Documents->Open('yourdocument.docx');//这个是绝对文件地址,如c:\www\1.txt这样的地址才通过  
 8 // save it as word 2003  
 9 $word->ActiveDocument->SaveAs('newdocument.doc');//转换成doc格式  
10 // convert word 2007-2013 to PDF  
11 $word->ActiveDocument->ExportAsFixedFormat('yourdocument.pdf', 17, false, 0, 0, 0, 0, 7, true, true, 2, true, true, false);//转换为pdf模式  
12 // quit the Word process  
13 $word->Quit(false);  
14 // clean up  
15 unset($word);

 

 

以上代码的原始地址:http://stackoverflow.com/questions/5538584/convert-word-doc-docx-and-excel-xls-xlsx-to-pdf-with-php

我把以上的代码做成了一个函数,代码如下:

 

 1 function word2pdf($lastfnamedoc,$lastfnamepdf)  
 2 {  
 3 $word = new COM("Word.Application") or die ("Could not initialise Object.");  
 4 // set it to 1 to see the MS Word window (the actual opening of the document)
 5 $word->Visible = 0;  
 6 // recommend to set to 0, disables alerts like "Do you want MS Word to be the default .. etc"
 7 $word->DisplayAlerts = 0;  
 8 // open the word 2007-2013 document 
 9 // $word->Documents->Open('3.docx');
10 // $wordname='D:/www/fa/3.doc';
11 $word->Documents->Open($lastfnamedoc);  
12 // save it as word 2003
13 //  $word->ActiveDocument->SaveAs('4.doc');
14 // convert word 2007-2013 to PDF
15 // $pdfname='D:/www/fa/3.pdf';
16 $word->ActiveDocument->ExportAsFixedFormat($lastfnamepdf, 17, false, 0, 0, 0, 0, 7, true, true, 2, true, true, false);  
17 // quit the Word process
18 $word->Quit(false);  
19 // clean up
20   unset($word);  
21 } 

 

我的是doc文件直接换pdf文件,代码是文件的地址我服务器的全是绝对地址,否则文件通不过

posted @ 2017-03-28 10:25  hoi123  阅读(309)  评论(0编辑  收藏  举报