Examples

Below are example scripts that demonstrate how to submit a PDF generation job to Influxion, poll for its completion, and download the resulting PDF file.

The examples send the HTML and CSS inline in the /pdf/generate request. For invoice/profile templates with separate binary images and CSS scaling, see Bundled images and scaling and docs/examples/generate_bundle.py.

All examples define configuration parameters (such as BASE_URL and polling intervals) at the top of the script for easy customization.

Available examples

Python (httpx)

generate_pdf.py

Bash (curl & jq)

generate_pdf.sh

PowerShell (Invoke-RestMethod)

generate_pdf.ps1

Markdown to PDF (Python, httpx)

generate_markdown_pdf.py

Python example

#!/usr/bin/env python3
"""
Example script to generate a PDF via the Influxion API, poll until it's ready,
and download the resulting PDF file.
"""
import os
import re
import time
from pathlib import Path

import httpx

# Configuration
BASE_URL = "https://influxion.nedomkull.com"
TIMEOUT = 10.0  # seconds for HTTP requests
POLL_INTERVAL = 1.0  # seconds between status checks


def _load_env_from_file(path: Path) -> None:
    if not path.exists() or not path.is_file():
        return
    for raw_line in path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        if line.startswith("export "):
            line = line[len("export "):].strip()
        if "=" not in line:
            continue
        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip().strip('"').strip("'")
        if key:
            os.environ.setdefault(key, value)


def _load_local_dotenv() -> None:
    script_env = Path(__file__).resolve().parent / ".env"
    cwd_env = Path.cwd() / ".env"
    _load_env_from_file(script_env)
    if cwd_env != script_env:
        _load_env_from_file(cwd_env)


_load_local_dotenv()

CLIENT_ID = os.environ.get("INFLUXION_CLIENT_ID", "Or set it here")
CLIENT_SECRET = os.environ.get("INFLUXION_CLIENT_SECRET", "Or set it here")

PDF_STANDARD = "pdf/ua-1"
SIGN_KEY_ID = "B1B9EA5014C096A99CFA462A00AC24ED40507BCB"
HTML_TEMPLATE = "<html><body><h1>{{ data.message }}</h1></body></html>"
CSS_TEMPLATE = "body { font-family: 'Futura PT', 'DejaVu Sans', sans-serif; } h1 { color: #1d4ed8; }"


def get_token(client: httpx.Client) -> str:
    data = {
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "scope": "api://d88ae758-e67d-492d-bcc6-63f560ee1f04/.default"
    }
    response = client.post("/auth/token", data=data)
    response.raise_for_status()
    return response.json()["access_token"]


def main() -> None:
    client = httpx.Client(base_url=BASE_URL, timeout=TIMEOUT)
    token = get_token(client)
    client.headers.update({"Authorization": f"Bearer {token}"})

    # Define the payload for PDF generation
    payload = {
        "data": {
            "message": "Hello World!",
        },
        "document_id": None,
        "pdf_standard": PDF_STANDARD,
        "sign_key_id": SIGN_KEY_ID,
        "html_template": {"filename": None, "content": HTML_TEMPLATE},
        "css_template": {"filename": None, "content": CSS_TEMPLATE},
    }

    # Submit a generate request
    response = client.post("/pdf/generate", json=payload)
    response.raise_for_status()
    job_id = response.json().get("job_id")
    if job_id is None:
        raise RuntimeError(f"No job_id returned: {response.text}")
    print(f"Job created with ID: {job_id}")

    # Poll for job completion
    while True:
        response = client.get(f"/pdf/{job_id}")
        response.raise_for_status()
        data = response.json()
        status = data.get("status")
        print(f"Job status: {status}")
        if status == "Done":
            break
        if status == "Error":
            error = data.get("error")
            raise RuntimeError(f"PDF generation failed: {error}")
        time.sleep(POLL_INTERVAL)

    # Download the resulting PDF
    response = client.get(f"/pdf/{job_id}/download")
    response.raise_for_status()
    content_disp = response.headers.get("Content-Disposition", "")
    match = re.search(r'filename="(.+)"', content_disp)
    if match:
        output_file = match.group(1)
    else:
        output_file = f"{job_id}.pdf"
    with open(output_file, "wb") as f:
        f.write(response.content)
    print(f"PDF downloaded to {output_file}")


if __name__ == "__main__":
    main()

Bash example

#!/usr/bin/env bash
# Example: Generate a PDF via the Influxion API with OAuth2, poll until done, and download it.
# Requires: curl, jq

# Prerequisites:
#   export INFLUXION_AZURE_TENANT_ID=<tenant-id>
#   export INFLUXION_CLIENT_ID=<client-id>
#   export INFLUXION_CLIENT_SECRET=<client-secret>
#   export BASE_URL=https://influxion.nedomkull.com   # or your API URL

# Configuration
POLL_INTERVAL=1
PDF_STANDARD="pdf/ua-1"
SIGN_KEY_ID="B1B9EA5014C096A99CFA462A00AC24ED40507BCB"
HTML_TEMPLATE='<html><body><h1>{{ data.message }}</h1></body></html>'
CSS_TEMPLATE='body { font-family: "Futura PT", "DejaVu Sans", sans-serif; } h1 { color: #1d4ed8; }'

# OAuth2 credentials
CLIENT_ID="$INFLUXION_CLIENT_ID"
CLIENT_SECRET="$INFLUXION_CLIENT_SECRET"
TENANT_ID="$INFLUXION_AZURE_TENANT_ID"
SCOPE="https://graph.microsoft.com/.default"

# Obtain access token
get_token() {
  curl -sS -X POST "$BASE_URL/auth/token" \
    -d "client_id=$CLIENT_ID&client_secret=$CLIENT_SECRET&scope=$SCOPE" \
    | jq -r .access_token
}

TOKEN=$(get_token)
AUTH_HEADER="Authorization: Bearer $TOKEN"

# Submit a generation request and return the job ID
generate_pdf() {
  jq -n \
    --argjson data '{"message":"Hello, world!"}' \
    --arg std "$PDF_STANDARD" \
    --arg sig "$SIGN_KEY_ID" \
    --arg html "$HTML_TEMPLATE" \
    --arg css "$CSS_TEMPLATE" \
    '{data: $data, document_id: null, pdf_standard: $std, sign_key_id: $sig, html_template: {filename: null, content: $html}, css_template: {filename: null, content: $css}}' | \
  curl -sS -X POST "$BASE_URL/pdf/generate" \
    -H "Content-Type: application/json" \
    -H "$AUTH_HEADER" \
    --data @- | jq -r .job_id
}

# Poll until the job finishes or errors out
poll_until_done() {
  local job_id=$1
  while true; do
    status=$(curl -sS -X GET "$BASE_URL/pdf/$job_id" -H "$AUTH_HEADER" | jq -r .status)
    echo "Job status: $status"
    if [[ "$status" == "Done" ]]; then
      break
    elif [[ "$status" == "Error" ]]; then
      error=$(curl -sS -X GET "$BASE_URL/pdf/$job_id" -H "$AUTH_HEADER" | jq -r .error)
      echo "PDF generation failed: $error" >&2
      exit 1
    fi
    sleep $POLL_INTERVAL
  done
}

# Download the resulting PDF, preserving the filename
download_pdf() {
  local job_id=$1
  content_disp=$(curl -sSI -X GET "$BASE_URL/pdf/$job_id/download" -H "$AUTH_HEADER" | grep -i Content-Disposition)
  filename=$(echo "$content_disp" | sed -n 's/.*filename="\([^\"]*\)".*/\1/p')
  [[ -z "$filename" ]] && filename="${job_id}.pdf"
  curl -sS -X GET "$BASE_URL/pdf/$job_id/download" -H "$AUTH_HEADER" --output "$filename"
  echo "PDF downloaded to $filename"
}

# Main workflow
job_id=$(generate_pdf)
echo "Job created with ID: $job_id"
poll_until_done "$job_id"
download_pdf "$job_id"

PowerShell example

#!/usr/bin/env pwsh
<#
Example: Generate a PDF via the Influxion API with OAuth2, poll until done, and download it.

Prerequisites:
  - Set environment variables:
      $env:INFLUXION_AZURE_TENANT_ID
      $env:INFLUXION_CLIENT_ID
      $env:INFLUXION_CLIENT_SECRET
  - Point $BaseUrl at your Influxion API server.
#>

# Configuration
$BaseUrl      = "https://influxion.nedomkull.com"    # Change to your API URL
$PollInterval = 1                                    # Seconds between status checks
$PdfStandard  = "pdf/ua-1"
$SignKeyId    = "B1B9EA5014C096A99CFA462A00AC24ED40507BCB"
$HtmlTemplate = '<html><body><h1>{{ data.message }}</h1></body></html>'
$CssTemplate  = 'body { font-family: "Futura PT", "DejaVu Sans", sans-serif; } h1 { color: #1d4ed8; }'

# OAuth2 credentials (from environment)
$TenantId     = $env:INFLUXION_AZURE_TENANT_ID
$ClientId     = $env:INFLUXION_CLIENT_ID
$ClientSecret = $env:INFLUXION_CLIENT_SECRET
$Scope        = "https://graph.microsoft.com/.default"

