How to save a page as pdf in php

How to save a page as pdf in php

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to save a page as pdf in php

Saving a dynamic HTML page as a PDF file requires bridging the gap between browser rendering and static document generation. The core challenge isn't just writing code; it's ensuring that the final PDF accurately represents what the user sees on screen, including complex elements like signature capture fields. A common approach for this specific use case is to leverage a headless browser environment rather than trying to force a static library to parse your layout.

The most robust solution involves using a tool like puppeteer or playwright, which runs in a headless Chrome instance. Since you are working within PHP, the standard execution model requires an external process to handle the heavy lifting of rendering. You can achieve this by spawning a Node.js process directly from your PHP script. This separation of concerns allows you to keep your PHP logic for handling database transactions and form submissions while offloading the complex DOM rendering to an environment optimized for it.

To implement this, you first need a local instance of Node.js installed on your server along with the Puppeteer library. Once the environment is ready, your PHP script can execute a command that launches Chrome, navigates to your specific URL, waits for the signature field to be populated, and then triggers the PDF save action.

The following example demonstrates how to construct the PHP command string to invoke Puppeteer:

$script = <<<JS
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: 'new' });
  const page = await browser.newPage();

  // Navigate to your signature page
  await page.goto('https://your-domain.com/signature-page', { waitUntil: 'networkidle2' });

  // Simulate user interaction if necessary, e.g., clicking a "Sign" button
  // await page.click('.sign-button');

  // Wait for the signature canvas to be ready or visible
  await page.waitForSelector('canvas.signature-canvas', { timeout: 10000 }).catch(() => {});

  // Generate PDF
  await page.pdf({
    path: '/var/www/html/generated/signature_page_20231027.pdf',
    format: 'A4',
    printBackground: true,
    margin: { top: '20px', right: '20px', bottom: '20px', left: '20px' }
  });

  await browser.close();
})();
JS;

$phpCommand = "node -e '{$script}'";
exec($phpCommand, $output, $returnCode);

if ($returnCode === 0) {
    // Logic to handle successful file generation or redirect user
}

This approach offers significant control over the rendering process. You can inject custom CSS into the headless browser before generating the PDF to ensure fonts render correctly or that specific background colors are preserved, which often fails with simpler server-side libraries. The waitUntil option in the navigation command is critical here; without it, the script might attempt to generate a PDF before the signature canvas has fully loaded from the DOM.

However, there are inherent trade-offs to this architecture. Spawning a Node.js process for every PDF generation request introduces latency compared to generating a static image or using a lightweight library like TCPDF directly in PHP. For high-traffic applications where every millisecond counts, you might consider caching the rendered PDF files if the underlying HTML content doesn't change frequently. Alternatively, you could queue these requests using a message bus like Redis or RabbitMQ to handle concurrent generation tasks asynchronously, preventing your web server from becoming blocked during heavy rendering cycles.

If you are working within the Laravel ecosystem and prefer not to manage a separate Node environment, libraries like laravel-dompdf provide a direct in-process solution. While convenient, DOMPDF operates differently; it parses HTML into an XML tree and then renders it to PDF. This method is generally less faithful to browser rendering quirks. If your signature page relies heavily on specific CSS3 properties or complex JavaScript events that only fire after user interaction, DOMPDF may not capture the final state unless you meticulously script the DOM manipulation before passing the HTML string to the library.

Regardless of the method chosen, always verify the output file path permissions. Server environments often restrict write access in web directories like public_html. You must ensure the generated PDF is saved to a directory where your web server user has explicit write permissions, or configure the script to save to a system temp directory and then move it afterward.

Our network