How to Add Attachments to PDF Files with PHP
Why Add Attachments to PDF with PHP?
The pdfRest Add to PDF API Tool is a powerful resource that allows developers to programmatically add attachments to PDF documents. This tutorial will demonstrate how to make an API call to the Add to PDF endpoint using PHP.
A real-world example of using Add to PDF might include attaching related documents to a PDF report, such as source data files, additional references, or supplementary materials for a presentation.
Add Attachments to PDF with PHP Code Example
'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' ]; $options = [ 'multipart' => [ [ 'name' => 'file', 'contents' => Utils::tryFopen('/path/to/file', 'r'), 'filename' => '/path/to/file', 'headers' => [ 'Content-Type' => '' ] ], [ 'name' => 'file_to_attach', 'contents' => Utils::tryFopen('/path/to/file', 'r'), 'filename' => '/path/to/file', 'headers' => [ 'Content-Type' => ' ' ] ], [ 'name' => 'output', 'contents' => 'pdfrest_pdf_with_added_attachment' ] ] ]; $request = new Request('POST', 'https://api.pdfrest.com/pdf-with-added-attachment', $headers); $res = $client->sendAsync($request, $options)->wait(); echo $res->getBody(); ?>
Reference: GitHub - datalogics/pdf-rest-api-samples
Breaking Down the Code
The code above demonstrates how to send a multipart/form-data POST request to the pdfRest API to add an attachment to a PDF file:
require 'vendor/autoload.php'; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Utils;
This includes the necessary classes from the Guzzle HTTP client library to send HTTP requests and handle file streams.
$headers = [ 'Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' ];
The API key is provided in the headers for authentication purposes.
$options = [ 'multipart' => [ // ...multipart array contents... ] ];
The options array contains the multipart form data, which includes the main PDF file, the file to attach, and output options.
$request = new Request('POST', 'https://api.pdfrest.com/pdf-with-added-attachment', $headers); $res = $client->sendAsync($request, $options)->wait();
A POST request is created and sent asynchronously. The response is waited on and then the body of the response, which should be the processed PDF, is outputted.
Beyond the Tutorial
This tutorial walked through the process of making an API call to the pdfRest Add to PDF endpoint using PHP and the Guzzle HTTP client. By following the steps outlined above, you can add attachments to PDF documents programmatically.
To explore and demo all of the pdfRest API Tools, visit the API Lab at https://pdfrest.com/apilab/. For more detailed information on the API, refer to the API Reference documentation at https://pdfrest.com/documentation/.
Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at GitHub - datalogics/pdf-rest-api-samples.