Making pdf with php

How to Generate PDF Documents using PHP and Libraries

PHP is one of the most powerful server-side scripting languages available today. This programming language is used by developers to create websites that are dynamic and interactive.

PDF is an abbreviation for Portable Document Format, which captures all the elements in a file and allows people to easily present documents irrespective of the application used. PHP has some powerful libraries that can convert executable codes into PDF documents.

Imagine if you were given a task to include PDF generation in your PHP-based web application, knowing how to use PHP to create PDF documents would come in very handy.

In this article, I’ll demonstrate how to create PDF files with third-party PHP PDF libraries like FPDF, TCPDF, DOMPDF, html2PDF, and PHP PDF generator.

2. PHP Libraries for PDF Generation

PHP provides a range of libraries that can easily assist you in converting your PHP files into PDF documents. I compiled a list of simple libraries, taking implementation, functions, and use cases into account.

2.1 – FPDF

FPDF(Free Portable Document Format) is a PHP class that includes numerous functions for creating and editing PDFs for free. The FPDF class supports a variety of features like:

  • Image support (PNG, JPEG, and GIF)
  • Page headers
  • Page format
  • Footers
  • Automatic page break, and many more
Читайте также:  Online редактор для html

However, because it is a third-party library, it requires some processes before you can use it. You will need to:

  1. Download the FPDF class for free from the FPDF website.
  2. Create a folder and extract the FPDF package into it. Let’s say that you have downloaded and extracted the FPDF package inside a folder called fpdf (or any name you like).
  1. Create a new PHP file called scriptToPDF.php inside the same folder and insert the code snippet below. Save the file and try to access it through your localhost : http://localhost/fpdf/scriptToPDF.php
SetFont('Times','B',14); // Move to the right $this->Cell(276,5, 'HOW TO GENERATE PDF USING FPDF'); //Sets the text color $this->SetTextColor(0,0,255); //Line break $this->Ln(20); // Header $this->Cell(200,10,'FPDF DOCUMENTATION',0,0,'C'); // Line break $this->Ln(20); > // Page footer function Footer() < // Position at 1.5 cm from bottom $this->SetY(-25); // Arial italic 8 $this->SetFont('Arial','I',8); // Page number $this->Cell(0,10,'Page ' . $this->PageNo() . '/',0,0,'C'); > // header Attributes function headerAttributes() < $this->SetFont('Times','B', 10); $this->Cell(30,10,'Attributes',1,0,'C'); $this->Cell(45,10,'Description',1,0,'C'); $this->Cell(60,10,'How to Use',1,0,'C'); $this->Cell(40,10,'Tutorials',1,0,'C'); $this-the >Ln(); > > // Instantiation of FPDF class $pdf = new myPDF(); // Define an alias for number of pages $pdf->AliasNbPages(); $pdf->AddPage(); $pdf->headerAttributes(); $pdf->SetFont('Times','',14); $pdf->Output(); ?>

This will create a PDF document with a header, header attributes, and a footer. You can also use FPDF to add a link, draw a line, and perform other functions. More information has been provided in the documentation.

2.2 – TCPDF

The TCPDF PHP library makes it simple to generate a PDF document. You can easily accomplish this by cloning the GitHub repository. After cloning the repository, you can import this library into your PHP file. The TCPDF library also supports a variety of functions like:

  • Manage page headers and footers automatically
  • Text rendering options -Processes for publishing XHTML + CSS code, JavaScript, and Forms.
  • Supports JPEG, PNG, and SVG images natively.
  • Page breaks, line breaks, and text alignments are all automated.
  • Page grouping and automatic page numbering, and many more.

To enable it to work, it requires the following:

  1. Clone the repository
  2. Create a file called ‘myPDF.php’ (or any other name you want) inside the folder you cloned and insert the following code snippet.
SetCreator(PDF_CREATOR); $pdf->SetAuthor('Nicole Asuni'); $pdf->SetTitle('PDF file using TCPDF'); // set default header data $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 006', PDF_HEADER_STRING); // set header and footer fonts $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); // set default monospaced font $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); // set margins $pdf->SetMargins(20, 20, 20); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); // set auto page breaks $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); // set image scale factor $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); // add a page $pdf->AddPage(); $html = TCPDF PHP Library is easy! This is an example of the TCPDF library. 

I am using the default header and footer

