HTML to PDF with Laravel 7 HTTP Client
Tags: laravel, showdev, pdf, php
Published: 2020-04-20 10:11:49

Laravel 7 has brough us a super minimal [HTTP client](https://laravel.com/docs/7.x/http-client). I'm a big fan. If you are familair with the powerful Guzzle HTTP client, you may have found it a little unintuitive or overkill for most projects.

In this breif intro, I'll show you how awesomley minimal this HTTP client is, using the [Docamatic API](https://docamatic.com) Docamatic API **(disclaimer!!! - I am the founder)**.


## Getting Started

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](https://docamatic.com/account/api-key). Once you have your API key, add it to your `.env` file as follows:

```php
DOCAMATIC_KEY=YOUR-API-KEY-HERE
```



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

```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](https://laravel.com/docs/7.x/queues#generating-job-classes) that can be dispatched to a Queue or a [Console Command](https://laravel.com/docs/7.x/artisan#generating-commands) that runs as a scheduled task. 

```php
     <?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.

```php
// 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.

```php
        // 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**.

```php
    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.

```php
    // 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'  
    ]);
```