dompdf使用教程_使用Dompdf将HTML转换为PDF

dompdf使用教程

PDF is a standard format originally created by Adobe for representing text and images in a fixed-layout document. It’s not uncommon for a web application to support downloading data, such as invoices or reports, in PDF format, so in this article we’ll go through how we can easily generate PDF documents using PHP.

PDF是Adobe最初创建的一种标准格式,用于在固定布局的文档中表示文本和图像。 Web应用程序支持以PDF格式下载数据(例如发票或报告)的情况并不少见,因此在本文中,我们将介绍如何使用PHP轻松生成PDF文档。

Dompdf is a great library, capable of generating a PDF from HTML markup and CSS styles (it’s mostly CSS 2.1 compliant and has support for some CSS3 properties). We can decide how our content should look using these familiar technologies, and then easily convert that into a fixed document. The library has many other useful and interesting features, too.

Dompdf是一个很棒的库,能够从HTML标记和CSS样式生成PDF(它主要符合CSS 2.1,并且支持某些CSS3属性)。 我们可以使用这些熟悉的技术来决定内容的外观,然后轻松地将其转换为固定文档。 该库还具有许多其他有用和有趣的功能。

入门 (Getting Started)

Dompdf is available on GitHub and can be installed using Composer. Getting a Composer-based install up and running correctly is admittedly still a bit tricky, so I recommend just using Git to install Dompdf.

Dompdf在GitHub上可用,可以使用Composer安装。 正确地安装和运行基于Composer的安装仍然有些棘手,因此我建议仅使用Git来安装Dompdf。

The library requires PHP >= 5.0 with the mbstring and DOM extensions enabled. It also needs some fonts, which are generally available on most machines.

该库要求PHP> = 5.0,并且已启用mbstring和DOM扩展。 它还需要一些字体,这些字体通常在大多数计算机上都可用。

Navigate to wherever you want to put the library and execute:

导航至要放置库并执行的位置:

git clone https://github.com/dompdf/dompdf.git
git submodule init
git submodule update

With Dompdf downloaded, let’s write a short example that will generate a simple PDF.

下载Dompdf后,让我们写一个简短的示例,它将生成一个简单的PDF。

<?php
set_include_path(get_include_path() . PATH_SEPARATOR . "/path/to/dompdf");

require_once "dompdf_config.inc.php";

$dompdf = new DOMPDF();

$html = <<<'ENDHTML'
<html>
 <body>
  <h1>Hello Dompdf</h1>
 </body>
</html>
ENDHTML;

$dompdf->load_html($html);
$dompdf->render();

$dompdf->stream("hello.pdf");

To use the library in a project, we first pull in dompdf_config.inc.php which contains most of the Dompdf configuration. It also loads an autoloader and a custom configuration file in which we can override default configuration parameters.

要在项目中使用该库,我们首先dompdf_config.inc.php ,其中包含大多数Dompdf配置。 它还会加载一个自动加载器和一个自定义配置文件,在其中我们可以覆盖默认配置参数。

HTML markup is given as a string to the load_html() method. Alternatively, we can load markup from a file or URL using the load_html_file() method. It accepts a filename or the URL of a webpage as its argument.

HTML标记作为字符串提供给load_html()方法。 另外,我们可以使用load_html_file()方法从文件或URL加载标记。 它接受文件名或网页的URL作为其参数。

The render() method renders the HTML into PDF and we are ready to dump the PDF file. stream() sends the resulting PDF as an attachment to the browser. The stream() method has an optional second parameter, an array of options:

render()方法将HTML渲染为PDF,我们准备转储PDF文件。 stream()将生成的PDF作为附件发送到浏览器。 stream()方法有一个可选的第二个参数,它是一个选项数组:

  • Accept-Ranges – boolean, send “Accept-Ranges” header (false by default).

    Accept-Ranges –布尔值,发送“接受范围”标头(默认为false)。

  • Attachment – boolean, send “Content-Disposition: attachment” header forcing the browser to display a save prompt (true by default).

    Attachment -布尔值,发送“ Content-Disposition:附件”标头,强制浏览器显示保存提示(默认情况下为true)。

  • compress – boolean, enable content compression (true by default).

    compress –布尔值,启用内容压缩(默认情况下为true)。

We’ve generated a very simple PDF here, but that’s not very practical. In reality we’ll often have requirements about paper size, page orientation, character encoding, etc. There are number of configuration options that we can set to make Dompdf more suitable for our real-world needs. All of them are listed and explained in dompdf_config.inc.php which sets them to their default values. You can change these values by updating the the custom configuration file dompdf_config.custom.inc.php. Some of the important settings are:

我们在这里生成了一个非常简单的PDF,但这不是很实际。 实际上,我们通常对纸张大小,页面方向,字符编码等有要求。我们可以设置许多配置选项,以使Dompdf更适合我们的实际需求。 所有这些都在dompdf_config.inc.php中列出并说明,该文件将它们设置为默认值。 您可以通过更新定制配置文件dompdf_config.custom.inc.php来更改这些值。 一些重要的设置是:

  • DOMPDF_DEFAULT_PAPER_SIZE – sets the default paper size for the PDF document. Supported paper sizes can be found in include/cpdf_adapter.cls.php (the default value is “letter”).

    DOMPDF_DEFAULT_PAPER_SIZE –设置PDF文档的默认纸张尺寸。 支持的纸张尺寸可以在include/cpdf_adapter.cls.php找到(默认值为“ letter”)。

  • DOMPDF_TEMP_DIR – specifies the temporary directory used by Dompdf. Make sure this location is writable by the web server account.

    DOMPDF_TEMP_DIR –指定DOMPDF_TEMP_DIR使用的临时目录。 确保此位置可由Web服务器帐户写入。

  • DOMPDF_UNICODE_ENABLED – sets whether the PDF uses Unicode fonts (the default is true).

    DOMPDF_UNICODE_ENABLED –设置PDF是否使用Unicode字体(默认为true)。

  • DOMPDF_ENABLE_REMOTE – enables the inclusion of images or CSS styles from remote sites (default is false).

    DOMPDF_ENABLE_REMOTE –允许包含来自远程站点的图像或CSS样式(默认为false)。

  • DEBUG_LAYOUT – whether to render a box around each HTML block in the PDF file which is useful for debugging the layout (default is false).

    DEBUG_LAYOUT –是否在PDF文件中的每个HTML块周围呈现一个框,这对于调试布局很有用(默认为false)。

高级用法 (Advanced Usage)

Now let’s talk about some advanced uses of Dompdf. Perhaps we want to save the generated PDF document to disk instead of sending it to the browser. Here’s how:

现在让我们谈谈Dompdf的一些高级用法。 也许我们想将生成的PDF文档保存到磁盘,而不是将其发送到浏览器。 这是如何做:

<?php
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();

$output = $dompdf->output();
file_put_contents("/path/to/file.pdf", $output);

Instead of calling stream() like in the previous example, we use output() which returns the PDF as a string. It too accepts an optional options array, but the only option available is compress (the default is true).

而不是像上一个示例那样调用stream() ,我们使用output()将PDF作为字符串返回。 它也接受可选的options数组,但是唯一可用的选项是compress(默认为true)。

Dompdf also allows us to add a header or footer to the generated PDF by embedding a PHP script in the HTML that it renders. But because processing arbitrary code can pose a security risk if you’re not careful, the configuration value that controls this functionality is off by default. We need to first set the DOMPDF_ENABLE_PHP option true.

Dompdf还允许我们通过将PHP脚本嵌入所呈现HTML中,从而在生成的PDF中添加页眉或页脚。 但是由于不小心处理任意代码会带来安全隐患,因此控制此功能的配置值默认为关闭。 我们需要首先将DOMPDF_ENABLE_PHP选项设置为true。

Once we’ve enabled inline PHP execution, the PDF object will be made available within the script, which we can use to manipulate the page. We can add text, lines, images, rectangles, etc. anywhere inside the page.

启用内联PHP执行后,脚本中将提供PDF对象,我们可以使用该对象来操纵页面。 我们可以在页面内的任何地方添加文本,线条,图像,矩形等。

$html = <<<'ENDHTML'
<html>
 <body>
  <script type="text/php">
if (isset($pdf)) {
    // open the PDF object - all drawing commands will
    // now go to the object instead of the current page
    $footer = $pdf->open_object();

    // get height and width of page
    $w = $pdf->get_width();
    $h = $pdf->get_height();

    // get font
    $font = Font_Metrics::get_font("helvetica", "normal");
    $txtHeight = Font_Metrics::get_font_height($font, 8);

    // draw a line along the bottom
    $y = $h - 2 * $txtHeight - 24;
    $color = array(0, 0, 0);
    $pdf->line(16, $y, $w - 16, $y, $color, 1);
    
    // set page number on the left side
    $pdf->page_text(16, $y, "Page: {PAGE_NUM} of {PAGE_COUNT}", $font, 8, $color);
    // set additional text
    $text = "Dompdf is awesome";
    $width = Font_Metrics::get_text_width($text, $font, 8);
    $pdf->text($w - $width - 16, $y, $text, $font, 8);

    // close the object (stop capture)
    $pdf->close_object();

    // add the object to every page (can also specify
    // "odd" or "even")
    $pdf->add_object($footer, "all");
}
  </script>
  <h1>Hello Dompdf</h1>
 </body>
</html>
ENDHTML;

The script is embedded directly into the HTML markup, and first opens an object so we can affect the rendering. All drawing will be recorded into that object and we can add this object to all or selected pages (though there are limitations).

该脚本直接嵌入到HTML标记中,然后首先打开一个对象,这样我们就可以影响渲染了。 所有图形都将记录到该对象中,我们可以将该对象添加到所有或选定的页面中(尽管有限制)。

