Free ways to view, create, and edit PDFs in PHP
Table of contents
As developers, we often encounter the need to work with PDF documents within our PHP applications. Whether it’s displaying reports, generating invoices, or manipulating existing files, handling PDFs is crucial. The good news is that the PHP ecosystem offers a wealth of free and open source libraries to tackle these tasks.
This blog post will explore practical ways to integrate PDF functionality into your PHP projects. It’ll cover everything from simple PDF viewing in the browser to generating PDFs and making structural edits with libraries.
Discover free PHP tools and libraries for PDF functionality: browser-based viewing, TCPDF and FPDF for generation, and advanced manipulation options. Compare open source solutions with commercial libraries for features like annotations, multiformat support, and enterprise security.
Using the browser’s built-in PDF viewer
The simplest way to display a PDF in a PHP web application is to rely on the browser’s native PDF viewer. Modern browsers such as Chrome, Firefox, Edge, and Safari come equipped with this functionality out of the box.
How it works with PHP
PHP serves the PDF file with the correct headers. You can create direct links to your PDF files, and the browser will handle the rendering.
Requirements
- A web server running PHP. You can also run PHP’s built-in server using
php -S localhost:8000. - PDF files you want to display, accessible by your PHP script.
Step-by-step instructions
- Store your PDF files — Place your PDF files in a directory accessible by your web server, such as a
pdfsfolder in your web root. - Create a PHP page to list the PDFs (optional but useful) — You can create a PHP page that dynamically lists the available PDF files:
<!DOCTYPE html><html><head> <title>PDF viewer</title></head><body> <h1>Available PDF documents</h1>
<ul> <?php foreach (glob(__DIR__ . '/pdfs/*.pdf') ?: [] as $filePath): ?> <?php $fileName = basename($filePath); ?> <li> <a href="pdfs/<?= rawurlencode($fileName) ?>" target="_blank" rel="noopener"> <?= htmlspecialchars($fileName, ENT_QUOTES, 'UTF-8') ?> </a> </li> <?php endforeach; ?> </ul>
</body></html>- Link directly to the PDF file — In your HTML, you can create a link to the PDF file. The
target="_blank"attribute will open the PDF in a new tab, using the browser’s built-in viewer:
<a href="pdfs/my_document.pdf" target="_blank" rel="noopener">View my document</a>Embedding a JavaScript PDF viewer
You can use a free JavaScript PDF viewer library for more control over the viewing experience. Examples include a custom user interface (UI) or embedded viewing within your page.
Requirements
- A web server running PHP. You can also run PHP’s built-in server using
php -S localhost:8000. - PDF files that you want to display.
- A free JavaScript PDF viewer library (for example, PDF.js or other open source libraries).
Step-by-step instructions (using PDF.js as an example)
- Select a matching library and worker — This example uses PDF.js 6.3.289 from jsDelivr(opens in a new tab). Pin both files to the same version. PDF.js renders the first page here; navigation, text selection, and other viewer controls require additional work.
- Create
viewer.php— Place a PDF atpdfs/another_document.pdf. Then save the following code asviewer.phpin your web root. Serve it through PHP and open it in a modern browser with JavaScript module support.
<?php$pdfFile = 'pdfs/another_document.pdf';?><!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <title>PDF viewer</title> <style> #pdf-container { width: 80%; margin: 0 auto; overflow: auto; } canvas { display: block; max-width: 100%; height: auto; } </style></head><body> <h1>Embedded PDF page</h1> <p id="status" role="status">Loading PDF…</p> <div id="pdf-container"></div> <script type="module"> import * as pdfjsLib from "https://cdn.jsdelivr.net/npm/pdfjs-dist@6.3.289/build/pdf.min.mjs";
pdfjsLib.GlobalWorkerOptions.workerSrc = "https://cdn.jsdelivr.net/npm/pdfjs-dist@6.3.289/build/pdf.worker.min.mjs"; const pdfUrl = <?= json_encode($pdfFile, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>; const status = document.getElementById("status");
try { const pdf = await pdfjsLib.getDocument(pdfUrl).promise; const page = await pdf.getPage(1); const viewport = page.getViewport({ scale: 1.5 }); const canvas = document.createElement("canvas"); const context = canvas.getContext("2d"); if (!context) throw new Error("Canvas is unavailable."); canvas.width = Math.ceil(viewport.width); canvas.height = Math.ceil(viewport.height); document.getElementById("pdf-container").appendChild(canvas); await page.render({ canvasContext: context, viewport }).promise; status.textContent = `Page 1 of ${pdf.numPages}`; } catch (error) { console.error(error); status.textContent = "The PDF could not be loaded."; } </script></body></html>- Check access to the PDF — The PHP value is a server-selected file path. If you accept user-selected documents, authorize each request and restrict it to permitted files. A public
pdfsfolder is appropriate only for documents intended to be public.
Generating and manipulating PDFs with open source PHP libraries
Open source PHP libraries can generate and, to some extent, edit PDF files. However, most free libraries focus on manipulating existing PDF structure, such as merging, splitting, adding watermarks, or annotating. They don’t directly modify the content within the PDF in a what-you-see-is-what-you-get (WYSIWYG) manner.
The following sections cover some popular open source PHP libraries for PDF generation and manipulation in detail.
FPDF
- Enables you to generate PDFs using PHP code to define elements such as text, images, lines, and shapes at specific coordinates.
- Lightweight and doesn’t require external dependencies (except
Zlibfor compression andGDfor GIF support). - Limited HTML/CSS support.
- Good for generating documents such as invoices, certificates, and reports where layout can be controlled programmatically.
- No package manager such as Composer is needed. Download the
fpdf.phpfile from the official FPDF website and include it in your project.
Example
<?phprequire('fpdf.php');$pdf = new FPDF();$pdf->AddPage();$pdf->SetFont('Arial','B',16);$pdf->Cell(40,10,'Hello world!');$pdf->Output();?>TCPDF
- Offers support for HTML and CSS, Unicode, and other page layout options.
- Supports multiple languages, barcodes, and QR codes.
- No external dependencies for basic functions.
- Can be more memory-intensive than FPDF for complex documents.
- Installation —
composer require "tecnickcom/tcpdf:^6". The example below uses the 6.x API; version 7 is a rewrite that handles fonts differently.
Example
<?phprequire_once __DIR__ . '/vendor/autoload.php';$pdf = new TCPDF();$pdf->AddPage();$pdf->SetFont('helvetica', '', 12);$pdf->Write(0, 'Hello world!');$pdf->Output('example.pdf', 'I');?>Dompdf
- Library for converting HTML and CSS to PDF.
- Supports a range of CSS 2.1 features and some CSS3 features.
- Ideal for generating PDFs from webpage content or HTML templates.
- Requires either the
PDFLib PECLextension (for better performance) or its bundledR&OS CPDFclass. - Installation —
composer require dompdf/dompdf
Example
<?phprequire_once 'vendor/autoload.php';use Dompdf\Dompdf;
$dompdf = new Dompdf();$dompdf->loadHtml('<h1>Hello world</h1><p>This is some HTML content.</p>');$dompdf->render();$dompdf->stream();?>mPDF
- A fork of FPDF and HTML2PDF with extended features.
- Suitable for converting HTML to PDF, with support for UTF-8, CSS styles, and embedded fonts.
- Suitable for projects requiring rich formatting and non-Latin languages.
- Can be slower and consume more memory for large or complex HTML.
- Installation —
composer require mpdf/mpdf
Example
<?phprequire_once __DIR__ . '/vendor/autoload.php';$mpdf = new \Mpdf\Mpdf();$mpdf->WriteHTML('<h1>Hello world!</h1>');$mpdf->Output();?>Snappy
- A PHP wrapper for the wkhtmltopdf command-line tool, which uses the WebKit rendering engine.
- Provides support for HTML-to-PDF conversion, as it uses a browser engine for rendering.
- Requires installing wkhtmltopdf on the server. Note that wkhtmltopdf was archived in January 2023 and is no longer maintained. For new projects, consider Browsershot(opens in a new tab), a Puppeteer-based PHP wrapper from Spatie, as the actively maintained replacement.
- Can have higher server load compared to pure PHP libraries.
- Installation —
composer require knplabs/knp-snappy
Example
<?phprequire_once __DIR__ . '/vendor/autoload.php';use Knp\Snappy\Pdf;
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');$snappy->generate('https://example.com', '/path/to/file.pdf');?>FPDI
- Free PDF Parser (FPDI) is a separate library that enables you to import pages from existing PDF files into FPDF or TCPDF objects.
- It enables you to use the drawing capabilities of FPDF/TCPDF to add content (text, images, etc.) on top of existing PDF pages.
- Not a direct content editor, but enables overlaying and appending to existing PDFs.
- Installation — Install FPDI 2 and its FPDF dependency with
composer require setasign/fpdi:^2.0 setasign/fpdf:^1.8.
Example
<?phprequire_once __DIR__ . '/vendor/autoload.php';
use setasign\Fpdi\Fpdi;
$pdf = new Fpdi();$pdf->AddPage();$pdf->setSourceFile('existing.pdf');$tplIdx = $pdf->importPage(1);$pdf->useTemplate($tplIdx, 0, 0, 210, 297, true); // Use the imported page.
$pdf->SetFont('Arial', '', 12);$pdf->SetTextColor(0, 0, 255);$pdf->SetXY(50, 50);$pdf->Write(0, 'Added text to existing PDF');
$pdf->Output('F', 'modified.pdf');?>PDF Parser
- A library focused on extracting text and metadata from PDF files.
- Not for editing content, but useful for reading information from a PDF before generating a new one based on it.
- Installation —
composer require smalot/pdfparser
Example
<?phprequire_once __DIR__ . '/vendor/autoload.php';
use Smalot\PdfParser\Parser;
// Path to your PDF file.$pdfFilePath = 'path/to/your/document.pdf';
try { $parser = new Parser(); $pdf = $parser->parseFile($pdfFilePath);
$text = $pdf->getText();
echo ""; echo htmlspecialchars($text); echo "";
// You can also access metadata: $details = $pdf->getDetails(); echo "<h2>Metadata:</h2>"; echo ""; print_r($details); echo "";
} catch (\Exception $e) { echo 'Error parsing PDF: ' . $e->getMessage();}?>iLovePDF API client
- While iLovePDF offers online tools, it also offers a PHP library to interact with its REST API.
- Enables you to perform various operations such as merging, splitting, compressing, rotating, and adding watermarks to PDFs.
- Not direct content editing, but provides manipulation features through its cloud service.
- Installation —
composer require ilovepdf/ilovepdf-php
While the library is free to use, the iLovePDF API might have usage limits on its free tier.
Example
Before you can use the iLovePDF API, you’ll need to sign up for an account on the website and obtain an API key.
<?phprequire __DIR__ . '/vendor/autoload.php';
use Ilovepdf\Ilovepdf;
// Replace with your iLovePDF public key.$public_key = 'YOUR_ILOVEPDF_PUBLIC_KEY';
// Path to the PDF file you want to watermark.$pdfFilePath = 'path/to/your/input.pdf';
// Path where the watermarked PDF will be saved.$outputFilePath = 'path/to/your/watermarked.pdf';
try { $ilovepdf = new Ilovepdf($public_key, null); // No secret key needed for basic operations.
$process = $ilovepdf->newTask('watermark'); $process->addFile($pdfFilePath);
// Watermark settings. $process->setText('Confidential', 'Arial', 30, '0', 45, 'center', 'middle', '50'); // Parameters: text, font, size, color (hex or name), rotation, x, y, opacity (0-100).
$process->execute(); $process->download($outputFilePath);
echo 'PDF watermarked successfully and saved to: ' . $outputFilePath;
} catch (\Ilovepdf\Exceptions\IlovepdfException $e) { echo 'iLovePDF API Error: ' . $e->getMessage();} catch (\Exception $e) { echo 'General Error: ' . $e->getMessage();}?>Open source vs. commercial — Which PHP PDF option to use
The best approach depends on your specific needs:
- Basic viewing — Direct links or embedding a PDF in HTML might suffice.
- Enhanced viewing and embedding — JavaScript PDF viewer libraries offer more control.
- Generating new PDFs — FPDF, TCPDF, Dompdf, and mPDF might suffice based on complexity and HTML/CSS support.
- Structural editing — FPDI might suffice for adding content to existing PDFs, while the iLovePDF API provides manipulation features. PDF Parser helps in extracting information.
These libraries cover PDF viewing, creation, and structural manipulation in PHP applications. However, editing PDF content directly with free open source PHP libraries, such as changing existing text or moving elements around, is generally not straightforward. PDF is a complex format, and true content editing usually requires libraries with advanced parsing and rendering capabilities, which are often found in commercial solutions.
For browser-based PDF tools in a PHP application, consider Nutrient Web SDK. The JavaScript SDK runs in the browser while PHP serves your application. Available capabilities depend on your license, selected components, and deployment. Evaluate the following features against your requirements:
- AI-powered document understanding — Analyze text and perform document tasks using AI.
- PDF content editing and manipulation — Edit PDF content, merge/split PDFs, and generate PDFs from templates.
- Conversion tools — Convert MS Office files, convert images to PDFs, render PDFs as images, and much more.
- Optical character recognition (OCR) — Evaluate OCR for searchable scans with the deployment described in the linked guide.
- Customizable interface — Configure behavior, appearance, and tooltips, and hide specific annotation types.
- Comprehensive PDF tools — Annotate, edit, sign, fill forms, redact, and manipulate PDFs.
- Interactive forms — Create, fill, and customize interactive forms programmatically or through the UI.
- Third-party integrations — Integrate with SharePoint, Microsoft Teams, Salesforce, and more.
- Advanced text search and redaction — Search text in documents, or remove sensitive information securely.
- Measurement tools — Measure area, distance, and perimeter in PDFs.
- Bookmark and outline management — Create, edit, and remove bookmarks and structured outlines.
- Document comparison — Compare text across PDFs, analyze content changes, and detect version differences.
Add Nutrient Web SDK to a PHP application
Follow the PHP setup guide to obtain the SDK distribution. For the example below, place nutrient-viewer.js and its matching nutrient-viewer-lib directory together in a publicly served assets directory. Keep these files from the same SDK version.
Open and view PDFs
To load PDFs, use the load method, which takes a configuration object as its parameter. This object specifies where the document appears, its source, your license key, and other settings. For more information, see the guides on loading a document.
Starting with version 2021.4.2, a trial license key is no longer required to evaluate the SDK. You may omit the license key or set it to an empty string. When used without a license key, the SDK applies a watermark to the output file.
<?php$licenseKey = 'YOUR_LICENSE_KEY';$documentPath = 'source.pdf';?>
<!DOCTYPE html><html><head> <title>PDF viewer</title> <script src="assets/nutrient-viewer.js"></script></head><body> <div id="nutrient" style="width: 100%; height: 100vh;"></div>
<script> NutrientViewer.load({ container: "#nutrient", document: <?= json_encode($documentPath, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>, baseUrl: new URL("assets/", window.location.href).href, licenseKey: <?= json_encode($licenseKey, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?> }).then(instance => { console.log("Nutrient web viewer loaded", instance); }).catch(error => { console.error("Failed to load Nutrient web viewer", error); }); </script></body></html>Integrate AI Assistant with Nutrient Web SDK
After setting up the AI Assistant backend, replace the previous load call with an AI-enabled configuration; don’t mount two viewers in the same container. Pass the AI Assistant configuration and a generated JSON Web Token (JWT) to NutrientViewer.load(). For more information, refer to our guide on AI Assistant integration with Nutrient Web SDK:
<?php$sessionId = 'your-session-id';$jwt = 'your-jwt-token';$backendUrl = 'https://your-ai-backend.com';?>
<script> NutrientViewer.load({ container: "#nutrient", document: "source.pdf", baseUrl: new URL("assets/", window.location.href).href, licenseKey: <?= json_encode($licenseKey, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>, aiAssistant: { sessionId: <?= json_encode($sessionId, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>, jwt: <?= json_encode($jwt, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>, backendUrl: <?= json_encode($backendUrl, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?> } }).catch(error => console.error("Failed to load AI Assistant", error));</script>Try it in our playground or get started for free to begin integrating Nutrient PHP PDF viewer into your application.
To learn more, refer to our blogs on how to build a PHP PDF viewer and how to build a PHP image viewer.
Related PHP guides
Other server-side solutions
FAQs
Consider a commercial library (such as Nutrient PDF viewer) when you need advanced features, such as annotation, form filling, PDF editing, or signing. Also consider one when you need dedicated support and regular updates, or when you have strict performance and reliability requirements for crucial PDF workflows.
Validate upload types and sizes, but don’t treat those checks as sanitization. Keep PDF libraries updated, isolate processing with resource limits, restrict file access, and handle malformed inputs. Don’t interpolate untrusted values into shell commands.
Open source PHP libraries primarily focus on server-side generation or basic structural manipulation. Real-time, interactive in-browser annotation and collaborative features typically require dedicated client-side components and backend integrations often found in commercial solutions (such as Nutrient PDF viewer).
Commercial PDF libraries designed for business use (such as Nutrient PDF viewer) often incorporate advanced security features. They also support compliance standards, like digital signature verification and audit trails, and provide dedicated support for implementing legally binding electronic signatures. This can be less straightforward with open source tools and might require significant custom development.
Commercial libraries (such as Nutrient PDF viewer) offer more granular control over PDF structure and content. That control enables precise programmatic manipulation and redaction capabilities that can be complex or unavailable in free alternatives. This often includes better support for PDF specifications.