Display PDF on browser

Display PDF on browser

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

Stefan Bogdanescu

Founder & Senior Architect

Streaming PDFs Without Breaking the Browser

When you try to stream a binary file like a PDF directly from PHP, the browser expects a specific contract: correct headers and a clean byte stream. If either is off, the browser defaults to showing the raw binary data as text. The symptom of seeing %PDF-1.4 at the top of your page means the browser received the file content before it finished processing the HTTP response headers.

In your initial code, you correctly set the Content-Type and Content-Disposition headers. However, there is a subtle interaction between how PHP handles output buffering and the order in which headers are sent. The critical rule is that headers must be sent immediately after header() calls, before any actual output (like whitespace) or significant buffering occurs.

Your first snippet used @readfile($file). While this function reads the file into a buffer, it does not necessarily flush it to the client immediately in the context of a continuous stream if the PHP output buffer is active. More importantly, if you are iterating through multiple files in the second edit using echo file_get_contents($file), you risk corrupting the response if the headers aren't set before the loop starts.

The Single File Flow

To display a single PDF correctly, you must ensure no output is sent before the headers. In PHP, this includes even a stray space or newline after the opening < tag of your view file.

Here is the robust pattern for serving a single PDF:

$path = $_SERVER['DOCUMENT_ROOT'] . '/folder_name/resources/uploads/pdf/pdf_label_' . $order['id'] . '.pdf';
$filename = 'pdf_label_' . $order['id'] . '.pdf';

header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
// Optional but recommended for large files to support range requests
header('Accept-Ranges: bytes');
header('Cache-Control: no-cache, must-revalidate');

readfile($path);
exit;

Notice the use of readfile() instead of echo file_get_contents(). The readfile() function sends data directly to the output stream without buffering it in PHP memory first. It returns the number of bytes sent, which is useful for debugging, but here we just need it to trigger the transmission. The exit at the end ensures no additional HTML or errors are appended after the PDF content.

Handling Multiple Files

Your second edit attempted to loop through an array of orders and output multiple PDFs in sequence. Browsers generally treat a single HTTP response as one document. If you send two distinct file headers followed by binary data, the browser will interpret the stream incorrectly because it expects only one Content-Length header that matches the total size of all bytes sent.

To display multiple files sequentially (e.g., generating a report containing several labels), you must merge them into a single PDF document before sending. You cannot simply loop and output separate files with distinct headers; the response body must be a valid, continuous stream representing one logical file.

This is where libraries like php-mepdf or wrappers around FPDF/TCPDF are necessary. The link you found, pdfmerger.codeplex.com, provides an older implementation of merging logic. While the project is archived and may not be directly installable via Composer as a modern package, the underlying concept relies on reading each file into memory, appending the raw bytes to a master buffer, and then writing that combined buffer once at the end.

A safer approach in a modern Laravel or CodeIgniter environment is to use a maintained PDF library like barryvdh/laravel-dompdf or tecnickcom/tcpdf. These libraries handle the complex logic of appending pages and generating the correct cross-reference tables required for valid PDFs.

If you must stick to raw merging without a heavy library, you have to manually construct the PDF header. You read the first file's content, then iterate through the subsequent files, reading their contents into a string variable and concatenating them: $mergedPdf = $firstFileContent . $secondFileContent;. Finally, you apply your headers once, before echoing the entire $mergedPdf string using readfile() or echo.

The pitfall here is ensuring that the file paths are correct and that the files do not contain any extra whitespace at the beginning or end that would invalidate the PDF structure. Always sanitize the path inputs to prevent directory traversal vulnerabilities when constructing these strings.

Our network