如何使用PHPWord将Word文档转换为PDF

问题描述 投票:0回答:3

我正在使用

PHPWord
创建 Microsoft Word 报告。我基本上从一个模板开始,填充字段并将其保存为文字报告。

我想将此报告转换为 pdf 文件。我尝试通过 PHPWord 加载生成的文档文件。但是,当我保存 pdf 文件时,格式全部丢失。

这是我正在使用的代码:

       require_once DOC_ROOT . '/vendor/phpoffice/phpword/bootstrap.php';

$path_to_tcpdf = DOC_ROOT . '/includes/plugins/TCPDF/'; // C:\xampp\htdocs\clients\corporate\includes\plugins\TCPDF
\PhpOffice\PhpWord\Settings::setPdfRendererPath($path_to_tcpdf);
\PhpOffice\PhpWord\Settings::setPdfRendererName('TCPDF');

$report_file_doc = DOC_ROOT . '/reports/business_report_U72900GJ2002PTC040573_68628.docx';
$report_file_pdf = DOC_ROOT . '/reports/business_report_U72900GJ2002PTC040573_68628.pdf';



$phpWord = \PhpOffice\PhpWord\IOFactory::load($report_file_doc); 
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord , 'PDF');

$xmlWriter->save($report_file_pdf);  

知道可能缺少什么吗?

谢谢

php pdf phpword
3个回答
17
投票

对于 PHPWord

v0.14

这是

TCPDF
渲染器的示例(在 v0.13 中已弃用):

// Require composer autoloder.
require __DIR__.'/vendor/autoload.php';

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Settings;

// Set PDF renderer.
// Make sure you have `tecnickcom/tcpdf` in your composer dependencies.
Settings::setPdfRendererName(Settings::PDF_RENDERER_TCPDF);
// Path to directory with tcpdf.php file.
// Rigth now `TCPDF` writer is depreacted. Consider to use `DomPDF` or `MPDF` instead.
Settings::setPdfRendererPath('vendor/tecnickcom/tcpdf');

$phpWord = IOFactory::load('document.docx', 'Word2007');
$phpWord->save('document.pdf', 'PDF');

这是

DomPDF
渲染器的示例:

// Require composer autoloder.
require __DIR__.'/vendor/autoload.php';

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Settings;

// Make sure you have `dompdf/dompdf` in your composer dependencies.
Settings::setPdfRendererName(Settings::PDF_RENDERER_DOMPDF);
// Any writable directory here. It will be ignored.
Settings::setPdfRendererPath('.');

$phpWord = IOFactory::load('document.docx', 'Word2007');
$phpWord->save('document.pdf', 'PDF');

2
投票

我不知道我是否正确,但您将文档另存为 HTML 内容。之后,您阅读 HTML 文件内容并借助 mPDF 或 tcPdf 或 fpdf 将内容写入 PDF 文件。

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

更多相关信息请点击这里


0
投票
<?php
require 'vendor/autoload.php';

use PhpOffice\PhpWord\IOFactory;
use Dompdf\Dompdf;
use Dompdf\Options;

try {
    // Word
    $phpWord = IOFactory::load('path/to/your/file.docx');

    // HTML
    $htmlWriter = IOFactory::createWriter($phpWord, 'HTML');
    ob_start();
    $htmlWriter->save('php://output');
    $html = ob_get_clean();

    // Dompdf
    $options = new Options();
    $options->set('defaultFont', 'Arial');
    $dompdf = new Dompdf($options);
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();

    // PDF
    $pdfOutput = $dompdf->output();
    file_put_contents('path/to/save/file.pdf', $pdfOutput);


} catch (Exception $e) {
    echo "error: " . $e->getMessage();
}
© www.soinside.com 2019 - 2024. All rights reserved.