Available Now: Explore our latest release with enhanced accessibility and powerful IDP features

How to Build a PDF Viewer in PHP

By Apryse | 2023 Aug 07

Sanity Image
Read time

8 min

In this guide, we’ll review everything you need to know about using PHP to build a PDF viewer. We'll discuss which scenarios are best suited for using PHP to view and render PDFs, then look at two free methods for building a PHP PDF viewer. We’ll also show you how our professional PDF SDK is a flexible and powerful alternative for viewing, editing, and sharing PDF files.

Whether you want to incorporate PDF functionality into your existing PHP application or are just curious about what else you can do with PHP, this guide should help.

Why Build a PHP PDF Viewer?

Copied to clipboard

PHP is a very popular scripting language, as it’s relatively easy to use, multi-functional, and free. While it’s primarily used to make web apps more dynamic and interactive (along with MySQL), it is also useful for scripting command line interface (CLI) programs that help automate common tasks like testing, deployment, and application administration.

It makes sense to pair such a widespread scripting language with a file format as well-known and well used as PDF. PHP by itself is only used to point a web browser to a PDF (much like HTML methods), but you can pair it with libraries to generate PDFs. This makes it possible to use input forms to automatically create simple, customized PDF documents.

Methods for Building a PDF Viewer in PHP for Free

Copied to clipboard

There are two approaches to view PDFs with PHP. The first method is the simplest, and both methods are free of cost.

  • Use PHP code to pass a PDF file to the browser, where you can view it using the native PDF viewer, or
  • Integrate a third-party library using PHP code to generate basic PDFs from either HTML documents or scratch.

Learn how to build a PDF viewer using PHP and Laravel.

Viewing PDFs with PHP Code

Using this simple method, locate the file on the server, then use headers to define aspects of the content, such as type, disposition, and encoding. The code then passes the PHP file to the browser to either read it or download it to the local machine.

For example:

<?php
  
// Store the file name into variable
$file = 'filename.pdf';
$filename = 'filename.pdf';
  
// Header content type
header('Content-type: application/pdf');
  
header('Content-Disposition: inline; filename="' . $filename . '"');
  
header('Content-Transfer-Encoding: binary');
  
header('Accept-Ranges: bytes');
  
// Read the file
@readfile($file);
  
?>

Generating PDFs with Open-Source PHP Libraries

You can generate PDFs using a range of native, open-source PHP libraries. While it’s possible to use them to create complex, sophisticated layouts that support images, tables, colors, and more, these libraries are best used for documents with simple layouts, such as invoices and reports. Nevertheless, these libraries are a great way to incorporate PDF creation capabilities into your PHP application without relying on any external tools.

Let’s take a closer look at two of the most popular PHP PDF libraries: FPDF and TCPDF.

FPDF

FPDF is a PHP class you use to create and edit PDFs with numerous functions for free. It requires no extensions and is used or modified according to your needs, making it a good choice for both commercial and non-commercial applications. Some of its main features include:

  • Page header and footer management
  • Automatic page break
  • Automatic line break and text justification
  • Image support (JPEG, PNG, and GIF)
  • Colors
  • Links

Its longevity, excellent documentation, and base capabilities make it a good choice for those with basic PDF requirements. It’s great for simple documents where the content doesn’t vary much in size. But if you need to display complex pages, including tables with varying lengths of content in each table cell, FPDF falls short. And while it is technically still under active development, it has not seen a significant release since 2015.

How to Install FPDF

  1. Download the FPDF package.
  2. Create a folder and extract the FPDF package into it.
  3. After downloading and extracting the FPDF package, you can generate a basic PDF with the following code:

<?php
require('fpdf/fpdf.php');

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

TCPDF

TCPDF is another free, open-source PHP library. While based on FPDF, it adds a few capabilities, such as SetCellPadding, SetAlpha, WriteHTML, and WriteHTMLCell. The HTML methods are useful for displaying text already formatted with HTML. Other notable features include:

  • Automatic management of page headers and footers
  • Processes for publishing XHTML, CSS code, JavaScript, and forms
  • Native support for JPEG, PNG, and SVG images
  • Automated page breaks, line breaks, and text alignments
  • Page grouping and automatic page numbering

The downside of TCPDF is that it parses only a limited set of HTML tags and embedded CSS, its website and documentation are poor, and technically there isn’t a supported version of TCPDF. The current version will be replaced by tc-lib-pdf.

How to Install TCPDF

  1. Clone the repository.
  2. Create a file inside the folder you cloned and insert the following code snippet:
<?php

	// Include the main TCPDF library (search for installation path).
	require_once('tcpdf.php');

	// create new PDF document
	$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

	// set document information
	$pdf->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 = <<<EOD
<h1>TCPDF PHP Library is easy!</h1>
<i>This is an example of the TCPDF library.</i>
<p>I am using the default header and footer</p>
<p>Please check the source code documentation for more examples of using TCPDF.</p>

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 = '<h4>Second page</h4>';
	
	$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');

?>

Quote

Learn to convert, manipulate, and sign documents effortlessly with PHP PDF Viewer. Unlock the potential of your forms and documents with our expert guidance.

Using Apryse’s WebViewer

Copied to clipboard

Building a PDF viewer with PHP is a viable solution for those with basic PDF viewing needs. However, if your users work with complex layouts and edit and collaborate on PDFs, this requires extensive programming and a good deal of manual work. Instead, you may want to use a fully-featured commercial solution, such as Apryse WebViewer.

Learn more about Apryse's PDF and DOCX editor functionality.

WebViewer Features

  • WebViewer offers a reliable way to view PDFs on the web, since it works seamlessly with every modern browser and OS, including Android, Mac (OS X), and Linux.
  • WebViewer comes with a rich feature set, including annotations, collaboration, bookmarks, digital signatures, advanced search functions, and much more.
  • It includes complete customization, so you control the viewing experience. You also have the flexibility to change the look and feel of WebViewer itself so it matches your web page or application.
  • Many file formats are supported, including DOCX, images, audios, videos, CAD files, and more.
  • It incorporates fast, high-quality rendering without memory problems, even with large and complex documents.

Want to learn more about WebViewer? Check out our comprehensive WebViewer blog.

How to Embed Apryse WebViewer

You can embed WebViewer into your web applications in many ways, using your JavaScript framework of choice, manually or via npm, and headlessly (without the viewer) for document processing applications.

Conclusions

Copied to clipboard

PHP is a useful and versatile scripting language. With a little coding, it is easy to incorporate PDF viewing capabilities into your PHP application, or even use an open-source library to generate PDF files from scratch. However, you are limited to only the most basic viewing and editing capabilities. Instead, a commercial solution such as the Apryse WebViewer offers a more flexible, scalable strategy, along with a host of features for viewing, editing, and sharing PDFs and other documents.

Learn more about Apryse WebViewer or try out features on the interactive demo at Apryse WebViewer showcase.

Sanity Image

Apryse

Share this post

email
linkedIn
twitter