Dompdf 有用的方法
Dompdf 库提供了各种方法和选项来配置 PDF 创建。
下面给出了 Dompdf 类的一些有用方法,它们通常用于将 HTML 集成到 PDF 功能。
loadHtml():加载 HTML 内容。
- $str (string) - 必需。指定要加载的 HTML。
- $encoding (string) - 可选。指定编码。
loadHtmlFile():从 HTML 文件加载内容。
- $file (string) - 必需。指定要加载的文件名或者 url。
output():以字符串形式返回 PDF。
- $options (array) - 可选。指定是否启用内容流压缩。 (压缩 => 1 或者 0)
render():将 HTML 呈现为 PDF。
setBasePath():设置基本路径以包含外部样式表和图像。
- $basePath (string) - 加载外部资源 URL 时使用的基本路径。
setPaper():设置纸张大小和方向。
- $size (string|array) - 'letter', 'legal', 'A4' 等。
- $orientation (string) - 'portrait' 或者 'landscape'。
stream():将 PDF 流式传输到客户端。
- $filename (string) - 指定要流式传输的文件的名称(不带 .pdf 扩展名)。
- $options (array)
- 'compress' => 1 或者 0 - 启用内容流压缩。
- '附件' => 1 = 下载或者 0 = 预览
Dompdf 安装和设置
从 GitHub 下载 dompdf 的稳定版本。
https://github.com/dompdf/dompdf/releases
将下载的 dompdf 存档版本解压,放到你要使用 Dompdf 的目录下。
注意:我们不需要单独下载Dompdf库,所有需要的文件都包含在我们的源代码包中。
实例化 Dompdf 类
要使用 Dompdf 类,我们需要在 PHP 脚本中包含自动加载器。
使用以下 PHP 代码实例化并使用 dompdf 类。
//Include autoloader require_once 'dompdf/autoload.inc.php'; //Reference the Dompdf namespace use Dompdf\Dompdf; //Instantiate and use the dompdf class $dompdf = new Dompdf();
基本用法(将 HTML 转换为 PDF)
以下示例展示了如何使用 Dompdf 以最少的配置转换 HTML 并生成 PDF。
- 在 Dompdf 类的 loadHtml() 方法中指定 HTML 内容。
- 使用 render() 方法将 HTML 呈现为 PDF。
- 使用 stream() 方法将生成的 PDF 输出到浏览器。
//Load HTML content $dompdf->loadHtml('<h1>Welcome to onitroad.com</h1>'); //(Optional) Setup the paper size and orientation $dompdf->setPaper('A4', 'landscape'); //Render the HTML as PDF $dompdf->render(); //Output the generated PDF to Browser $dompdf->stream();
高级用法
使用 Dompdf 库,我们可以轻松增强 PDF 创建的功能。
以下代码从 HTML 文件 ( 'pdf-content.html' ) 生成 PDF。
- 使用 PHP 中的 file_get_contents() 函数从 HTML 文件中获取内容。
- 使用 Dompdf 类的 loadHtml() 方法加载 HTML 内容。
- 使用 Dompdf 类的 stream() 函数控制 PDF 输出。
- '$filename' - (字符串)PDF 文件的名称。
- '$options' - (数组)标题选项。
- “附件” - 1 = 下载,0 = 预览
//Load content from html file $html = file_get_contents("pdf-content.html"); $dompdf->loadHtml($html); //(Optional) Setup the paper size and orientation $dompdf->setPaper('A4', 'landscape'); //Render the HTML as PDF $dompdf->render(); //Output the generated PDF (1 = download and 0 = preview) $dompdf->stream("onitroad", array("Attachment" => 0));
PDF 是 Adobe Systems 创建的一种文件格式,用于在固定版式文档中说明文本和图像。
PDF 用于下载 Web 应用程序中的一堆数据或者文本内容。
PDF 文件格式是下载文件中的文本或者 HTML 内容的完美选择。
在将网页内容下载为 PDF 文件时,需要将 HTML 转换为 PDF。
在本教程中,我们将向我们展示如何使用 PHP 将 HTML 转换为 PDF 并生成 PDF 文件。
Dompdf 是一个 PHP 库,它提供了一种将 HTML 转换为 PDF 文档的简单方法。
使用 Dompdf 库,我们可以轻松地从 PHP 中的 HTML 页面生成 PDF。
示例代码将在 Web 应用程序中实现 PDF 生成功能,并使在 PHP 中使用 Dompdf 将 HTML 转换为 PDF 变得简单。