sodcalculator

10 Tech How-To

html2pdf App with Python Requests: A Step-by-Step Guide

Guide 10-28141 · Updated · Step by step

This guide shows you how to use the html2pdf.app API with Python’s requests library to convert HTML content into a PDF file. You’ll learn how to send an HTTP request with your HTML, receive the PDF response, and save it locally. Before starting, you’ll need a free API key from html2pdf.app and Python installed on your machine.

What You’ll Need

  • Python 3.6 or newer installed on your computer.
  • The requests library installed (use pip install requests).
  • An API key from html2pdf.app (sign up for a free account at their website).
  • A text editor or IDE to write the Python script.

Step-by-Step

  1. Get your API key. Log in to your html2pdf.app account and copy your API key from the dashboard. It looks like a long string of letters and numbers.
  2. Set up your Python environment. Open a terminal or command prompt and create a new Python file, for example html2pdf.py. Install the requests library if you haven’t already: pip install requests.
  3. Import the requests library. At the top of your Python file, add import requests.
  4. Define your API key and endpoint. The API endpoint for html2pdf.app is https://api.html2pdf.app/v1/generate. Store your API key in a variable: api_key = "YOUR_API_KEY".
  5. Prepare your HTML content. Create a string variable containing the HTML you want to convert. For example: html_content = "

    This is a test.

    ". You can also read HTML from a file using open('file.html').read().

  6. Build the request payload. The API expects a JSON payload with the HTML and your API key. Construct a dictionary: payload = {'html': html_content, 'api_key': api_key}. Optionally, you can add other parameters like 'filename' or 'margin' (see the API documentation for all options).
  7. Send the POST request. Use requests.post() to send the request to the endpoint: response = requests.post('https://api.html2pdf.app/v1/generate', json=payload).
  8. Check the response status. Verify that the request succeeded by checking response.status_code. A 200 status means success. If it’s not 200, print response.text to see the error message.
  9. Save the PDF. If the request was successful, the response content is the PDF binary data. Open a file in binary write mode and save it: with open('output.pdf', 'wb') as f: f.write(response.content).
  10. Run the script. Execute the Python file. If all goes well, you’ll see an output.pdf file in the same directory.

Common Mistakes

  • Forgetting the api_key in the payload. The API key is required in the JSON body, not as a header. Omitting it will result in a 401 error.
  • Using the wrong endpoint. Some tutorials use the older endpoint https://api.html2pdf.app/v1/pdf; the correct one is /v1/generate.
  • Sending HTML as form data instead of JSON. The API expects JSON. Use the json= parameter in requests, not data=.
  • Not handling non-200 responses. Always check the status code and print the error text to debug.
  • Writing the response as text instead of binary. Use 'wb' mode when saving the PDF, otherwise you’ll get a corrupted file.

Tips

  • Use a dedicated HTML file for complex content. For large HTML, read it from a file to keep your code clean.
  • Set a filename in the payload. Add 'filename': 'my_document.pdf' to the payload; the API will use that as the default filename when you download.
  • Handle errors gracefully. Wrap the request in a try-except block to catch network issues.
  • Test with simple HTML first. Start with a minimal example to confirm your API key works before adding complex styling.
  • Check the API documentation for advanced options. You can set page size, margins, orientation, and more via payload parameters.

Troubleshooting

401 Unauthorized: Your API key is missing or invalid. Double-check that you copied it correctly and that it’s included in the JSON payload.

400 Bad Request: The payload is malformed. Ensure the html field is a string and that you’re sending valid JSON.

500 Internal Server Error: The server encountered an issue. This could be due to invalid HTML or an unsupported parameter. Simplify your HTML and remove optional parameters to test.

PDF is empty or corrupted: You likely saved the response as text. Open the file in binary mode ('wb'). Also verify that response.content is not empty.

Network errors: Check your internet connection. If you’re behind a proxy, configure requests to use it.

Frequently Asked Questions

Do I need a paid plan to use the API?

No, html2pdf.app offers a free tier with a limited number of conversions per month. For heavier usage, you can upgrade to a paid plan.

Can I convert a URL instead of raw HTML?

Yes, you can pass a url parameter instead of html in the payload to convert a live webpage.

How do I set custom page margins?

Add a margin parameter to the payload, e.g., 'margin': '10mm 20mm'. The format is similar to CSS margin shorthand.

Is there a rate limit on the free plan?

Yes, the free plan typically allows a certain number of requests per month. Check the API documentation for the current limit.

Can I use this method in a production environment?

Yes, many developers use the API in production. Just ensure you handle errors and respect rate limits.

What if I need to convert a large HTML file?

You can send large HTML strings, but there may be a size limit. For very large documents, consider splitting them into smaller parts or using the URL option.

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

The whole Tech How-To bed →