PDF Generation API

Convert any URL or HTML to a pixel-perfect PDF with one API call. Full Chromium rendering — JavaScript, CSS, web fonts, charts, and dynamic content all print exactly as they appear in the browser.

curl https://api.snapapi.pics/v1/pdf \
  -H "X-Api-Key: sk_live_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/invoice/123", "format": "A4", "print_background": true}' \
  | python3 -c "import sys,json,base64; d=json.load(sys.stdin); open('out.pdf','wb').write(base64.b64decode(d['pdf']))"

Why Use an API Instead of wkhtmltopdf or Puppeteer?

wkhtmltopdf renders pages using an outdated WebKit engine that does not support modern CSS (Grid, Flexbox gaps, CSS variables) or JavaScript. Pages that look correct in Chrome often render incorrectly or incompletely in wkhtmltopdf. Maintaining a Puppeteer or Playwright server adds DevOps overhead — browser crashes, memory leaks, version mismatches, and security concerns around running a headless browser in production.

SnapAPI runs a managed Chromium fleet. Your application makes one HTTPS POST and receives a PDF. No browser process to manage, no memory to tune, no crashes to recover from. The same rendering engine that powers Chrome handles your documents.

SnapAPI's PDF endpoint supports authenticated pages via cookie injection, custom HTTP headers, JavaScript execution before print, print media CSS, and precise margin control. Everything you need for production invoice, report, and document generation.

PDF API Parameters

ParameterTypeDefaultDescription
urlstringrequired*URL to convert to PDF
htmlstringRaw HTML to render as PDF (alternative to url)
formatstringA4Paper size: A4, A3, Letter, Legal, Tabloid
landscapebooleanfalseLandscape orientation
print_backgroundbooleantrueInclude CSS background colors and images
margin_topstring10mmTop margin (e.g. "20mm", "1in", "0")
margin_bottomstring10mmBottom margin
header_templatestringHTML template for page header
footer_templatestringHTML template for page footer (supports page numbers)
wait_forstringCSS selector to wait for before printing

Either url or html is required. When using html, all external resources (CSS, images, fonts) are fetched and rendered. Use wait_for to delay printing until a specific element appears — useful for pages that load data asynchronously before the content is ready to print.

Node.js PDF Generation Example

const fetch = require('node-fetch');
const fs = require('fs');

async function generatePDF(url) {
  const resp = await fetch('https://api.snapapi.pics/v1/pdf', {
    method: 'POST',
    headers: {
      'X-Api-Key': process.env.SNAP_API_KEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      url,
      format: 'A4',
      print_background: true,
      margin_top: '15mm',
      margin_bottom: '15mm',
      footer_template: '<div style="font-size:10px;text-align:center;width:100%">Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>'
    })
  });
  const data = await resp.json();
  fs.writeFileSync('document.pdf', Buffer.from(data.pdf, 'base64'));
  console.log('PDF saved');
}

generatePDF('https://example.com/report');

Common PDF Generation Use Cases

Invoice and Receipt Generation

SaaS platforms generate invoices by rendering an HTML template with customer and billing data, then converting it to PDF with SnapAPI. The HTML template is a regular web page — styled with CSS, using web fonts, and including your company logo as an inline SVG or hosted image. Pass the rendered page URL to the pdf endpoint and receive a production-quality PDF ready for email attachment or customer download.

Report and Dashboard Export

Analytics dashboards with Chart.js, Recharts, or D3 can be exported to PDF using SnapAPI. The full Chromium renderer executes JavaScript and waits for charts to finish animating before printing. Use the wait_for parameter to specify a CSS selector that appears only after your data has loaded — preventing the PDF from capturing an empty loading state.

Certificate and Badge Generation

Online course platforms generate personalized completion certificates as PDFs. Create an HTML template with the student's name, course title, completion date, and your logo. Pass the URL with name and course as query parameters, and SnapAPI returns a certificate PDF that's indistinguishable from one created with a professional design tool — at a fraction of the cost and complexity.

Legal Document Archive

Compliance and legal teams use PDF generation APIs to create tamper-evident snapshots of web-based agreements, terms of service, and policy documents. Record the exact state of a page at the time a user accepted terms by generating a PDF immediately after acceptance. Store the PDF with the acceptance timestamp and IP address as a legally defensible audit trail.

Python PDF Generation

import requests, base64

resp = requests.post(
    'https://api.snapapi.pics/v1/pdf',
    headers={'X-Api-Key': 'sk_live_YOUR_KEY'},
    json={
        'url': 'https://example.com/report/q1-2025',
        'format': 'A4',
        'landscape': False,
        'print_background': True,
        'margin_top': '20mm',
        'wait_for': '.chart-loaded'
    }
)
pdf_bytes = base64.b64decode(resp.json()['pdf'])
with open('report.pdf', 'wb') as f:
    f.write(pdf_bytes)
