Generate a PDF from Raw HTML and Add a Barcode Using Python

4 Minutes Read

This tutorial shows how to:

  1. Generate a barcode image.
  2. Convert raw HTML code into a PDF.
  3. Place the barcode on the generated PDF.

The workflow uses these PDF.co endpoints:

  • POST /v1/barcode/generate
  • POST /v1/pdf/convert/from/html
  • POST /v1/pdf/edit/add

The HTML-to-PDF endpoint accepts raw HTML code. It does not accept an HTML file as the source input. To convert an existing webpage, use the PDF from URL endpoint instead.

Step 1: Install the Python Dependency

Install the requests package:

python -m pip install requests

Store your PDF.co API key in an environment variable named PDFCO_API_KEY.

Step 2: Prepare the Python Script

Create a file named app.py and add the following code:

import os
import requests

API_KEY = os.environ["PDFCO_API_KEY"]
BASE_URL = "https://api.pdf.co/v1"
OUTPUT_FILE = "document-with-barcode.pdf"

HTML_CONTENT = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body {
            margin: 40px;
            font-family: Arial, sans-serif;
            color: #222;
        }

        h1 {
            color: #2457a7;
        }
    </style>
</head>
<body>
    <h1>Order Confirmation</h1>
    <p>Thank you for your order.</p>
    <p>Order number: 123456</p>
</body>
</html>
"""


def pdfco_post(endpoint, payload):
    response = requests.post(
        f"{BASE_URL}{endpoint}",
        headers={
            "x-api-key": API_KEY,
            "Content-Type": "application/json"
        },
        json=payload,
        timeout=120
    )
    response.raise_for_status()

    result = response.json()

    if result.get("error"):
        raise RuntimeError(result.get("message", "PDF.co request failed"))

    return result


def generate_barcode():
    return pdfco_post(
        "/barcode/generate",
        {
            "type": "Code128",
            "value": "ORDER-123456",
            "name": "barcode.png",
            "inline": False,
            "async": False
        }
    )


def generate_pdf():
    return pdfco_post(
        "/pdf/convert/from/html",
        {
            "html": HTML_CONTENT,
            "name": "order-confirmation.pdf",
            "paperSize": "Letter",
            "orientation": "Portrait",
            "margins": "20px",
            "printBackground": True,
            "mediaType": "print",
            "async": False
        }
    )


def add_barcode(pdf_url, barcode_url):
    return pdfco_post(
        "/pdf/edit/add",
        {
            "url": pdf_url,
            "name": OUTPUT_FILE,
            "images": [
                {
                    "url": barcode_url,
                    "x": 400,
                    "y": 20,
                    "width": 150,
                    "height": 50,
                    "pages": "0"
                }
            ],
            "async": False
        }
    )


def download_file(file_url):
    response = requests.get(file_url, timeout=120)
    response.raise_for_status()

    with open(OUTPUT_FILE, "wb") as output:
        output.write(response.content)


def main():
    barcode = generate_barcode()
    pdf = generate_pdf()
    final_pdf = add_barcode(pdf["url"], barcode["url"])
    download_file(final_pdf["url"])

    print(f"Generated {OUTPUT_FILE}")


if __name__ == "__main__":
    main()

Step 3: Configure the Barcode

Update these values in generate_barcode():

  • type: The barcode format, such as Code128, QRCode, or DataMatrix.
  • value: The information to encode.
  • name: The temporary barcode-image filename.

See the Barcode Generator API for supported formats.

Step 4: Configure the HTML

Replace HTML_CONTENT with the raw HTML markup that should become the PDF.

The /pdf/convert/from/html endpoint accepts the markup through the html parameter. If your application keeps HTML in a local file, Python may read that file into a string first, but the API still receives raw HTML—not the file itself.

To convert a published webpage, call:

POST /v1/pdf/convert/from/url

and supply its URL. See the PDF from HTML documentation and PDF from URL documentation.

Step 5: Position the Barcode

The images object controls where the barcode appears:

  • x and y: Position measured from the upper-left corner.
  • width and height: Barcode dimensions.
  • pages: Target page. 0 represents the first page.

Use the PDF.co PDF Inspector to determine suitable coordinates.

Step 6: Run the Script

Run:

python app.py

The script generates the barcode and PDF as temporary PDF.co files, places the barcode on the first page, and downloads the completed document as:

document-with-barcode.pdf

PDF.co output URLs are temporary. This script downloads the finished PDF immediately so it remains available locally.

Conclusion

You have generated a PDF from raw HTML and added a barcode using Python. The workflow passes the temporary barcode and PDF URLs directly between PDF.co endpoints, eliminating unnecessary uploads and avoiding unsupported HTML-file conversion.

Related Tutorials

See Related Tutorials