This guide shows you how to send a request from your PHP server to the HTML2PDF App API, turning HTML content into a PDF file. You’ll learn the exact steps to authenticate, send your HTML, and handle the returned PDF, whether you’re using cURL or file_get_contents. By the end, you’ll have a working PHP function you can integrate into your own projects.
What You’ll Need
- A server or local environment with PHP 7.0 or higher (any recent version works).
- The cURL extension enabled in PHP (it’s usually enabled by default; you can check with
phpinfo()). - An API key from html2pdf.app. Sign up on their website to get one.
- Basic familiarity with PHP arrays and HTTP requests.
Step-by-Step
- Get your API key. Log in to your html2pdf.app dashboard and copy your secret API key. Keep it private—never expose it in client-side code.
- Decide on the endpoint. The API endpoint for HTML to PDF conversion is
https://api.html2pdf.app/v1/generate. You’ll send a POST request to this URL. - Prepare your HTML content. You can send raw HTML as a string, or you can send a URL to a page you want to convert. For this guide, we’ll use raw HTML. Make sure your HTML is well-formed; the API uses a headless browser to render it.
- Set up the request parameters. The API expects at least two parameters:
html(the HTML content) andapiKey(your secret key). Optionally, you can add parameters likefileName(for the downloaded file name),marginTop,marginBottom, etc. Check the official documentation for a full list. - Write the PHP code using cURL. Here’s a complete function that makes the API call and saves the PDF to a file:
function html2pdf($html, $apiKey, $outputFile) { $url = 'https://api.html2pdf.app/v1/generate'; $data = [ 'html' => $html, 'apiKey' => $apiKey ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode == 200) { file_put_contents($outputFile, $response); return true; } else { // Handle error return false; } } - Call the function with your HTML. For example:
$html = '<h1>Hello, PDF!</h1><p>This is a test.</p>'; $apiKey = 'your_secret_key_here'; if (html2pdf($html, $apiKey, 'output.pdf')) { echo 'PDF generated successfully!'; } else { echo 'Failed to generate PDF.'; } - Handle the response. If the API returns HTTP 200, the response body is the raw PDF binary. Save it directly to a file. If the status code is not 200, the response is usually a JSON error message—decode it to see what went wrong.
- Test with a simple HTML string. Start with a short, simple HTML snippet to confirm your setup works before sending complex documents.
Common Mistakes
- Forgetting to URL-encode the HTML. When using
http_build_query(), encoding is handled automatically. If you manually concatenate the POST fields, useurlencode()on the HTML. - Using GET instead of POST. The API expects a POST request. Sending the HTML in the URL will fail or truncate.
- Exposing your API key. Never put the key in JavaScript or in a public repository. Keep it in a server-side config file.
- Ignoring the response status code. Always check the HTTP code. A 200 means success; anything else means an error, even if the body looks like a PDF.
- Not setting CURLOPT_RETURNTRANSFER. Without it, cURL prints the response directly instead of returning it as a string, breaking your file save.
Tips
- Use
CURLOPT_TIMEOUTto set a reasonable timeout (e.g., 60 seconds) to avoid hanging forever. - If your HTML is large, consider using
CURLOPT_POSTFIELDSwith an array instead of a query string—cURL will handle multipart encoding, which is more reliable for large payloads. - For production, wrap the API call in a try-catch block and log errors to a file for debugging.
- You can pass a URL instead of HTML by using the
urlparameter instead ofhtml. This is handy for converting an existing webpage. - Test with a small PDF first to verify the output looks correct before scaling up.
Troubleshooting
- HTTP 401 Unauthorized: Your API key is wrong or missing. Double-check the key and that you’re sending it as
apiKey. - HTTP 400 Bad Request: The API couldn’t parse your request. Verify that the HTML is not empty and that all required parameters are present. Check for any malformed JSON if you’re sending JSON instead of form data.
- HTTP 413 Payload Too Large: Your HTML is too big. Try reducing the size, or use a URL instead of inline HTML.
- cURL error: SSL certificate problem: On some local servers, the CA bundle isn’t set. You can temporarily add
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);for testing, but never in production. - The PDF is blank: The HTML might not have rendered correctly. Check that your HTML is valid and includes proper CSS if needed. Also, ensure you’re not using JavaScript that requires more time to load—the API waits for page load, but complex JS might need extra wait time (check the
waitForparameter). - file_put_contents fails: Ensure the directory is writable and the path is correct. Use an absolute path to avoid issues.
Frequently Asked Questions
- Can I use file_get_contents instead of cURL? Yes, but you’ll need to set up a stream context with headers and method. cURL is more flexible and recommended for production.
- Does the API support CSS and JavaScript? Yes, the API uses a headless browser, so it renders modern HTML, CSS, and JavaScript. Just make sure your JS is not too slow; you can increase the
waitForparameter if needed. - How do I set page size or margins? Add parameters like
pageSize(e.g., ‘A4’) andmarginTop(in mm) to your POST data. Refer to the API docs for exact names. - Is there a limit on the number of pages? The API has a maximum of 20 pages per PDF. If your content exceeds that, consider splitting it.
- Can I convert a URL instead of raw HTML? Yes, pass the URL in the
urlparameter instead ofhtml. You can also combine both, but the API will prefer theurlif both are present. - What do I do if I get a 500 error? This is an internal server error on the API side. Wait a few seconds and retry. If it persists, check the API status page or contact support.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Secure Guest Account on Windows 11: Step-by-Step
- Stop Outlook From Changing Hyperlink Font
- Hiberfil.sys: What It Is & How to Delete It
- How to Make a Mask on Snapchat: Step-by-Step
- How to Factory Reset iPad If You Forgot Password
- Ubuntu in Windows Store: Which Editions Work?