Please check the source code documentation for more examples of using TCPDF.

EOD; // Print text using writeHTMLCell() $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true); // $pdf->writeHTML($html, true, false, true, false, ''); // add a page $pdf->AddPage(); $html = '

Second page

'; $pdf->writeHTML($html, true, false, true, false, ''); // reset pointer to the last page $pdf->lastPage(); //Close and output PDF document $pdf->Output('example.pdf', 'I'); ?>

This generates a PDF document using the TCPDF’s library default header and footer. You can find more examples of how to use the library on their website.

2.3 – DOMPDF

DomPDF is a PHP-based HTML to PDF converter. It is a library that reads HTML and CSS documents (including inline styles and external stylesheets) and converts them to an automatically generated PDF document. The dompdf library supports many features like:

  • CSS 2.1 and a few CSS3 properties, including @import, @media, and @page rules
  • The majority of HTML 4.0 presentational attributes
  • Compatibility with complex tables
  • Support for images (gif, png (8, 24, and 32 bit with alpha channel), bmp, and jpeg).
  • No reliance on third-party PDF libraries, among other advantages.

** Note: To enable it to function, PHP version 7.1 or higher is required.

This library can be easily installed via composer:

composer require dompdf/dompdf

Or you can choose to clone the repository on Github to your system. After cloning the repository, create a file called index.php inside the folder you cloned and insert the following code snippet.

 table < font-family: arial; width:400px; border-collapse: collapse; >td, th < border: 1px solid black; text-align: left; padding: 8px; >tr:nth-child(even) 

Welcome to api.template

List of Registered users

Name Age Date of Birth Country
Caroline White 50 20-12-1960 Germany
Jane Dutch 35 20-12-1978 Kenya
'; // Load HTML content $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 to Browser $dompdf->stream(); ?>

This code generates a PDF document with the following HTML and CSS layout.

2.4 – HTML2PDF

The HTML2PDF API makes it simple to convert web pages to PDF. It reads valid HTML codes and converts them to PDF format, allowing it to generate documents such as receipts and manuals, among many others. It should be noted that specific tags must be implemented to use the html2pdf API, therefore, it is recommended that you write your own HTML code. It utilizes TCPDF.

It has a lot of cool features, such as:

  • The ability to customize the page size and margins
  • Allows you to personalize the layout by changing the fonts and colors to your liking.
  • Enables you to customize your headers, footers, and offsets.
  • Allows you to add watermarks to your PDF documents.
  • Uses encryption or passwords to protect your PDF from unauthorized printing and copying.

To use the HTML2PDF API, you will need:

The recommended way to install the HTML2PDF is via composer:

composer require spipu/html2pdf

Create a new file in the root folder and paste the following code into it.

HTML2PDF is easy 

The HTML2PDF API makes it simple to convert web pages to PDF.

It should be noted that specific tags must be implemented to use the html2pdf

' $html2pdf->writeHTML($html); $html2pdf->output(); ?>

This code converts the HTML into a PDF document.

2.5 – APITemplate.io – REST API

APITemplate.io is a robust cloud-based API platform that makes it simple to generate REST APIs as PDF documents by using already created templates. It currently supports HTML to PDF conversions and lets you preview your PDF before downloading. It includes some great features, such as:

  • Convert HTML to PDF
  • It is compatible with CSS, JavaScript, PHP, and Python
  • Integrate with Zapier, Integromat, n8n, Airtable, UiPath, and other No-code platforms
  • Custom footer and header with page number and total pages are supported.

To use APITemplate.io, you need to do the following:

  1. Signup at app.apitemplate.io/accounts/signup/ to create an account
  2. In the Manage Templates page, click on Create PDF Template button to create a new template
  3. Post and manipulate your JSON data however you like along with the parameters to generate a PDF!
else< $json_result = json_decode($result, 1); if($json_result["status"]=="success")< return $json_result["download_url"]; >else < return null; >> > $tempate_id = "79667b2b1876e347"; $api_key = "6fa6g2pdXGIyHRhVlGh7U56Ada1eF"; $json_payload='< "invoice_number": "INV38379", "date": "2021-09-30", "currency": "USD", "total_amount": 82542.56 >'; echo generate($tempate_id,$api_key,$json_payload); ?>

This endpoint generates a PDF document containing JSON data and the template.

