【问题标题】:How I can convert an docx into pdf using phpWord template engine?如何使用 phpWord 模板引擎将 docx 转换为 pdf?
【发布时间】:2021-02-28 11:00:52
【问题描述】:

我制作了一个快速控制器,以测试在替换占位符值后如何将 docx 模板转换为 pdf。 .docx 是:

https://drive.google.com/file/d/14-Nh0L-R7ulHgpmTN5s-T0PilwWSsE7L/view?usp=sharing

我使用以下 laravel 代码将其从 docx 模板转换为 pdf


namespace App\Controllers\Services;

use App\Controllers\BaseController;
use Illuminate\Support\Facades\Response;

use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\PhpWord;

class Contract extends BaseController
{
    public function getContract()
    {
        $file = storage_path()."/contracts/contract.docx";
        $tmpFile = storage_path()."/contracts/output.pdf";

        $template = new TemplateProcessor($file);
        $template->setValue('COMP_NAME',"LOREM IPSUM INC");
        $template->setValue('ADDRESS',"Nowhere Str Tsastikistan");
        $template->saveAs($tmpFile);

        return Response::make("OK");
    }
}

但代码无法生成可读的pdf:https://drive.google.com/file/d/1wYsVrjwQNMN8r3sWZlOm6x7cNeja3ET0/view?usp=sharing

我还尝试生成一个 html,以便将其转换为 pdf:https://drive.google.com/file/d/1wYsVrjwQNMN8r3sWZlOm6x7cNeja3ET0/view?usp=sharing

但输出仍然看起来很垃圾。

因此,您知道如何将 docx 模板转换为 PDF,如果可以,如何使用内存文件而不是文件系统?

【问题讨论】:

    标签: php pdf docx laravel-5.7 phpword


    【解决方案1】:

    直接你不能。您需要先将其保存为 docx,然后再阅读并保存为 PDF:

    namespace App\Controllers\Services;
    
    use App\Controllers\BaseController;
    use Illuminate\Support\Facades\Response;
    
    use PhpOffice\PhpWord\TemplateProcessor;
    use PhpOffice\PhpWord\IOFactory;
    
    class Contract extends BaseController
    {
        public function getContract()
        {
            $file = storage_path()."/contracts/contract.docx";
            $tmpFile = storage_path()."/contracts/output.pdf";
            $outfile = storage_path()."/contracts/output.docx";
    
            $template = new TemplateProcessor($file);
            $template->setValue('COMP_NAME',"LOREM IPSUM INC");
            $template->setValue('ADDRESS',"Nowhere Str Tsastikistan");
            $template->saveAs($outfile);
    
            $phpWord = IOFactory::load($outfile);
            $phpWord->save($tmpFile,'PDF');        
    
            return Response::make("OK");
        }
    }
    

    我没有测试过的一个解决方案是使用php://tempphp://memory 以避免文件系统IO。

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 2019-02-18
      • 2020-08-14
      • 2017-07-06
      • 2021-02-28
      • 2018-08-13
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多