PHP利用COM组件将Word转换为PDF的实现方法
本实例详细解析了如何使用PHP将上传的Word文件转换为PDF格式,旨在为开发者提供参考与借鉴。
此前曾使用Office组件将Word转为HTML,如今需实现Word到PDF的转换。鉴于网上方案繁杂且不愿额外部署第三方软件,经数日探索,发现利用已安装的Office 2010中的COM组件,可在生成HTML的同时输出PDF,仅需微调原有少量代码即可达成目标。
$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);
上述代码灵感源自StackOverflow上的讨论: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的需求,务必注意文件路径必须为服务器绝对路径(如c:\www\1.txt),否则程序将无法正确读取文件。
期望上述内容能对从事PHP程序设计的读者提供实质性的帮助。