从PHPWord生成的.docx生成PDF

时间:2015-10-12 14:53:46

标签: php pdf docx phpword

我正在使用.docx从模板创建PHPWord个文件。它工作正常但现在我想将生成的文件转换为PDF

首先,我尝试将tcpdfPHPWord

结合使用
$wordPdf = \PhpOffice\PhpWord\IOFactory::load($filename.".docx");

\PhpOffice\PhpWord\Settings::setPdfRendererPath(dirname(__FILE__)."/../../Office/tcpdf");
\PhpOffice\PhpWord\Settings::setPdfRendererName('TCPDF');

$pdfWriter = \PhpOffice\PhpWord\IOFactory::createWriter($wordPdf , 'PDF');
if (file_exists($filename.".pdf")) unlink($filename.".pdf");
$pdfWriter->save($filename.".pdf");  

但是当我尝试加载文件以将其转换为PDF时,我在加载文件时遇到以下异常

  

致命错误:未捕获的异常'BadMethodCallException',消息'无法在Section中添加PreserveText。'

经过一番研究后,我发现其他一些人也有这个错误(phpWord - Cannot add PreserveText in Section

修改

  

在尝试了一些后,我发现,Exception仅在我的文档中有一些mail merge fields时才会出现。删除后,Exception不再出现,但转换后的PDF文件看起来很糟糕。所有样式信息都消失了,我无法使用结果,因此需要替代方案。



我考虑使用其他方式生成PDF,但我只能找到4种方式:

  1. 使用OpenOffice - 不可能,因为我无法在服务器上安装任何软件。提及here的方式也不起作用,因为我的主机(Strato)使用SunOS作为操作系统,这需要Linux
  2. 使用phpdocx - 我没有任何预算需要支付,而且演示无法创建PDF
  3. 使用PHPLiveDocx - 这有效,但每天限制250份文件,每小时20份,我必须一次转换300份文件,甚至可能每天转换多次
  4. 使用PHP-Digital-Format-Convert - 输出看起来比使用PHPWordtcpdf更好,但仍然无法使用,因为图像丢失,而且大多数(不是全部! )样式
  5. 是否有第五种生成PDF的方法?或者是否有任何解决方案可以使生成的PDF文档看起来不错?

4 个答案:

答案 0 :(得分:0)

我使用Gears/pdf将phpword生成的docx文件转换为PDF:

$success = Gears\Pdf::convert(
            'file_path/file_name.docx',
            'file_path/file_name.pdf');

答案 1 :(得分:0)

您要先取消链接PDF文件,然后再保存它,而且还必须取消DOCX文档的链接,而不是PDF文件的链接。

尝试一下。

$pdfWriter = \PhpOffice\PhpWord\IOFactory::createWriter($wordPdf , 'PDF');    
$pdfWriter->save($filename.".pdf");
unlink($wordPdf);

答案 2 :(得分:0)

尝试一下:

// get the name of the input PDF
$inputFile = "C:\\PHP\\Test1.docx";

// get the name of the output MS-WORD file
$outputFile = "C:\\PHP\\Test1.pdf";

try
    {
    $oLoader = new COM("easyPDF.Loader.8");
    $oPrinter = $oLoader->LoadObject("easyPDF.Printer.8");
    $oPrintJob = $oPrinter->PrintJob;
    $oPrintJob->PrintOut ($inputFile, $outputFile);
    print "Success";
    }


catch(com_exception $e)
    {
    Print "error code".$e->getcode(). "\n";
    print $e->getMessage();
    }

答案 3 :(得分:-1)

我不认为我是对的.. 您将文档另存为HTML内容

  

$ objWriter = \ PhpOffice \ PhpWord \ IOFactory :: createWriter($ phpWord,' HTML');

在您阅读HTML文件内容之后,在 mPDF 或tcPdf或fpdf的帮助下将内容写为PDF文件。