vestnik / phpwkhtmltopdf
一个简洁的PHP包装器,围绕wkhtmltopdf,具有易于使用和清晰的OOP接口
Requires
- php: >=5.0.0
- mikehaertl/php-shellcommand: ^1.0.2
- mikehaertl/php-tmpfile: ^1.0.0
README
PHP WkHtmlToPdf提供了一个简单且清晰的接口,以简化使用wkhtmltopdf(wkhtmltopdf)创建PDF和图像。 必须安装并确保系统上的wkhtmltopdf和可选的wkhtmltoimage命令正常工作。 有关详细信息,请参阅下面的部分。
安装
通过composer安装包
composer require mikehaertl/phpwkhtmltopdf
确保在代码库的某个位置包含composer的自动加载器。
单页PDF
use mikehaertl\wkhtmlto\Pdf; // You can pass a filename, a HTML string or an URL to the constructor $pdf = new Pdf('/path/to/page.html'); // On some systems you may have to set the path to the wkhtmltopdf executable // $pdf->binary = 'C:\...'; if (!$pdf->saveAs('/path/to/page.pdf')) { echo $pdf->getError(); }
带目录和封面页的多页PDF
use mikehaertl\wkhtmlto\Pdf; $pdf = new Pdf; $pdf->addPage('/path/to/page.html'); $pdf->addPage('<html>....</html>'); $pdf->addPage('http://www.example.com'); // Add a cover (same sources as above are possible) $pdf->addCover('/path/to/mycover.html'); // Add a Table of contents $pdf->addToc(); // Save the PDF $pdf->saveAs('/path/to/report.pdf'); // ... or send to client for inline display $pdf->send(); // ... or send to client as file download $pdf->send('report.pdf'); // ... or you can get the raw pdf as a string $content = $pdf->toString();
创建图像
use mikehaertl\wkhtmlto\Image; // You can pass a filename, a HTML string or an URL to the constructor $image = new Image('/path/to/page.html'); $image->saveAs('/path/to/page.png'); // ... or send to client for inline display $image->send(); // ... or send to client as file download $image->send('page.png');
设置选项
wkhtmltopdf
shell命令接受不同类型的选项
- 全局选项(例如,设置文档的DPI或默认页面选项)
- 页面选项(例如,为页面提供自定义CSS文件)
- 目录选项(例如,设置目录标题)
请参阅wkhtmltopdf -H
以获取完整说明。所有选项都作为数组传递,例如
$options = array( 'no-outline', // option without argument 'encoding' => 'UTF-8', // option with argument // Option with 2 arguments 'cookie' => array('name'=>'value'), // Repeatable options with single argument 'run-script' => array( '/path/to/local1.js', '/path/to/local2.js', ), // Repeatable options with 2 arguments 'replace' => array( '{page}' => $page++, '{title}' => $pageTitle, ), );
可以将选项传递给多个PDF方法
$pdf = new Pdf($globalOptions); // Set global PDF options $pdf->setOptions($globalOptions); // Set global PDF options (alternative) $pdf->addPage($page, $pageOptions); // Add page with options $pdf->addCover($page, $pageOptions); // Add cover with options $pdf->addToc($tocOptions); // Add TOC with options
注意,您也可以在全局PDF选项中使用页面选项。
wkhtmltopdf
将它们应用于所有页面,除非您在添加页面时覆盖它们。
对于wkhtmltoimage
,只有一组选项
$image = new Image($options); // Set image options $image->setOptions($options); // Set image options (alternative)
包装器选项
包装器本身可以通过以下选项进行配置,这些选项可以传递给构造函数或通过setOptions()
设置
binary
:wkhtmltopdf
命令的完整路径。默认为wkhtmltopdf
,假定该命令位于您的shell搜索路径中。commandOptions
:传递给https://github.com/mikehaertl/php-shellcommand的选项。tmpDir
:tmp目录的路径。默认为PHP临时目录。ignoreWarnings
:是否忽略任何错误,如果仍创建了PDF文件。默认为false
。version9
:是否使用较旧版本的wkhtmltopdf的命令行语法。
除了上述的binary
、commandOptions
、tmpDir
和ignorWarnings
选项之外,Image
类还有一个type
选项
type
:图像类型。默认为png
。您也可以使用jpg
或bmp
。
commandOptions
可以用来为wkhtmltopdf
设置环境变量。例如,如果您想传递UTF-8编码的参数,可能需要设置LANG
环境变量
$pdf = new Pdf(array( 'commandOptions' => array( 'procEnv' => array( // Check the output of 'locale' on your system to find supported languages 'LANG' => 'en_US.utf-8', ), ), ));
错误处理
send()
、saveAs()
和toString()
在发生错误时将返回false
。在这种情况下,详细的错误消息可以通过getError()
获取。
if (!$pdf->send()) { throw new Exception('Could not create PDF: '.$pdf->getError()); } $content = $pdf->toString(); if ($content === false) { throw new Exception('Could not create PDF: '.$pdf->getError()); }
针对Windows用户的说明
如果您使用双引号("
)或百分号(%
)作为选项值,它们可能会被转换为空格。在这种情况下,您可以在command中禁用参数转义。还有两个有趣的选项可以用于proc_open()
,您可能想使用它们。
$pdf = new Pdf(array( 'commandOptions' => array( 'escapeArgs' => false, 'procOptions' => array( // This will bypass the cmd.exe which seems to be recommended on Windows 'bypass_shell' => true, // Also worth a try if you get unexplainable errors 'suppress_errors' => true, ), ), ... ));
但这时您必须自己注意适当的参数转义。在某些情况下,可能需要在参数值周围添加额外的双引号。
我还发现,某些选项在Windows上不起作用(使用wkhtmltopdf 0.11 rc2进行测试),例如下面示例中使用的user-style-sheet
选项。
wkhtmltopdf的安装
建议您从他们的网站下载最新的wkhtmltopdf
http://wkhtmltopdf.org/downloads.html
这些版本应该可以直接运行。
如果您由于某些原因无法这样做,您可能会遇到wkhtmltopdf的动态链接版本的问题。例如,在Ubuntu 12.04 LTS上安装wkhtmltopdf包时,会出现这种情况。它将可以工作,但为了使用所有功能,它需要一个通常不在无头web服务器上可用的X服务器。
因此,我们提供了两种基于Xvfb的解决方案。您可以选择使用
- 内置的Xvfb支持或
- 独立的Xvfb服务器。
两者都需要在系统上安装Xvfb包,两者也有一些缺点。
内置Xvfb支持
这会将每个对wkhtmltopdf
的调用包裹在xvfb-run中。xvfb-run
将在没有完整X会话的所有开销的情况下运行任何给定的命令。这个解决方案的缺点是,每次创建每个PDF时仍然会启动一个新的会话,这将在您的CPU上创建相当多的额外负载。因此,这个设置只建议用于低频率网站。
要使用内置支持,您必须在commandOptions
中设置enableXvfb
。还有一些可以设置的选项。
$pdf = new Pdf(array( // Explicitly tell wkhtmltopdf that we're using an X environment 'use-xserver', // Enable built in Xvfb support in the command 'commandOptions' => array( 'enableXvfb' => true, // Optional: Set your path to xvfb-run. Default is just 'xvfb-run'. // 'xvfbRunBinary' => '/usr/bin/xvfb-run', // Optional: Set options for xfvb-run. The following defaults are used. // 'xvfbRunOptions' => '--server-args="-screen 0, 1024x768x24"', ), ));
独立Xvfb
最好启动一个Xvfb进程一次,然后将其用于所有的PHP请求(感谢Larry Williamson提供原始想法)。这需要您有权访问您的机器,因为您需要为该进程添加一个启动脚本。我们提供了一个Ubuntu(感谢eusonlito)的示例init脚本。您可以将它放在/etc/init.d/xvfb
,并用update-rc.d xvfb defaults 10
添加到启动文件中。
如果您的系统基于systemd,这个配置应该有帮助(感谢nkm)。
如果您的Xvfb
进程正在运行,您只需告诉类使用此X显示进行渲染即可。这是通过一个环境变量完成的。
$pdf = new Pdf(array( 'use-xserver', 'commandOptions' => array( // You can change ':0' to whatever display you pick in your daemon script 'procEnv' => array( 'DISPLAY' => ':0' ), ), ));
完整示例
对我来说,wkhtmltopdf
似乎在关闭智能缩放时可以创建最佳结果。但那时我遇到了缩放问题,在将所有边距设置为零并通过CSS添加边距后消失。您还可以在CSS中使用cm
或in
,因为这更适合打印样式。
use mikehaertl\wkhtmlto\Pdf; // Create a new Pdf object with some global PDF options $pdf = new Pdf(array( 'no-outline', // Make Chrome not complain 'margin-top' => 0, 'margin-right' => 0, 'margin-bottom' => 0, 'margin-left' => 0, // Default page options 'disable-smart-shrinking', 'user-style-sheet' => '/path/to/pdf.css', )); // Add a page. To override above page defaults, you could add // another $options array as second argument. $pdf->addPage('/path/to/demo.html'); $pdf->send();
demo.html
<!DOCTYPE html> <html> <head> </head> <body> <div id="print-area"> <div id="header"> This is an example header. </div> <div id="content"> <h1>Demo</h1> <p>This is example content</p> </div> <div id="footer"> This is an example footer. </div> </div> </body> </html>
pdf.css
/* Define page size. Requires print-area adjustment! */ body { margin: 0; padding: 0; width: 21cm; height: 29.7cm; } /* Printable area */ #print-area { position: relative; top: 1cm; left: 1cm; width: 19cm; height: 27.6cm; font-size: 10px; font-family: Arial; } #header { height: 3cm; background: #ccc; } #footer { position: absolute; bottom: 0; width: 100%; height: 3cm; background: #ccc; }
链接
还可以查看我的php-pdftk包装器,它将pdftk的完整功能带到了PHP中。