3. Conclusion

In this article, we discussed how to generate PDF files from HTML files using PHP.

We also went over some of the libraries, including htmltopdf, tcpdf, dompdf, fpdf, and APITemplate.io. We also compared them in terms of features, implementation, functions, and use cases.

If I had to suggest a tool, I would recommend APITemplate.io, this is because it can help you generate PDFs quickly and is compatible with CSS, JavaScript, Java, and Python.

Источник

PHP Making PDFs

PHP Code Snippets Make a PDF

In this code snippet, we’ll learn how to make a PDF file in PHP.

We will use t he FPDF library to generate a PDF. More specifically we’ll see how to create page headers/footers, add page numbers, write text, use cells, use multicell, inserting links and images.

Let’s see how to do it in the example below.

Installing FPDF:

Install FPDF using Composer by opening your project directory in cmd and running this:

composer require setasign/fpdf

Code:

PDF.php
Image(dirname(__FILE__) . "\\logo.png", 180, 5, 15); //Insert link over the area of the image. $this->Link(180, 5, 15, 15, "https://eecs.blog"); //Arial bold 15. $this->SetFont("Helvetica", "B", 15); //Make empty cell 80 wide(to move to the right). $this->Cell(80); //Title Cell(width, height, text, draw border, 1 - same as calling Ln(), center text). $this->Cell(30, 10, "Title", 1, 0, "C"); $this->setCreator("The EECS Blog"); > //Page footer. function Footer() < //Position at 1.5 cm from bottom. $this->SetY(-15); //Set font. $this->SetFont("Helvetica", "I", 8); //Set page number. $this->PageNo() gets current page number. $this->Cell(0, 10, "Page " . $this->PageNo() . "/", 0, 0, "C"); > > //Make PDF//////////////////////////////////////////////////// //Instantiation PDF(child class of FPDF). $pdf = new PDF(); //Defines an alias for the total number of pages. $pdf->AliasNbPages(); //Add a page. $pdf->AddPage(); //left, top, right $pdf->SetMargins(10, 10, 10); //Enable auto page breaks with a margin of 0.5cm. $pdf->SetAutoPageBreak(true, 0.5); //Font type, style(B - bold, I - italic, U - underline, "" - none), font size $pdf->SetFont("Helvetica", 'B', 10); //Set text color in RGB. $pdf->SetTextColor(35, 31, 32); //Sets background color. $pdf->SetFillColor(145, 205, 255); //Set "cursor" x,y position. $pdf->SetXY(10, 30); //Cell(width, height, text, ) $pdf->MultiCell(180, 4, "Multicell text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla eget magna tristique, dignissim enim nec, suscipit purus. Donec tellus nibh, iaculis ut aliquet ut, faucibus a elit. Sed quam dui, dictum et nisi at, dapibus auctor neque. Donec eu metus vitae augue vestibulum finibus. Maecenas condimentum dui orci, sed vestibulum dolor suscipit quis. Proin tempor imperdiet ex a finibus. Maecenas blandit viverra est, ac maximus erat efficitur a. Cras cursus eros et sapien ultrices varius.", 0); $pdf->SetXY(10, 60); $pdf->Cell(30,5, "Some text.", 0); $pdf->SetXY(10, 70); $pdf->Cell(30,5, "Some text.", 0); $pdf->SetXY(10, 80); $pdf->Cell(30,5, "Some text.", 0); //Ln() can be used to move the "cursor" down instead of setting the x,y every time. $pdf->Ln(10); $pdf->Cell(30,5, "Some text.", 0); $pdf->Ln(10); //Degree symbol conversion. $pdf->Cell(30,5, "Temperature: 25" . iconv('UTF-8', 'windows-1252', '°C'), 0); $pdf->Ln(10); //Text() or Write() can also be used to write text insated of Cell(). $pdf->Text(10, 120, "Some other text."); $pdf->Ln(10); $pdf->Write(10, "Some other text."); //Write file as: //I: send the file inline to the browser. The PDF viewer is used if available. //D: send to the browser and force a file download with the name given by name. //F: save to a local file with the name given by name (may include a path). //S: return the document as a string. //Write the PDF file. Output(destination, "path") $pdf->Output('F', dirname(__FILE__) . "\\NewPDF.pdf"); //////////////////////////////////////////////////////////////

Источник

Оцените статью