Home  >  Article  >  Backend Development  >  How to generate PDF files in PHP

How to generate PDF files in PHP

PHPz
PHPzOriginal
2023-08-27 09:25:042326browse

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.

HeaderMethod

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:

How to generate PDF files in PHP

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:

How to generate PDF files in PHP

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

现在我们已经添加了一个页面,我们可以开始在此页面上书写。

接下来,我们使用 WritewriteHTML 方法在左侧打印日期和发票号码。

// 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 方法的最后一个参数,如上面的代码片段所示。在我们的例子中,我们希望显示右对齐的收单地址。

让我们快速浏览一下到目前为止我们已经构建的内容。

How to generate PDF files in PHP

接下来,我们有一个代码片段,它负责打印项目信息表的繁重工作。

// 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 方法来打印总金额。

表格的快速预览应如下所示:

How to generate PDF files in PHP

现在,让我们回到 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 文件。

How to generate PDF files in PHP

结论

这就是如何使用 TCPDF 库在 PHP 中创建 PDF 文档。我们创建了一个真实示例来演示 TCPDF 库提供的一些不同的 API。

TCPDF 官方文档提供了许多现成的模板,您可以探索它们以了解内置 API,我鼓励您探索它!

如果您想了解有关在网站中包含 PDF 的更多信息,请查看以下链接:

  • How to generate PDF files in PHPHow to generate PDF files in PHP How to create a JavaScript PDF viewer How to generate PDF files in PHPHow to generate PDF files in PHP Ashraf Hatibelagar August 16, 2021
  • How to generate PDF files in PHPHow to generate PDF files in PHP How to embed and protect PDF files using WordPress plugins How to generate PDF files in PHPHow to generate PDF files in PHP Esther persisted October 17, 2022
  • How to generate PDF files in PHPHow to generate PDF files in PHP How to embed PDF files on your WordPress website using a free plugin How to generate PDF files in PHPHow to generate PDF files in PHP a hundred sons July 29, 2019
  • How to generate PDF files in PHPHow to generate PDF files in PHP How to use the WowBook ​​jQuery Flipbook plug-in How to generate PDF files in PHPHow to generate PDF files in PHP 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn