Using api2pdf for reliable PDF generation
posted 2019.07.26 by Clark Wilkins, Simplexable

We've just switched our service management platform servicd over to using to generate PDFs. Since the documentation for setting this up is not completely clear, I thought I'd share some of my experience in getting this to run in a PHP 5.6.x environment.

embed your CSS

I was unsuccessful in getting api2pdf to resolve the path to our CSS code, so I decided to just embed it in the header of the HTML before it's sent over. No significant difference in resource usage IMO, and we know it's current. In our code, the page we construct to use for a PDF is in $html. In the middle of the header, we add <style> + the full CSS + </style>.

putting the PDF inline in the window

Once the HTML is setup, we call the service like this:

// PDF generator api2pdf

require_once 'external/vendor/api2pdf/api2pdf.php/src/Api2Pdf.php';
require_once 'external/vendor/api2pdf/api2pdf.php/src/ApiResult.php';
use Api2Pdf\Api2Pdf;$apiClient = new Api2Pdf('my API');

try {

$result = $apiClient->headlessChromeFromHtml( $html );
$pdfLink = $result->getPdf();

header( 'Content-type: application/pdf');
header( 'Content-Disposition: inline; filename="' . $pdfName . '"' );
header( 'Content-Transfer-Encoding: binary' );
header( 'Accept-Ranges: bytes' );
@readfile ( $pdfLink );


catch ( Exception $result ) { ... }

This works beautifully. I recommend the service whole-heartedly.