New: Markdown to PDF built for AI agents, PDF to E-Invoice for Factur-X/ZUGFeRD, and PDF to PDF/A for archive-ready PDF/A-3b.

Convert a Local HTML File to PDF in Python

3 Minutes Read

This tutorial uses Python and PDF.co’s /v1/pdf/convert/from/html endpoint to convert HTML content read from a local file into a PDF. You supply the HTML content and an API key, then save the completed PDF to your computer. This approach is useful when your application already produces HTML and needs a PDF version of that content.

Step 1: Install the Requests Library

To begin, we need to install the requests module, which will help us make HTTP requests to the PDF.co API. In your command line or terminal, type the following command and hit Enter to install the requests library: python -m pip install requests

Step 2: Source Code Samples

Next, copy the Python sample code from this link. Then, paste the code into your editor (e.g., Visual Studio Code, PyCharm, or any editor of your choice).

Step 3: Setup Python Code Configuration

Now, let's configure the Python code to work with your specific settings:

  • API Key: Add your API Key in the designated spot within the code. You can obtain your API Key from your PDF.co Dashboard.
  • HTML File: Specify the name of the HTML file you want to convert into a PDF. Ensure that the HTML file is accessible in your directory.
  • Output PDF Name: Enter the name for the output PDF file.

The initial response accepts a job. Keep its job ID, check that job until it succeeds or fails, and download only after success. A job ID is not a completed PDF.

Setup Python Code Configuration

Step 4: Save Python Program

Once you have configured the code with your API key, file names, and settings, save the Python program in your preferred directory.

Save Python Program

Step 5: Run the Program

After saving the program, run the Python script to see the result. If everything is configured correctly, the program will successfully convert your HTML file into a PDF. Once the program has finished executing, navigate to your Python folder to find the generated PDF file.

Run the Program

Step 6: View PDF Result

Finally, open the output PDF file in your preferred PDF viewer. Here’s an example of how the generated PDF might look once the conversion from HTML is completed.

PDF Result

Compare the saved PDF with the HTML input. Check the text, page breaks, images and fonts.

Local relative paths to images, stylesheets or fonts are not automatically accessible to the remote converter. Use asset URLs that PDF.co can access, or embed supported assets directly in the HTML, then check that they appear correctly in the generated PDF.

This is just one example of the many tasks you can accomplish more quickly and easily in Python using the PDF.co Web API, including generating PDFs with barcodes and converting emails to PDFs.

Related Tutorials

See Related Tutorials