php转换上传word文件为PDF的方法【基于COM组件】

yipeiwu_com6年前PHP代码库

本文实例讲述了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程序设计有所帮助。

相关文章

利用PHP如何统计Nginx日志的User Agent数据

利用PHP如何统计Nginx日志的User Agent数据

前言 即将用到爬虫,于是打算收集一下User Agent(UA)数据。接着马上想到自己网站的访问日志不就是现成的优质数据源吗?于是愉快的决定写个脚本统计一下Nginx访问日志中的UA信息...

PHP基于自定义类随机生成姓名的方法示例

本文实例讲述了PHP基于自定义类随机生成姓名的方法。分享给大家供大家参考,具体如下: 自定义类rndChinaName.class.php: <?php Class r...

PHP 5.0对象模型深度探索之属性和方法

可以联用->,如果一个对象的属性包含了一个对象,你可以使用两个->运算符来得到内部对象的属性. 你甚至可以用双重引用的字符串来放置这些表达式. 下面的例子中,对象Ho...

PHP常见字符串操作函数与用法总结

本文实例讲述了PHP常见字符串操作函数与用法。分享给大家供大家参考,具体如下: 一、字符串的格式化 1、字符串的格式化 trim()函数可以去除字符串的开始位置和结束位置的空格,并将结果...

php foreach 参数强制类型转换的问题

所以,为了防止这样的信息出现,我使用foreach的时候,都会把参数进行强制类型转换,形势如下: foreach((array)$arr as $key => $value); 这...