parejaleonardo/phpwkhtmltopdf

Fork:一个简单的PHP包装器,围绕wkhtmltopdf,具有易于使用和干净的OOP接口

2.4.6 2019-07-30 09:26 UTC

README

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

PHP WkHtmlToPdf提供了简单、干净的接口,用于通过wkhtmltopdf创建PDF和图像。 必须安装并启用系统上的wkhtmltopdf和可选的-wkhtmltoimage命令。 有关详细信息,请参阅下面的部分。

对于Windows系统,请确保在二进制选项中设置wkhtmltopdf.exe的路径。或者,您可以将wkhtmltopdf "bin"目录添加到系统PATH变量中,以便Windows CMD可以使用wkhtmltopdf命令。

安装

通过composer安装包

composer require mikehaertl/phpwkhtmltopdf

确保您在代码库的某个位置包含composer 自动加载器

示例

单页PDF

use mikehaertl\wkhtmlto\Pdf;

// You can pass a filename, a HTML string, an URL or an options array 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')) {
    $error = $pdf->getError();
    // ... handle error here
}

带目录和封面页的多页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
if (!$pdf->saveAs('/path/to/report.pdf')) {
    $error = $pdf->getError();
    // ... handle error here
}

// ... or send to client for inline display
if (!$pdf->send()) {
    $error = $pdf->getError();
    // ... handle error here
}

// ... or send to client as file download
if (!$pdf->send('report.pdf')) {
    $error = $pdf->getError();
    // ... handle error here
}

// ... 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, an URL or an options array to the constructor
$image = new Image('/path/to/page.html');
$image->saveAs('/path/to/page.png');

// ... or send to client for inline display
if (!$image->send()) {
    $error = $image->getError();
    // ... handle error here
}

// ... or send to client as file download
if (!$image->send('page.png')) {
    $error = $image->getError();
    // ... handle error here
}

设置选项

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:到临时目录的路径。默认为PHP临时目录。
  • ignoreWarnings:是否忽略任何错误,如果仍然创建了PDF文件。默认为false
  • version9:是否使用较旧版本wkhtmltopdf的命令行语法。

除了上述的binarycommandOptionstmpDirignoreWarnings选项外,Image类还有一个type选项

  • type:图像类型。默认为png。您还可以使用jpgbmp

可以使用commandOptions来设置wkhtmltopdf的环境变量。例如,如果您想传递UTF-8编码的参数,您可能需要设置LANG环境变量。

$pdf = new Pdf(array(
    'binary' => '/obscure/path/to/wkhtmltopdf',
    'ignoreWarnings' => true,
    'commandOptions' => array(
        'useExec' => true,      // Can help if generation fails without a useful error message
        'procEnv' => array(
            // Check the output of 'locale' on your system to find supported languages
            'LANG' => 'en_US.utf-8',
        ),
    ),
));

传递字符串

某些选项(如header-html)通常期望URL或文件名。使用我们的库,您也可以传递字符串。类将尝试检测参数是URL、文件名还是某些HTML或XML内容。为了使检测更容易,您可以在内容周围添加<html>标签。

如果这不起作用,您也可以作为最后手段传递我们的File辅助实例

use mikehaertl\tmp\File;
$options = [
    'header-html' => new File('Complex content', '.html'),
];

错误处理

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 用户注意

如果您使用双引号(")或百分号(%)作为选项值,它们可能会被转换为空格。在这种情况下,您可以在 命令 中禁用参数转义。对于 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 环境,而不需要完整 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)。您可以将其放置在 /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 中使用 cmin,因为这更适合打印样式。

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');

if (!$pdf->send()) {
    $error = $pdf->getError();
    // ... handle error here
}

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 中。