dfware / html2pdf
提供HTML到PDF和PHP到PDF转换的支持
Requires
- yiisoft/yii2: ~2.0.14
Requires (Dev)
- phpunit/phpunit: 4.8.27|^5.0|^6.0
This package is auto-updated.
Last update: 2024-09-27 20:00:21 UTC
README
安装此扩展的首选方法是通过 composer。
运行
composer require dfware/html2pdf
或者
"dfware/html2pdf": "*"
将以下内容添加到你的 composer.json 的 require 部分。
注意:你需要根据你选择的转换器,单独安装用于实际HTML到PDF转换的软件。
用法
此扩展提供HTML到PDF和PHP到PDF转换的支持。它允许通过HTML和通过渲染PHP模板来组合PDF文件。
扩展功能聚合到 \yii2tech\html2pdf\Manager
应用程序组件中。应用程序配置示例
<?php return [ 'components' => [ 'html2pdf' => [ 'class' => 'yii2tech\html2pdf\Manager', 'viewPath' => '@app/views/pdf', 'converter' => 'wkhtmltopdf', ], ], ... ];
对于简单的转换,你可以使用 \yii2tech\html2pdf\Manager::convert()
和 \yii2tech\html2pdf\Manager::convertFile()
方法
<?php $html = <<<HTML <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p>Simple Content</p> </body> </html> HTML; // create PDF file from HTML content : Yii::$app->html2pdf ->convert($html) ->saveAs('/path/to/output.pdf'); // convert HTML file to PDF file : Yii::$app->html2pdf ->convertFile('/path/to/source.html') ->saveAs('/path/to/output.pdf');
实际的转换结果由所使用的特定转换器决定。你可以使用 \yii2tech\html2pdf\Manager::$converter
属性进行转换器设置。
提供了一些内置的转换器
- yii2tech\html2pdf\converters\Wkhtmltopdf - 使用 wkhtmltopdf 工具进行转换。
- yii2tech\html2pdf\converters\Dompdf - 使用 dompdf 库进行转换。
- yii2tech\html2pdf\converters\Mpdf - 使用 mpdf 库进行转换。
- yii2tech\html2pdf\converters\Tcpdf - 使用 TCPDF 库进行转换。
- yii2tech\html2pdf\converters\Callback - 使用自定义PHP回调进行转换。
注意!大多数提供的转换器需要安装额外的软件,这些软件不是由其扩展默认提供的。你将需要手动安装它,一旦你决定使用哪个转换器。请参阅特定的转换器类以获取更多详细信息。
你可以通过 convert()
或 convertFile()
方法的第二个参数指定转换选项
<?php Yii::$app->html2pdf ->convertFile('/path/to/source.html', ['pageSize' => 'A4']) ->saveAs('/path/to/output.pdf');
你可以在 \yii2tech\html2pdf\Manager
级别设置默认的转换选项
<?php return [ 'components' => [ 'html2pdf' => [ 'class' => 'yii2tech\html2pdf\Manager', 'viewPath' => '@app/pdf', 'converter' => [ 'class' => 'yii2tech\html2pdf\converters\Wkhtmltopdf', 'defaultOptions' => [ 'pageSize' => 'A4' ], ] ], ], ... ];
注意:可用的实际转换选项列表取决于将要使用的特定转换器。
模板使用
你可以通过渲染PHP模板(视图文件)来创建PDF文件,这些文件组合HTML输出。此类文件作为常规视图文件处理,允许传递参数和布局包装。用于此的方法是 \yii2tech\html2pdf\Manager::render()
<?php Yii::$app->html2pdf ->render('invoice', ['user' => Yii::$app->user->identity]) ->saveAs('/path/to/output.pdf');
你可以为模板使用共享布局,这可以通过 \yii2tech\html2pdf\Manager::$layout
设置。
在每个渲染过程中,视图都在 \yii2tech\html2pdf\Template
对象的上下文中工作,这可以用来在视图文件中调整布局或PDF转换选项
<?php /* @var $this \yii\web\View */ /* @var $context \yii2tech\html2pdf\Template */ /* @var $user \app\models\User */ $context = $this->context; $context->layout = 'layouts/payment'; // use specific layout for this template // specify particular PDF conversion for this template: $context->pdfOptions = [ 'pageSize' => 'A4', // ... ]; ?> <h1>Invoice</h1> <p>For: <?= $user->name ?></p> ...