Next we fetch the actual width and height of the page to calculate the coordinates of the footer we intend to add. Also, we need to provide a font object while we add text contents. Font_Metrics::get_font() lets us to create the object we need. We also take the height of the given font at its font size using get_font_height()to calculate positioning for the footer’s contents. The method get_font_width() returns the width of our text for the given font and font size which is also used in our calculations.

接下来,我们获取页面的实际宽度和高度,以计算要添加的页脚的坐标。 另外,添加文本内容时,我们需要提供字体对象。 Font_Metrics::get_font()使我们可以创建所需的对象。 我们还使用get_font_height()来获取给定字体在其字体大小处的高度,以计算页脚内容的位置。 方法get_font_width()返回给定字体和字体大小的文本宽度,该宽度也用于我们的计算中。

The line() method draws a line from point (X1,Y1) to (X2,X2). Notice that the color value we provided is not an actual RGB value. The underlying PDF class requires values between 0 and 1 and so we convert the RGB values into these new values. To get a better approximation, you can divide it by 255.

line()方法绘制从点(X1,Y1)到(X2,X2)的线。 请注意,我们提供的颜色值不是实际的RGB值。 基础的PDF类需要0到1之间的值,因此我们将RGB值转换为这些新值。 为了获得更好的近似值,可以将其除以255。

We add the page number for each page using the page_text() method, which accepts an X and Y position, the text to be added, a font object, font size, and color. Dompdf automatically replaces the values for {PAGE_NUM} and {PAGE_COUNT} in each page, and makes $pdf available to us.

我们使用page_text()方法为每个页面添加页码,该方法接受X和Y位置,要添加的文本,字体对象,字体大小和颜色。 Dompdf自动替换每个页面中{PAGE_NUM}{PAGE_COUNT}的值,并向我们提供$pdf

When the PDF renders, the footer section will look like this:

PDF呈现后,页脚部分将如下所示:

dompdf-01

It’s possible to avoid using inline PHP and achieve the same effect directly from PHP, like so:

可以避免使用内联PHP并直接从PHP获得相同的效果,如下所示:

<?php
$dompdf = new DOMPDF();
$dompdf->set_paper("A4");

// load the html content
$dompdf->load_html($html);
$dompdf->render();
$canvas = $dompdf->get_canvas();
$font = Font_Metrics::get_font("helvetica", "bold");
$canvas->page_text(16, 800, "Page: {PAGE_NUM} of {PAGE_COUNT}", $font, 8, array(0,0,0));
$dompdf->stream("sample.pdf",array("Attachment"=>0));

Note that we place the code after calling $dompdf->render() because we are essentially modifying the rendered PDF.

注意,我们将代码放置在调用$dompdf->render()因为我们实际上是在修改呈现的PDF。

结论 (Conclusion)

In this article we discussed how to easily convert HTML to PDF using Dompdf. Although Dompdf is a great library, it’s not a bulletproof solution for generating PDF documents; it does has some limitations and issues. Dompdf is not really tolerant of poorly-formed HTML, and large tables can easily cause you to run out of memory. Some basic CSS features like float are not completely supported and there is only limited support for CSS3. If you need features which are not supported by Dompdf, something like wkhtmltopdf might be a better solution for you. Still, Dompdf is fairly simple and suitable for the majority of PDF export needs.

在本文中,我们讨论了如何使用Dompdf轻松将HTML转换为PDF。 尽管Dompdf是一个很棒的库,但它不是生成PDF文档的防弹解决方案; 它确实有一些限制和问题。 Dompdf对格式不正确HTML并不是真正的宽容,大型表很容易导致内存不足。 一些基本CSS功能(例如float)并未得到完全支持,并且对CSS3的支持也很有限。 如果您需要Dompdf不支持的功能,则wkhtmltopdf之类的东西可能是您更好的解决方案。 不过,Dompdf非常简单,适合大多数PDF导出需求。

It’s really difficult to explain all of the features provided by a library in article such as this, so be sure to check out the documentation and source code as well to learn about cool features like adding callbacks, using custom fonts, etc. Also, I’m happy to help you within my limited expertise. Feel free to leave your questions and share your experiences in the comments section.

真的很难在此类文章中解释库提供的所有功能,因此一定要查看文档和源代码,以了解一些很酷的功能,例如添加回调,使用自定义字体等。此外,我很高兴在我有限的专业知识范围内为您提供帮助。 随时留下您的问题,并在评论部分中分享您的经验。

Image via Fotolia

图片来自Fotolia

And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Jump Start PHP.

并且,如果您喜欢阅读这篇文章,您会喜欢Learnable的 向大师学习新鲜技能的地方。 会员可以立即访问所有SitePoint的电子书和交互式在线课程,例如Jump Start PHP

Comments on this article are closed. Have a question about PHP? Why not ask it on our forums?

本文的评论已关闭。 对PHP有疑问吗? 为什么不在我们的论坛上提问呢?

翻译自: https://www.sitepoint.com/convert-html-to-pdf-with-dompdf/

dompdf使用教程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值