print(f'PDF generated: {len(pdf_bytes):,} bytes')

HTML Input Mode

Instead of a URL, pass raw HTML directly in the request body. This is useful for generating PDFs from server-rendered templates without deploying a public URL. SnapAPI fetches all external CSS, fonts, and images referenced in the HTML, renders the complete page in Chromium, and returns the PDF.

html_content = '''<html><head>
<link href="https://fonts.googleapis.com/css2?family=Inter&display=swap" rel="stylesheet">
<style>body{font-family:Inter,sans-serif;padding:40px} .total{font-size:2rem;font-weight:700}</style>
</head><body>
<h1>Invoice #1042</h1>
<p>Customer: Acme Corp</p>
<p class="total">Total: $1,200.00</p>
</body></html>'''

resp = requests.post(
    'https://api.snapapi.pics/v1/pdf',
    headers={'X-Api-Key': 'sk_live_YOUR_KEY'},
    json={'html': html_content, 'format': 'A4'}
)

HTML input mode works with any CSS framework, inline styles, or external stylesheets. External resources are fetched from their original URLs, so CDN-hosted fonts and CSS load correctly without any preprocessing.

Frequently Asked Questions

Can I generate PDFs from authenticated pages?

Yes. Use the cookies parameter to pass session cookies that authenticate the browser before loading the page. Alternatively, use a signed URL that embeds an authentication token — your server generates the signed URL and passes it to SnapAPI, which loads it without needing a session cookie.

What is the maximum PDF page count?

There is no hard limit on page count — the PDF length is determined by the height of the rendered page content. Very long documents (100+ pages) may increase response time. Use the webhook parameter for large documents to receive the result asynchronously.

How do page numbers work in headers and footers?

The header_template and footer_template parameters accept HTML. Use the special class names pageNumber and totalPages in span elements — Chromium replaces them with the actual page number and total count during printing.

Sign up at snapapi.pics for 200 free PDF generations per month. No credit card required. The Starter plan at $19/month includes 5,000 API calls across all endpoints — screenshot, PDF, scrape, extract, video, and AI analysis.

Scaling PDF Generation in Production

For applications that generate PDFs on demand — invoices at payment, certificates on course completion, reports on user request — synchronous PDF generation works well. The SnapAPI PDF endpoint typically responds within 2-5 seconds for a standard document. Use this response time to set HTTP timeout expectations in your client and show a loading indicator while the PDF is being generated.

For batch PDF generation — generating hundreds of invoices for a monthly billing run or creating personalized certificates for a cohort of students — use an async queue. Enqueue each PDF generation request as a background job, use the SnapAPI webhook parameter to receive the result without polling, and upload the completed PDF to cloud storage. Track completion with a simple status table in your database.

Caching Generated PDFs

If the same PDF is requested multiple times — for example, a user downloading their invoice repeatedly — cache the PDF bytes after first generation. Store in S3 with a content-addressed key (SHA256 of the source URL and parameters) and serve directly from S3 on subsequent requests, skipping the API call entirely. Set a cache TTL that matches your document update frequency. For invoices that never change after issue, cache indefinitely.

SnapAPI's Business plan at $299/month provides 500,000 API calls — sufficient for generating 16,000 PDFs per day. Even at Pro ($79/month, 50,000 calls), you can generate 1,600 PDFs daily without hitting your quota. For most SaaS applications with under 10,000 active customers, the Starter plan handles PDF generation comfortably at $19/month.

PHP PDF Generation Example

SnapAPI works with any language or framework. Here is a minimal PHP example using cURL to generate a PDF from a URL and save it to disk. The response body contains JSON with a base64-encoded pdf field. Decode it with base64_decode and write the raw bytes to a file. The same pattern works in Laravel using Http::post(), in Symfony using the HttpClient component, or in any PHP project using Guzzle. Store your API key in an environment variable and retrieve it with getenv or , never hardcode it in source files shared with your team.

All SnapAPI PDF parameters — format, landscape, margins, headers, footers, wait conditions — are available in every language. The API is language-agnostic: a JSON POST with your API key in the header, a JSON response with your PDF in base64. Sign up at snapapi.pics for 200 free PDF generations per month and evaluate the output quality against your specific documents before choosing a plan.

pdf generation api html to pdf url to pdf chromium wkhtmltopdf alternative invoice report certificate node python ruby php