sodcalculator

10 Tech How-To

Convert HTML Invoices to PDFs for Automated Processing

Guide 10-60084 · Updated · Step by step

Converting HTML invoices to PDFs is a common step in automating accounts payable, document management, or data extraction workflows. This guide shows you how to reliably turn HTML files into PDFs using free, scriptable tools, so you can then run OCR, parse text, or archive them. You’ll need a computer with Python installed (or a command-line environment) and the ability to install packages.

What You’ll Need

  • A computer running Windows, macOS, or Linux
  • Python 3.7 or newer (check with python --version)
  • An HTML invoice file (or a folder of them)
  • Basic comfort with the command line/terminal
  • Internet access to install Python packages

Step-by-Step

  1. Set up a working directory. Create a folder where your HTML invoices and the output PDFs will live. For example, invoice_conversion on your desktop. Place your HTML files inside a subfolder called input.
  2. Install a PDF conversion library. Open your terminal (Command Prompt on Windows, Terminal on macOS/Linux) and install one of the most reliable libraries: pip install pdfkit or pip install weasyprint. WeasyPrint is often easier because it handles modern CSS well and doesn’t require a separate binary. For this guide, we’ll use WeasyPrint.
  3. Write a simple Python script. Create a file named convert.py in your working directory. Open it in a text editor and paste the following code:
    import os
    from weasyprint import HTML
    
    input_folder = "input"
    output_folder = "output"
    os.makedirs(output_folder, exist_ok=True)
    
    for filename in os.listdir(input_folder):
        if filename.lower().endswith(".html") or filename.lower().endswith(".htm"):
            input_path = os.path.join(input_folder, filename)
            output_path = os.path.join(output_folder, filename[:-5] + ".pdf")
            HTML(input_path).write_pdf(output_path)
            print(f"Converted {filename} to {output_path}")
    
  4. Run the script. In your terminal, navigate to your working directory (cd path/to/invoice_conversion) and run python convert.py. If all goes well, you’ll see a message for each file, and the PDFs will appear in the output folder.
  5. Verify the output. Open a few PDFs to ensure the layout looks correct. Check that tables, fonts, and images render as expected. If something looks off, proceed to the Troubleshooting section.
  6. Automate further (optional). To process new invoices automatically, you can schedule the script to run at a set time (using Task Scheduler on Windows, cron on macOS/Linux) or trigger it when files are added to a folder using a watch script.

Common Mistakes

  • Forgetting to install the library. The script will fail with a ModuleNotFoundError if WeasyPrint isn’t installed.
  • Using relative paths incorrectly. The script assumes the input and output folders are in the same directory as convert.py. If you run the script from elsewhere, use absolute paths.
  • Ignoring external resources. If your HTML references local images or CSS files with relative paths, the PDF may miss them. Ensure the HTML files are self-contained or that the paths are correct relative to the HTML file’s location.
  • Not handling HTML entities or special characters. Some HTML files may contain characters like & or < that need proper encoding. WeasyPrint usually handles this, but malformed HTML can cause issues.

Tips

  • Use a headless browser for complex layouts. If your invoices rely heavily on JavaScript to render (e.g., dynamic totals), WeasyPrint won’t execute JS. In that case, use a tool like Playwright or Puppeteer to render the HTML in a real browser and then print to PDF.
  • Set PDF metadata. You can add a title, author, or subject to the PDF by passing a pdf_metadata dictionary to write_pdf.
  • Batch process with parallel execution. For hundreds of files, consider using Python’s concurrent.futures to speed things up.
  • Test on one file first. Before running the script on a whole folder, test with a single invoice to catch issues early.

Troubleshooting

  • PDFs are blank or missing content. This usually means the HTML wasn’t fully rendered. Check if the HTML relies on JavaScript. If so, switch to a browser-based converter. Also, verify that the HTML file isn’t empty or corrupted.
  • Fonts look wrong or are missing. WeasyPrint uses system fonts. If the invoice specifies a font not installed on your system, it will fall back to a default. Install the required fonts or embed them in the HTML via base64.
  • Error: cannot find library on Linux. WeasyPrint depends on some system libraries like libpango. Install them using your package manager, e.g., sudo apt install libpango-1.0-0 libpangocairo-1.0-0 on Ubuntu.
  • PDFs are generated but have broken layout. This often happens with complex CSS. Try using HTML(string=...) instead of a file path if the HTML is a string, or ensure the HTML is well-formed. You can also use the base_url parameter to help resolve relative URLs.
  • Script runs but no PDFs appear. Double-check the input folder name and that the files have .html or .htm extensions. Also, check if the script printed any errors—maybe the output folder wasn’t created due to permission issues.

Frequently Asked Questions

Can I convert HTML to PDF without Python? Yes, you can use command-line tools like wkhtmltopdf or browser extensions, but Python with WeasyPrint offers more control and automation.

Will the PDFs be searchable? If the HTML contains text, the PDF will have a text layer, making it searchable. If you need OCR for scanned images, you’ll need an additional step like Tesseract.

Can I add headers and footers to the PDFs? Yes, WeasyPrint supports CSS paged media, allowing you to add page numbers, headers, and footers via @page rules.

Does this work with HTML emails? Yes, as long as the HTML is well-formed. However, email HTML often uses inline styles, which WeasyPrint handles fine.

How do I handle multiple files in subfolders? Modify the script to use os.walk() to recursively find HTML files.

Is there a way to convert HTML to PDF using a web service? Yes, many online APIs exist, but they may have costs or privacy concerns. Local conversion keeps your data secure.

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 →