Python

Integrate DoCreate with Python

This guide shows how to generate PDFs with DoCreate using Python and the requests library.

Prerequisites

Install the requests library if you have not already:

pip install requests

Basic Example

Generate a PDF and save it to a file:

import requests
import os

API_URL = "https://api.docreate.io/api/pdf/external"
API_KEY = os.environ["DOCREATE_API_KEY"]

response = requests.post(
    API_URL,
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    },
    json={
        "html": "<h1>Hello from DoCreate</h1><p>Generated with Python.</p>",
        "css": "h1 { color: #2563eb; } p { color: #555; }",
    },
)

response.raise_for_status()

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

print(f"PDF saved to output.pdf ({len(response.content)} bytes)")

With Error Handling

A production-ready implementation with proper error handling:

import requests
import os
import sys


def generate_pdf(api_key: str, html: str, css: str = "") -> bytes:
    """Generate a PDF using the DoCreate API.

    Args:
        api_key: Your DoCreate API key.
        html: The HTML content for the PDF.
        css: Optional CSS styles.

    Returns:
        The raw PDF bytes.

    Raises:
        RuntimeError: If the API returns an error.
    """
    response = requests.post(
        "https://api.docreate.io/api/pdf/external",
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        },
        json={"html": html, "css": css},
        timeout=30,
    )

    if not response.ok:
        try:
            error_data = response.json()
            message = error_data.get("error", f"HTTP {response.status_code}")
        except ValueError:
            message = f"HTTP {response.status_code}"
        raise RuntimeError(f"PDF generation failed: {message}")

    return response.content


def main():
    api_key = os.environ.get("DOCREATE_API_KEY")
    if not api_key:
        print("Error: DOCREATE_API_KEY environment variable is not set.")
        sys.exit(1)

    html = """
    <h1>Invoice #1042</h1>
    <p>Date: 2026-02-17</p>
    <table>
        <tr><th>Item</th><th>Amount</th></tr>
        <tr><td>Web Development</td><td>$2,500.00</td></tr>
        <tr><td>Hosting (annual)</td><td>$300.00</td></tr>
    </table>
    <p><strong>Total: $2,800.00</strong></p>
    """

    css = """
    body { font-family: Arial, sans-serif; padding: 40px; }
    h1 { color: #1a1a1a; }
    table { width: 100%; border-collapse: collapse; margin: 20px 0; }
    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
    th { background-color: #f5f5f5; }
    """

    try:
        pdf_bytes = generate_pdf(api_key, html, css)
        with open("invoice.pdf", "wb") as f:
            f.write(pdf_bytes)
        print(f"PDF saved to invoice.pdf ({len(pdf_bytes)} bytes)")
    except RuntimeError as e:
        print(f"Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()

Django Integration

Serve a generated PDF as a download from a Django view:

from django.http import HttpResponse
import requests
from django.conf import settings


def invoice_pdf(request, invoice_id):
    invoice = get_object_or_404(Invoice, pk=invoice_id)

    response = requests.post(
        "https://api.docreate.io/api/pdf/external",
        headers={
            "Authorization": f"Bearer {settings.DOCREATE_API_KEY}",
            "Content-Type": "application/json",
        },
        json={
            "html": render_invoice_html(invoice),
            "css": INVOICE_STYLES,
        },
        timeout=30,
    )

    response.raise_for_status()

    return HttpResponse(
        response.content,
        content_type="application/pdf",
        headers={
            "Content-Disposition": f'attachment; filename="invoice-{invoice.number}.pdf"',
        },
    )

Flask Integration

Serve a generated PDF from a Flask route:

from flask import Flask, send_file
import requests
import io

app = Flask(__name__)


@app.route("/invoice/<invoice_id>/pdf")
def invoice_pdf(invoice_id):
    invoice = get_invoice(invoice_id)

    response = requests.post(
        "https://api.docreate.io/api/pdf/external",
        headers={
            "Authorization": f"Bearer {app.config['DOCREATE_API_KEY']}",
            "Content-Type": "application/json",
        },
        json={
            "html": render_invoice_html(invoice),
            "css": INVOICE_STYLES,
        },
        timeout=30,
    )

    response.raise_for_status()

    return send_file(
        io.BytesIO(response.content),
        mimetype="application/pdf",
        as_attachment=True,
        download_name=f"invoice-{invoice.number}.pdf",
    )

Environment Variables

Store your API key as an environment variable. Never hard-code it in your source files.

export DOCREATE_API_KEY=your_api_key_here
python generate_pdf.py

For production deployments, use your platform's secrets management (e.g., environment variables in your hosting provider, a .env file loaded via python-dotenv, or a secrets manager like AWS Secrets Manager or HashiCorp Vault).