In this article, we will discuss how to generate PDF files using PHP. We will create PDF documents programmatically using the TCPDF library.
If you are developing a website that allows users to download or print documents such as order receipts, bills, or invoices, you have several options. You can display the document inline in the browser or provide it for download. PDF is one of the best formats when it comes to downloading documents and is excellent at preserving text formatting.
So, if you want to learn how to generate PDF files on your PHP website, you've come to the right place!
How to install TCPDF library
In this section, we will learn how to install the TCPDF library.
There are multiple ways to install the TCPDF library on the server. The TCPDF library is available on Packagist and GitHub, so you can use Composer or clone it from GitHub. In our case, we will install it using Composer.
Proceed to run the following command to install the TCPDF library using Composer.
$composer require tecnickcom/tcpdf Using version ^6.3 for tecnickcom/tcpdf ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Installing tecnickcom/tcpdf (6.3.5): Downloading (100%) Writing lock file Generating autoload files
After successful installation, you need to include the autoload.php file in your PHP script as shown in the following code snippet.
<?php require "./vendor/autoload.php"; ... ?>
This way, you can use all the utility methods provided by the TCPDF library.
How to use TCPDF library
In this section, we will build a practical example that demonstrates how to generate a PDF invoice. The TCPDF library provides many ready-made templates that you can use as references for generating PDF documents. However, we will generate the invoice from scratch.
As I already mentioned in the previous section, the TCPDF library provides many ready-made templates that allow you to generate generic PDF files with headers and footers. This is useful if you are happy with the default format and settings. But if you want to customize the header and footer as well as the content, you must extend the TCPDF
class and override the corresponding methods.
In our example, we will create two files: customPdfGenerator.php and example.php. In the customPdfGenerator.php file we will create the CustomPdfGenerator
class which will extend the core TCPDF
class and override a few methods. In the example.php file we will see how to use the CustomPdfGenerator
class.
CustomPdfGenerator
Class
Proceed to create the customPdfGenerator.php file with the following content.
<?php class CustomPdfGenerator extends TCPDF { public function Header() { $image_file = '/web/logo.png'; $this->Image($image_file, 10, 3, 25, '', 'PNG', '', 'T', false, 300, '', false, false, 0, false, false, false); $this->SetFont('helvetica', 'B', 20); $this->Cell(0, 15, '', 0, false, 'C', 0, '', 0, false, 'M', 'M'); $this->Ln(); $this->Cell(0, 15, 'Katie A Falk', 0, false, 'R', 0, '', 0, false, 'M', 'M'); } public function Footer() { $this->SetY(-15); $this->SetFont('helvetica', 'I', 15); $this->Cell(0, 10, 'Thank you for your business!', 0, false, 'C', 0, '', 0, false, 'T', 'M'); } public function printTable($header, $data) { $this->SetFillColor(0, 0, 0); $this->SetTextColor(255); $this->SetDrawColor(128, 0, 0); $this->SetLineWidth(0.3); $this->SetFont('', 'B', 12); $w = array(110, 17, 25, 30); $num_headers = count($header); for($i = 0; $i < $num_headers; ++$i) { $this->Cell($w[$i], 7, $header[$i], 1, 0, 'C', 1); } $this->Ln(); // Color and font restoration $this->SetFillColor(224, 235, 255); $this->SetTextColor(0); $this->SetFont(''); // table data $fill = 0; $total = 0; foreach($data as $row) { $this->Cell($w[0], 6, $row[0], 'LR', 0, 'L', $fill); $this->Cell($w[1], 6, $row[1], 'LR', 0, 'R', $fill); $this->Cell($w[2], 6, number_format($row[2]), 'LR', 0, 'R', $fill); $this->Cell($w[3], 6, number_format($row[3]), 'LR', 0, 'R', $fill); $this->Ln(); $fill=!$fill; $total+=$row[3]; } $this->Cell($w[0], 6, '', 'LR', 0, 'L', $fill); $this->Cell($w[1], 6, '', 'LR', 0, 'R', $fill); $this->Cell($w[2], 6, '', 'LR', 0, 'L', $fill); $this->Cell($w[3], 6, '', 'LR', 0, 'R', $fill); $this->Ln(); $this->Cell($w[0], 6, '', 'LR', 0, 'L', $fill); $this->Cell($w[1], 6, '', 'LR', 0, 'R', $fill); $this->Cell($w[2], 6, 'TOTAL:', 'LR', 0, 'L', $fill); $this->Cell($w[3], 6, $total, 'LR', 0, 'R', $fill); $this->Ln(); $this->Cell(array_sum($w), 0, '', 'T'); } }
It should be noted that the CustomPdfGenerator
class extends the TCPDF
class, so we can use all the utility methods provided by the TCPDF
class to format and generate PDF document.
The only purpose of creating our own class instead of using the TCPDF
class directly is that we don't want to use the built-in header and footer components. Therefore, we override the header
and footer
methods in the class.
Header
Method
In the title, we want to display the company logo as well as the owner's name. Let's go through the header method to understand how it works.
public function Header() { $image_file = '/web/logo.png'; $this->Image($image_file, 10, 3, 25, '', 'PNG', '', 'T', false, 300, '', false, false, 0, false, false, false); $this->SetFont('helvetica', 'B', 20); $this->Cell(0, 15, '', 0, false, 'C', 0, '', 0, false, 'M', 'M'); $this->Ln(); $this->Cell(0, 15, 'Katie A Falk', 0, false, 'R', 0, '', 0, false, 'M', 'M'); }
First, we use the Image method to draw the company logo on the left side. Importantly, you need to pass the absolute path to your logo image to the Image
method. Next, we use the SetFont method to set the font family and font size of the text that will be added to the title. Finally, we use the Cell
method to print the owner name on the right.
You will notice that you can pass a lot of parameters in these methods, and I encourage you to explore them in detail as it is impossible to discuss every parameter in this article.
With the above settings, the title will look like this:
Footer method
In the footer we want to display some static text, so the Footer
method is very simple as shown in the following code snippet.
public function Footer() { $this->SetY(-15); $this->SetFont('helvetica', 'I', 15); $this->Cell(0, 10, 'Thank you for your business!', 0, false, 'C', 0, '', 0, false, 'T', 'M'); }
The footer section looks like this:
Finally there is the printTable
method, we will discuss this method later. The printTable
method has nothing to do with the TCPDF
class. Instead, it is our custom utility method that we will use to draw a table to display project information.
This is the CustomPdfGenerator
class. In the next section, we'll see how to use it and some other ways to generate a full PDF invoice!
example.php file
In the previous section, we created the CustomPdfGenerator
wrapper class that we can use to generate PDF files with custom headers and footers. In this section we demonstrate how to use it.
Proceed to create the example.php file with the following content.
<?php require "./vendor/autoload.php"; require "./customPdfGenerator.php"; $pdf = new CustomPdfGenerator(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); $pdf->setFontSubsetting(true); $pdf->SetFont('dejavusans', '', 12, '', true); // start a new page $pdf->AddPage(); // date and invoice no $pdf->Write(0, "\n", '', 0, 'C', true, 0, false, false, 0); $pdf->writeHTML("<b>DATE:</b> 01/01/2021"); $pdf->writeHTML("<b>INVOICE#</b>12"); $pdf->Write(0, "\n", '', 0, 'C', true, 0, false, false, 0); // address $pdf->writeHTML("84 Norton Street,"); $pdf->writeHTML("NORMANHURST,"); $pdf->writeHTML("New South Wales, 2076"); $pdf->Write(0, "\n", '', 0, 'C', true, 0, false, false, 0); // bill to $pdf->writeHTML("<b>BILL TO:</b>", true, false, false, false, 'R'); $pdf->writeHTML("22 South Molle Boulevard,", true, false, false, false, 'R'); $pdf->writeHTML("KOOROOMOOL,", true, false, false, false, 'R'); $pdf->writeHTML("Queensland, 4854", true, false, false, false, 'R'); $pdf->Write(0, "\n", '', 0, 'C', true, 0, false, false, 0); // invoice table starts here $header = array('DESCRIPTION', 'UNITS', 'RATE $', 'AMOUNT'); $data = array( array('Item #1','1','100','100'), array('Item #2','2','200','400') ); $pdf->printTable($header, $data); $pdf->Ln(); // comments $pdf->SetFont('', '', 12); $pdf->writeHTML("<b>OTHER COMMENTS:</b>"); $pdf->writeHTML("Method of payment: <i>PAYPAL</i>"); $pdf->writeHTML("PayPal ID: <i>katie@paypal.com"); $pdf->Write(0, "\n\n\n", '', 0, 'C', true, 0, false, false, 0); $pdf->writeHTML("If you have any questions about this invoice, please contact:", true, false, false, false, 'C'); $pdf->writeHTML("Katie A Falk, (07) 4050 2235, katie@sks.com", true, false, false, false, 'C'); // save pdf file $pdf->Output(__DIR__ . '/invoice#12.pdf', 'F');
Let’s take a look at the important snippets from the above file.
First, we added the autoload.php file to ensure that the TCPDF
class is automatically loaded. Next, we added the customPdfGenerator.php file to load our custom class.
接下来,我们实例化了 CustomPdfGenerator
类以及默认设置。在实际开始写入 PDF 文件之前,我们还调用了一些方法来进行默认设置。
$pdf = new CustomPdfGenerator(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); $pdf->setFontSubsetting(true); $pdf->SetFont('dejavusans', '', 12, '', true);
我们在上面代码片段中使用的常量已在 tcpdf_autoconfig.php 文件中定义。要覆盖这些常量之一,您只需在脚本中定义它,TCPDF 库将使用您的值。例如,PDF_PAGE_ORIENTATION
常量的默认值为 P
(纵向),如果要将其更改为 L
(横向),则只需包含 define ('PDF_PAGE_ORIENTATION', 'L ');脚本中的
。
接下来,有一个重要的片段,它调用 AddPage
方法,该方法实际上在 PDF 文档中添加一个新页面。
// start a new page $pdf->AddPage();
现在我们已经添加了一个页面,我们可以开始在此页面上书写。
接下来,我们使用 Write
和 writeHTML
方法在左侧打印日期和发票号码。
// date and invoice no $pdf->Write(0, "\n", '', 0, 'C', true, 0, false, false, 0); $pdf->writeHTML("<b>DATE:</b> 01/01/2021"); $pdf->writeHTML("<b>INVOICE#</b>12"); $pdf->Write(0, "\n", '', 0, 'C', true, 0, false, false, 0);
Write
方法从当前位置开始打印文本,您可以使用它来打印纯文本。另一方面, writeHTML
方法允许您保留文本中的 HTML 格式。虽然 writeHTML
方法提供了有限的 HTML 格式支持,但它涵盖了日常开发中经常使用的所有 HTML 标签。
同样,我们在 writeHTML
方法的帮助下打印了地址和收单地址。
// address $pdf->writeHTML("84 Norton Street,"); $pdf->writeHTML("NORMANHURST,"); $pdf->writeHTML("New South Wales, 2076"); $pdf->Write(0, "\n", '', 0, 'C', true, 0, false, false, 0); // bill to $pdf->writeHTML("<b>BILL TO:</b>", true, false, false, false, 'R'); $pdf->writeHTML("22 South Molle Boulevard,", true, false, false, false, 'R'); $pdf->writeHTML("KOOROOMOOL,", true, false, false, false, 'R'); $pdf->writeHTML("Queensland, 4854", true, false, false, false, 'R'); $pdf->Write(0, "\n", '', 0, 'C', true, 0, false, false, 0);
默认情况下,writeHTML
方法在左侧打印文本。如果要打印右对齐文本,可以传递 R
作为 writeHTML
方法的最后一个参数,如上面的代码片段所示。在我们的例子中,我们希望显示右对齐的收单地址。
让我们快速浏览一下到目前为止我们已经构建的内容。
接下来,我们有一个代码片段,它负责打印项目信息表的繁重工作。
// invoice table starts here $header = array('DESCRIPTION', 'UNITS', 'RATE $', 'AMOUNT'); $data = array( array('Item #1','1','100','100'), array('Item #2','2','200','400') ); $pdf->printTable($header, $data); $pdf->Ln();
还记得我们在customPdfGenerator.php类中定义的printTable
方法吗?现在是时候详细探讨它了。让我们拉入 printTable
方法的代码。
public function printTable($header, $data) { $this->SetFillColor(0, 0, 0); $this->SetTextColor(255); $this->SetDrawColor(128, 0, 0); $this->SetLineWidth(0.3); $this->SetFont('', 'B', 12); $w = array(110, 17, 25, 30); $num_headers = count($header); for($i = 0; $i < $num_headers; ++$i) { $this->Cell($w[$i], 7, $header[$i], 1, 0, 'C', 1); } $this->Ln(); // Color and font restoration $this->SetFillColor(224, 235, 255); $this->SetTextColor(0); $this->SetFont(''); // table data $fill = 0; $total = 0; foreach($data as $row) { $this->Cell($w[0], 6, $row[0], 'LR', 0, 'L', $fill); $this->Cell($w[1], 6, $row[1], 'LR', 0, 'R', $fill); $this->Cell($w[2], 6, number_format($row[2]), 'LR', 0, 'R', $fill); $this->Cell($w[3], 6, number_format($row[3]), 'LR', 0, 'R', $fill); $this->Ln(); $fill=!$fill; $total+=$row[3]; } $this->Cell($w[0], 6, '', 'LR', 0, 'L', $fill); $this->Cell($w[1], 6, '', 'LR', 0, 'R', $fill); $this->Cell($w[2], 6, '', 'LR', 0, 'L', $fill); $this->Cell($w[3], 6, '', 'LR', 0, 'R', $fill); $this->Ln(); $this->Cell($w[0], 6, '', 'LR', 0, 'L', $fill); $this->Cell($w[1], 6, '', 'LR', 0, 'R', $fill); $this->Cell($w[2], 6, 'TOTAL:', 'LR', 0, 'L', $fill); $this->Cell($w[3], 6, $total, 'LR', 0, 'R', $fill); $this->Ln(); $this->Cell(array_sum($w), 0, '', 'T'); }
首先,在实际开始打印发票表的标题行之前,我们调用了几个方法来设置字体大小、填充颜色、线宽和文本颜色。接下来,我们在 Cell
方法的帮助下循环遍历 $header
数组并打印表头标题。
Cell
方法允许您打印具有可选边框、背景颜色和字符串的单元格(矩形区域)。您还可以指定在单元格中打印的文本的对齐方式。因此,Cell
方法是构建表的完美候选方法。
打印表格标题标题后,我们循环遍历 $data
数组并打印它以完成整个表格。最后,我们多次调用 Cell
方法来打印总金额。
表格的快速预览应如下所示:
现在,让我们回到 example.php 文件来查看最后几行代码。
在发票末尾,我们将打印一些评论和联系信息,如以下代码片段所示。
// comments $pdf->SetFont('', '', 12); $pdf->writeHTML("<b>OTHER COMMENTS:</b>"); $pdf->writeHTML("Method of payment: <i>PAYPAL</i>"); $pdf->writeHTML("PayPal ID: <i>katie@paypal.com"); $pdf->Write(0, "\n\n\n", '', 0, 'C', true, 0, false, false, 0); $pdf->writeHTML("If you have any questions about this invoice, please contact:", true, false, false, false, 'C'); $pdf->writeHTML("Katie A Falk, (07) 4050 2235, katie@sks.com", true, false, false, false, 'C');
最后,我们使用 Output
方法将 PDF 文件保存到磁盘。如果您不想将 PDF 文件保存在磁盘上,而只想将其发送到浏览器,则需要在 Output
方法的第二个参数中使用 I
。
继续运行 example.php
文件,它应该生成如下屏幕截图所示的 PDF 文件。
结论
这就是如何使用 TCPDF 库在 PHP 中创建 PDF 文档。我们创建了一个真实示例来演示 TCPDF 库提供的一些不同的 API。
TCPDF 官方文档提供了许多现成的模板,您可以探索它们以了解内置 API,我鼓励您探索它!
如果您想了解有关在网站中包含 PDF 的更多信息,请查看以下链接:
-
How to create a JavaScript PDF viewer
Ashraf Hatibelagar August 16, 2021
-
How to embed and protect PDF files using WordPress plugins
Esther persisted October 17, 2022
-
How to embed PDF files on your WordPress website using a free plugin
a hundred sons July 29, 2019
-
How to use the WowBook jQuery Flipbook plug-in
Ashraf Hatibelagar January 16, 2019
The above is the detailed content of How to generate PDF files in PHP. For more information, please follow other related articles on the PHP Chinese website!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment
