HTML to PDF with Laravel 8 HTTP Client

Published on: Apr, 19 2020

In this breif guide you will learn how to generate high quality PDF documents using a simple POST request with Laravel 8 and the Docamatic API.

Laravel logo We will be using the Laravel 8 HTTP client in this guide. If you are not familiar with the Laravel HTTP client you can find everything you need to know in the official Laravel HTTP Client Documentation.

Before starting, please check out the Docamatic API Documentation for a better understanding of the endpoints and parameters available to you.

Set your API Key

Assuming you have a Laravel project up and running, the first thing you need to do is obtain your API key from the Docamatic dashboard. Once you have your API key, add it to your .env file as follows:

DOCAMATIC_KEY=YOUR-API-KEY-HERE

Then, add the following to config/services.php:

    'docamatic' => [  
           'key' => env('DOCAMATIC_KEY')  
    ]

Treat your API Key as a password — keep it secret. It should not be included in public repositories, emails or client side code


Making an API Request

For demonstration purposes, create a controller named DocumentController.php as below. In a real world application you may want to use a Job that can be dispatched to a Queue or a Console Command that runs as a scheduled task.

     <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Support\Facades\Http;
    
    class DocumentController extends Controller
    {
        public function create()
        {
            // Send the request
            $response = Http::withToken(config('services.docamatic.key'))->post('https://docamatic.com/api/v1/pdf', [
                'source' => 'https://example.com'
            ]);
    
            // Access the response data via json()
            $data = $response->json();
    
            // Dump out the data array
            dd($data);
        }
    
    }

Error Handling

A nice benefit of using the Laravel HTTP client is that you no longer need to wrap your requests within a try/catch block. Laravel provides convenient methods that you can use to determine if anything went wrong with the request.

// Determine if the status code was >= 200 and < 300...
$response->successful();

// Determine if the response has a 400 level status code...
$response->clientError();

// Determine if the response has a 500 level status code...
$response->serverError();

Blade Template To PDF

Laravel's render method will return a view as a HTML string, which we can use to populate the source parameter. As the Docamatic API doesnt have to look up an external URL, response times are usually quicker when sending raw HTML, opposed to a URL.

        // Blade template to PDF
        $response = Http::withToken(config('services.docamatic.key'))->post('https://docamatic.com/api/v1/pdf', [
            'source' => view('documents.report')->render()
        ]);

Return PDF as Base64 String

You may want to return your document as a base64 string, to save to your own storage or a database. To do so, set the encode parameter to true.

    public function create()
    {
        // Return the PDF as base64 string
        $response = Http::withToken(config('services.docamatic.key'))->post('https://docamatic.com/api/v1/pdf', [
            'source' => 'https://example.com',
            'encode' => true
        ]);

        // Access the response data via json()
        $data = $response->json();

        // Save to storage
        file_put_contents(storage_path('app/document.pdf'), base64_decode($data['document']));
    }

Delete from Storage

To delete a document from storage simply post the transaction_id of the document to be deleted.

    // Delete a document from storage  
    $response = Http::withToken(config('services.docamatic.key'))->delete('https://docamatic.com/api/v1/delete', [  
        'transaction_id' => '8c9a4943-5c13-483f-b3e4-de711e5b7006'  
    ]);