# Obtain an access token
function Get-Token {
    $body = @{ client_id = $ClientId; client_secret = $ClientSecret; scope = $Scope }
    $resp = Invoke-RestMethod -Method Post -Uri "$BaseUrl/auth/token" `
        -Body $body -ContentType "application/x-www-form-urlencoded"
    return $resp.access_token
}

$token   = Get-Token
$headers = @{ Authorization = "Bearer $token" }

# Prepare the PDF generation payload
$payload = @{ data          = @{ message = "Hello, world!" }
               document_id   = $null
               pdf_standard  = $PdfStandard
               sign_key_id   = $SignKeyId
               html_template = @{ filename = $null; content = $HtmlTemplate }
               css_template  = @{ filename = $null; content = $CssTemplate } } | ConvertTo-Json -Depth 4

# Submit the PDF generation job
$response = Invoke-RestMethod -Method Post -Uri "$BaseUrl/pdf/generate" `
    -Headers $headers -Body $payload -ContentType "application/json"
$jobId = $response.job_id
if (-not $jobId) { Write-Error "No job_id returned"; exit 1 }
Write-Host "Job created with ID: $jobId"

# Poll until the job is done or errors out
do {
    Start-Sleep -Seconds $PollInterval
    $statusResp = Invoke-RestMethod -Method Get -Uri "$BaseUrl/pdf/$jobId" -Headers $headers
    $status = $statusResp.status
    Write-Host "Job status: $status"
    if ($status -eq 'Error') {
        Write-Error "PDF generation failed: $($statusResp.error)"
        exit 1
    }
} until ($status -eq 'Done')

# Download the resulting PDF
$head = Invoke-WebRequest -Method Head -Uri "$BaseUrl/pdf/$jobId/download" -Headers $headers -UseBasicParsing
$contentDisp = $head.Headers['Content-Disposition']
if ($contentDisp -match 'filename="(.+)"') { $filename = $matches[1] } else { $filename = "$jobId.pdf" }
Invoke-RestMethod -Method Get -Uri "$BaseUrl/pdf/$jobId/download" `
    -Headers $headers -OutFile $filename
Write-Host "PDF downloaded to $filename"

Markdown example

Converts a Markdown file with /pdf/generate and "input_type": "markdown", optionally with a custom stylesheet: python generate_markdown_pdf.py notes.md --css my-style.css.

#!/usr/bin/env python3
"""
Convert a Markdown file to PDF via the Influxion API.

Usage:
    python generate_markdown_pdf.py notes.md
    python generate_markdown_pdf.py notes.md --css my-style.css -o notes.pdf
    python generate_markdown_pdf.py notes.md --css my-style.css --no-default-css

The CSS file is appended to Influxion's bundled Markdown stylesheet unless
--no-default-css is given. Credentials are read from INFLUXION_CLIENT_ID and
INFLUXION_CLIENT_SECRET (environment or .env), the server from INFLUXION_BASE_URL.
"""
import argparse
import os
import time
from pathlib import Path

import httpx

DEFAULT_BASE_URL = "http://localhost:8000"
POLL_INTERVAL = 1.0  # seconds between status checks


def load_dotenv(path: Path) -> None:
    if not path.is_file():
        return
    for line in path.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))


def main() -> None:
    parser = argparse.ArgumentParser(description="Convert Markdown to PDF with Influxion.")
    parser.add_argument("markdown", type=Path, help="Markdown file to convert")
    parser.add_argument("--css", type=Path, help="Custom CSS file")
    parser.add_argument("--no-default-css", action="store_true", help="Do not include the bundled stylesheet")
    parser.add_argument("--title", help="Document title (default: first H1)")
    parser.add_argument("--lang", default="en", help="Document language code (default: en)")
    parser.add_argument("--pdf-standard", help="e.g. pdf/a-1b or pdf/ua-1")
    parser.add_argument("--sign-key-id", help="Key Vault certificate id for signing")
    parser.add_argument("-o", "--output", type=Path, help="Output file (default: <markdown name>.pdf)")
    args = parser.parse_args()

    load_dotenv(Path.cwd() / ".env")
    base_url = os.environ.get("INFLUXION_BASE_URL", DEFAULT_BASE_URL)
    output = args.output or args.markdown.with_suffix(".pdf")

    payload = {
        "input_type": "markdown",
        "markdown_template": {"filename": args.markdown.name, "content": args.markdown.read_text(encoding="utf-8")},
        "include_default_css": not args.no_default_css,
        "title": args.title,
        "language": args.lang,
        "pdf_standard": args.pdf_standard,
        "sign_key_id": args.sign_key_id,
    }
    if args.css:
        payload["css_template"] = {"filename": args.css.name, "content": args.css.read_text(encoding="utf-8")}

    token_form = {
        "client_id": os.environ["INFLUXION_CLIENT_ID"],
        "client_secret": os.environ["INFLUXION_CLIENT_SECRET"],
    }
    if scope := os.environ.get("INFLUXION_SCOPE"):
        token_form["scope"] = scope

    with httpx.Client(base_url=base_url, timeout=120) as client:
        response = client.post("/auth/token", data=token_form)
        response.raise_for_status()
        client.headers["Authorization"] = f"Bearer {response.json()['access_token']}"

        response = client.post("/pdf/generate", json=payload)
        response.raise_for_status()
        job_id = response.json()["job_id"]

        while True:
            status = client.get(f"/pdf/{job_id}")
            status.raise_for_status()
            info = status.json()
            if info["status"] == "Done":
                break
            if info["status"] == "Error":
                raise SystemExit(f"PDF generation failed: {info.get('error')}")
            time.sleep(POLL_INTERVAL)

        download = client.get(f"/pdf/{job_id}/download")
        download.raise_for_status()
        output.write_bytes(download.content)
    print(f"Wrote {output}")


if __name__ == "__main__":
    main()