PHP中利用MS Office将docx文档以更近似样式转为PDF

{{ time }}

PHP中, 将word文档转为PDF的方法有很多, 比如OpenOffice和LibreOffice等, 但这两种生成的PDF与原word文档差别较大;

目前找到转换效果比较好是用微软的Office来转.

具体步骤如下:

Step1 在Windows下配置好PHP环境, 如Apache+PHP, 可以使用集成环境, 如XAMPP

Step2 在Windows下安装Micrsoft Office 2010/2019

a. 其他版本Office暂未测试

b. 安装Microsoft Office 2007须另安装一个包: Microsoft Save as PDF

c. 也可使用WPS专业版, 但效果可能逊于MS Office

Step3 给PHP安装php_com_dotnet扩展

在php.ini中加入如下代码

extension=php_com_dotnet.dll

并且找到

com.allow_dcom = true
# 上面这行是true, 且去掉前面的分号

Step4 使用如下代码进行转换

<?php

word2pdf();
function word2pdf()
{
    $filenamedoc = dirname(__FILE__) . "/index.docx";
    $filenamepdf = dirname(__FILE__) . "/index.pdf";

    // 或者 
    // $dd = $word = new COM("KWPS.Application") or die("Could not initialise Object.");
    $dd = $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($filenamedoc);
    // save it as word 2003
    // convert word 2007-2013 to PDF

    //判断要生成的文件名是否存在
    if (file_exists($filenamepdf)) {
        //存在就删除
        unlink($filenamepdf);
    }
    $word->ActiveDocument->ExportAsFixedFormat($filenamepdf, 17, false, 0, 0, 0, 0, 7, true, true, 2, true, true, false);
    // quit the Word process
    $word->Quit(false);
    // clean up
    unset($word);
    if (!function_exists('read_pdf')) {
        header('Content-type: application/pdf');
        header('filename=' . $filenamepdf);
        readfile($filenamepdf);
        read_pdf('Python_study.pdf');
    }
    echo 'ok';
}

当然, 要在同一目录下放一个index.docx的word文件