Blog

Back to blog posts

PHP code for converting html to PDFs using Api2Pdf now released

Published Jul 18, 2018

We released the full code and documentation on Github: https://github.com/Api2Pdf/api2pdf.php.

As Api2Pdf gains in popularity due to its low-cost and simple to use API for converting HTML to PDFs, we have started to get requests for libraries and packages in other languages. The most heavily requested is PHP. Therefore, we wrote the PHP code for Api2Pdf which hits all of our endpoints: HTML to PDF, URL to PDF, Office Docs to PDF, and Merge PDFs.

Api2Pdf is a wrapper for wkhtmltopdf, Headless Chrome, and LibreOffice and proudly runs on AWS Lambda to allow for extremely low cost PDF conversions with no rate limits or file size limits.

As an aside, PHP is still a gross language, but I digress.

For those that are looking for some quick and dirty PHP code to use with Api2Pdf, you can see this snippet below which connects to the wkhtmltopdf endpoint, converting HTML to PDF. It uses cURL.

 

<?php
function wkhtmltopdf_to_pdf($apikey, $payload) {
$endpoint = "https://v2018.api2pdf.com/wkhtmltopdf/html";
//Initiate cURL.
$ch = curl_init($endpoint);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($payload);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: '.$apikey));
//Execute the request
$json_result = curl_exec($ch);
if ($json_result === false) {
$info = curl_getinfo($ch);
curl_close($ch);
die('error occured during curl exec. Additional info: ' . var_export($info));
}
curl_close($ch);
$result = json_decode($json_result);
return $result;
}
?>

 

Usage is simple:

 

$apikey = "YOUR-API-KEY";
$payload = array("html"=>"<p>Hello World</p>", "inlinePdf"=> true, "fileName"=> "test.pdf");
$res = wkhtmltopdf_to_pdf($apikey, $payload);
echo($res->pdf);

 

For those looking for the full code and sample usage of all methods and endpoints supported by Api2Pdf, please see our Github (https://github.com/Api2Pdf/api2pdf.php) page.

Any and all feedback is welcome.