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

  • Post author:
  • Post category:其他


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 P