PHP mPDF save file as PDF

PHP mPDF save file as PDF

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

Stefan Bogdanescu

Founder & Senior Architect

Saving mPDF PDFs Directly to the Server File System

When you initialize an mPDF instance and call its Output() method, the default behavior is to stream the generated PDF directly to the browser. This triggers a download or inline preview depending on your HTTP headers. While this works perfectly for displaying reports in the browser, it does not automatically create a file on your server's disk. To achieve persistence, you need to redirect that output stream into a physical file before closing the session or returning control to the client.

The core mechanism relies on the Output() method available in mPDF. This method accepts several arguments, the most critical being the destination string and the format. By default, the destination is set to D (download). To save to a server path, you must explicitly change this parameter to F.

Here is how you modify the existing logic:

// Define the full path where the PDF will be saved
$filePath = $_SERVER['DOCUMENT_ROOT'] . '/reports/report_' . $reportID . '.pdf';

// Create the mPDF instance
include $_SERVER['DOCUMENT_ROOT'].'/include/seo-check/lib/MPDF/mpdf.php';
$mpdf = new mPDF();

// Generate HTML content (assumed to be stored in $HTMLoutput based on your code)
$mpdf->WriteHTML($HTMLoutput);

// Output the PDF directly to a file, not the browser
$mpdf->Output($filePath, 'F');

echo "PDF saved successfully: " . $filePath;

The first parameter, $filePath, allows you to specify any valid writable directory on your server. The second argument, 'F', tells mPDF to write to a file rather than sending bytes to the standard output stream. This approach ensures that even if the browser does not download the file, the data exists permanently in the expected directory.

Handling File Permissions and Paths

One common pitfall when implementing this solution involves server permissions. PHP scripts typically run under a specific user context (often www-data on Linux or IIS_IUSRS on Windows). If you attempt to save a PDF to a directory that your web server process cannot write to, the script will fail silently or throw a permission error, depending on your error reporting settings.

You must ensure the target directory is writable by the PHP user. Before generating the file, it is good practice to verify writability:

if (!is_writable(dirname($filePath))) {
    die('Error: The directory does not have write permissions.');
}

Additionally, be cautious with path concatenation. Using $_SERVER['DOCUMENT_ROOT'] can sometimes lead to issues if your application is installed in a subdirectory or if the root varies between environments. Constructing absolute paths using realpath() adds robustness:

$baseDir = realpath(dirname(__FILE__) . '/../reports');
$filePath = $baseDir . '/report_' . $reportID . '.pdf';

Cleanup and Memory Management

Since mPDF generates the PDF in memory before writing it to disk, large reports can consume significant RAM. If you process many reports concurrently, ensure your PHP memory_limit is configured appropriately. Once the file is successfully written via the 'F' option, the internal buffer of mPDF is cleared, preventing unnecessary memory retention.

You might also consider deleting temporary files or logs if your application generates them during the parsing phase (WSAParser::viewReportResponse). Always ensure that any temporary objects created before the PDF generation are unset or allowed to be garbage collected by PHP's reference counting mechanism.

Integrating with LaravelCompany

If you are managing a suite of reporting tools within the LaravelCompany ecosystem, this file-based approach aligns well with their backend architecture. The https://laravelcompany.com platform often utilizes server-side rendering for complex documents where direct browser interaction is insufficient. Saving the PDF locally allows subsequent processes—such as email attachments or archival systems—to retrieve the file via filesystem access rather than relying on transient HTTP headers. This decouples the generation logic from the delivery mechanism, offering greater flexibility in how you distribute the final report.

Final Considerations

By switching the Output destination to 'F', you transition from a stream-based interaction to a persistent storage model. This requires only minimal code changes but offers significant operational benefits, particularly for audit trails or offline access. Just remember to validate write permissions and manage file paths carefully to avoid runtime errors in production environments.

Our network