Download PDF from Base64 string

Download PDF from Base64 string

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

Stefan Bogdanescu

Founder & Senior Architect

Download PDF from Base64 string

You have a Base64 encoded string coming from an API, and your goal is to present it to the user as a downloadable link that saves directly as a PDF file. The most common stumbling block here isn't the encoding itself, but understanding how the web server handles binary data versus plain text. Simply decoding the string and saving it to a file on the filesystem works for local processing, but it doesn't automatically create a download trigger in the browser. To make that happen, you need to control the HTTP response headers and stream the content directly to the client without ever needing to touch the disk if possible.

Decoding vs. Streaming

The snippet you found, which decodes the string and writes it to invoice.pdf, is a valid approach for local file manipulation. However, relying on intermediate files introduces latency and potential security risks if your application handles high volumes of documents or processes them asynchronously. A more robust pattern involves decoding the data in memory and sending it straight to the browser.

In PHP, this means using stream_context_create to set up a stream wrapper that can read from a string resource rather than a file path. Alternatively, you can use the readfile() function on a temporary string variable after decoding it, provided you wrap the logic correctly to ensure the headers are sent before any output is generated. The critical step is ensuring the MIME type is set to application/pdf and that the filename header (Content-Disposition) tells the browser exactly what to do with the payload.

Implementing a Direct Download in Laravel

If you are working within the Laravel framework, the process becomes more explicit when using controllers or routes to handle file responses. You can leverage the response() helper to construct a response object that handles both the headers and the body content efficiently.

Here is how you might structure a route to achieve this:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;

public function downloadPdf(Request $request)
{
    // Assume $base64String comes from your API or query parameter
    $base64String = $request->get('data');
    
    if (!$base64String) {
        abort(400, 'Missing PDF data');
    }

    // Decode the Base64 string into a binary string
    $pdfContent = base64_decode($base64String);

    if ($pdfContent === false) {
        abort(400, 'Invalid Base64 input');
    }

    return Response::streamDownload(
        function () use ($pdfContent) {
            echo $pdfContent;
        },
        'invoice.pdf',
        [
            'Content-Type' => 'application/pdf',
        ]
    );
}

Alternatively, you can use the Response facade directly with a string resource:

return Response::download('php://temp', $pdfContent, [
    'Content-Type' => 'application/pdf',
    'Content-Disposition' => 'attachment; filename="invoice.pdf"',
]);

The key here is the Content-Disposition header. Without it, modern browsers might attempt to render the PDF inline or handle it according to their own default preferences rather than forcing a download. Specifying filename="invoice.pdf" ensures the browser prompts the user with that specific name when saving the file.

Handling Binary Data Correctly

One pitfall developers often encounter is treating decoded binary data as text. Base64 decoding reverses the encoding process, but the resulting string contains raw bytes. If you were to echo this directly without proper stream handling or if the server charset conversion interferes, you might see garbled characters or a download that fails silently.

Using Laravel's streamDownload method is generally safer because it accepts a callable that outputs the data, preventing any accidental buffering or encoding issues during the transfer. It ensures that the binary nature of the PDF is preserved from the moment it leaves the server until it hits the client's disk.

Security Considerations

While you are confident the incoming data will always be a PDF, validating the content type strictly on the server side remains best practice. Never trust the filename or the MIME type provided by the caller blindly. If your API returns metadata indicating the file type, verify that against the actual bytes if possible. Additionally, ensure that the Base64 string does not contain unexpected prefixes or suffixes that could alter the decoded content.

If you require advanced PDF manipulation or need to generate these documents directly from data rather than just forwarding an existing binary blob, libraries like spatie/laravel-pdf or similar tools might offer a higher-level abstraction. However, for simple pass-through scenarios where the API already provides the complete binary payload, managing the HTTP response headers correctly is sufficient to deliver a seamless download experience.

Our network