February 14, 2026 ยท 10 min read

HTML to PDF API: Convert Any Webpage or HTML to Pixel-Perfect PDF

Stack of documents and journal representing PDF generation

Need to convert HTML to PDF programmatically? Whether you're generating invoices, creating reports, archiving web content, or building document workflows โ€” an HTML to PDF API eliminates the headache of running your own rendering infrastructure.

In this guide, we'll cover everything you need to know about converting HTML and URLs to PDF using SnapAPI, including code examples, advanced options, and real-world use cases.

๐Ÿš€ Convert HTML to PDF in Seconds

200 free PDF conversions/month. No credit card required. Full Chromium rendering.

Get Free API Key โ†’

Why Use an HTML to PDF API?

Self-hosted PDF generation is notoriously painful. Libraries like wkhtmltopdf are outdated, Puppeteer requires server resources and maintenance, and browser-based solutions don't scale. An API-based approach gives you:

Quick Start: URL to PDF

The simplest way to generate a PDF is from a URL. One API call, one PDF:

curl "https://api.snapapi.pics/v1/screenshot?url=https://example.com&format=pdf" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -o document.pdf

That's it. SnapAPI loads the page in a full Chromium browser, waits for all resources to load, and generates a pixel-perfect PDF. The result is identical to what you'd get from Chrome's "Print to PDF" feature.

HTML to PDF: Converting Raw HTML

Don't have a hosted URL? You can send raw HTML directly using the html parameter:

curl -X POST "https://api.snapapi.pics/v1/screenshot" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "html": "<html><body><h1>Invoice #1234</h1><p>Total: $99.00</p></body></html>",
    "format": "pdf",
    "pdf_page_size": "A4"
  }' -o invoice.pdf

This is perfect for generating documents from templates. Build your HTML with any templating engine (Handlebars, Jinja2, EJS), then send it to SnapAPI for conversion.

PDF Customization Options

SnapAPI gives you full control over the PDF output. Here are the available options:

๐Ÿ“„ Page Size

A4, Letter, Legal, Tabloid, or custom dimensions. Set pdf_page_size or specify exact pdf_width and pdf_height.

๐Ÿ“ Margins

Control top, right, bottom, and left margins independently. Use pdf_margin for uniform margins or set each individually.

๐Ÿท๏ธ Headers & Footers

Add custom HTML headers and footers with page numbers, dates, and dynamic content using pdf_header and pdf_footer.

๐Ÿ”„ Orientation

Portrait or landscape. Set pdf_landscape=true for wide content like spreadsheets and dashboards.

๐ŸŽจ Background

Include or exclude background colors and images with pdf_print_background=true. Essential for styled documents.

๐Ÿ“Š Page Ranges

Generate specific pages only with pdf_page_ranges. Useful for extracting sections from long documents.

Real-World Use Cases

1. Invoice & Receipt Generation

The most common use case for HTML to PDF conversion. Design your invoice template in HTML/CSS, inject dynamic data, and convert to PDF:

// Node.js โ€” Generate an invoice PDF
const axios = require('axios');
const fs = require('fs');

const invoiceHtml = `
<html>
<head>
  <style>
    body { font-family: 'Helvetica', sans-serif; padding: 40px; }
    .header { display: flex; justify-content: space-between; margin-bottom: 40px; }
    .company { font-size: 24px; font-weight: bold; color: #1a1a2e; }
    .invoice-number { color: #666; font-size: 14px; }
    table { width: 100%; border-collapse: collapse; margin-top: 20px; }
    th { background: #f8f9fa; padding: 12px; text-align: left; border-bottom: 2px solid #dee2e6; }
    td { padding: 12px; border-bottom: 1px solid #eee; }
    .total { font-size: 20px; font-weight: bold; text-align: right; margin-top: 30px; }
  </style>
</head>
<body>
  <div class="header">
    <div class="company">Acme Corp</div>
    <div class="invoice-number">Invoice #INV-2026-001<br>Date: Feb 14, 2026</div>
  </div>
  <table>
    <tr><th>Item</th><th>Qty</th><th>Price</th><th>Total</th></tr>
    <tr><td>API Pro Plan</td><td>1</td><td>$79.00</td><td>$79.00</td></tr>
    <tr><td>Extra Captures (5,000)</td><td>2</td><td>$15.00</td><td>$30.00</td></tr>
  </table>
  <div class="total">Total: $109.00</div>
</body>
</html>`;

const response = await axios.post('https://api.snapapi.pics/v1/screenshot', {
  html: invoiceHtml,
  format: 'pdf',
  pdf_page_size: 'A4',
  pdf_print_background: true,
  pdf_margin: '20mm'
}, {
  headers: { 'Authorization': 'Bearer YOUR_API_KEY' },
  responseType: 'arraybuffer'
});

fs.writeFileSync('invoice.pdf', response.data);
console.log('Invoice generated!');

2. Report Generation

Generate automated reports from dashboards or data. Combine with SnapAPI's screenshot capability to capture charts rendered with Chart.js, D3, or other libraries:

# Python โ€” Generate a report PDF from a dashboard URL
import requests

response = requests.get(
    'https://api.snapapi.pics/v1/screenshot',
    params={
        'url': 'https://your-app.com/dashboard/monthly-report',
        'format': 'pdf',
        'pdf_page_size': 'A4',
        'pdf_landscape': 'true',
        'pdf_print_background': 'true',
        'delay': '3000',  # Wait for charts to render
        'pdf_header': '<div style="font-size:10px;text-align:center">Monthly Report - February 2026</div>',
        'pdf_footer': '<div style="font-size:10px;text-align:center">Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>'
    },
    headers={'Authorization': 'Bearer YOUR_API_KEY'}
)

with open('report.pdf', 'wb') as f:
    f.write(response.content)

3. E-commerce Receipts

Automatically generate order confirmations and receipts after purchase. Integrate into your checkout flow:

// After successful payment
const receipt = await generateReceipt(orderId);  // Your template engine
const pdf = await snapapi.screenshot({
  html: receipt,
  format: 'pdf',
  pdf_page_size: 'A4',
  pdf_margin: '15mm'
});

// Email the PDF to the customer
await sendEmail(customer.email, {
  subject: `Receipt for Order #${orderId}`,
  attachments: [{ filename: 'receipt.pdf', content: pdf }]
});

4. Legal Document Generation

Generate contracts, terms of service, and legal documents from HTML templates with consistent formatting across all devices.

5. Web Page Archiving

Archive important web content as PDFs for compliance, legal, or research purposes. SnapAPI's web archiving capabilities make this easy to automate.

HTML to PDF vs. Other Approaches

API vs. wkhtmltopdf

wkhtmltopdf was the go-to open-source solution for years, but it uses a dated WebKit engine that doesn't support modern CSS (Grid, Flexbox, custom properties). It also requires system-level installation and has known security vulnerabilities. An API like SnapAPI uses the latest Chromium engine with full modern web standards support.

API vs. Puppeteer/Playwright

Running headless Chrome with Puppeteer works but comes with operational overhead: you need servers, memory management (Chromium is hungry), process lifecycle management, and security sandboxing. An API abstracts all of this away. You get the same Chromium rendering without any infrastructure.

API vs. Client-side (jsPDF, html2canvas)

Client-side libraries like jsPDF and html2canvas run in the user's browser. They have limited CSS support, can't handle complex layouts reliably, and produce inconsistent results across browsers. Server-side rendering via API guarantees consistent output.

Advanced Tips

Handling Dynamic Content

If your page loads data via JavaScript (AJAX, fetch), use the delay parameter or wait_for selector to ensure content is fully loaded before PDF generation:

curl "https://api.snapapi.pics/v1/screenshot?\
url=https://app.example.com/report&\
format=pdf&\
wait_for=.chart-loaded&\
delay=2000" \
  -H "Authorization: Bearer YOUR_API_KEY" -o report.pdf

Print-Specific CSS

Use @media print CSS to optimize your HTML for PDF output. Hide navigation, adjust colors for readability, and control page breaks:

@media print {
  nav, footer, .no-print { display: none; }
  body { color: #000; background: #fff; }
  h2 { page-break-before: always; }
  table { page-break-inside: avoid; }
}

Custom Fonts

SnapAPI supports Google Fonts and any web font loaded via @font-face. Your PDFs will render with the exact typography you designed.

Injecting Custom CSS

Need to modify a page's appearance before converting to PDF? Use the css parameter to inject styles:

curl "https://api.snapapi.pics/v1/screenshot?\
url=https://example.com/article&\
format=pdf&\
css=body{font-size:14px}nav{display:none}" \
  -H "Authorization: Bearer YOUR_API_KEY" -o article.pdf

Integration Examples

Node.js with Express

Build a PDF generation endpoint in your Express app. See our full Node.js integration guide for more details:

app.get('/api/generate-pdf', async (req, res) => {
  const { templateId, data } = req.query;
  
  // Render HTML template
  const html = renderTemplate(templateId, JSON.parse(data));
  
  // Convert to PDF via SnapAPI
  const response = await fetch('https://api.snapapi.pics/v1/screenshot', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.SNAPAPI_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ html, format: 'pdf', pdf_page_size: 'A4' })
  });
  
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', `attachment; filename="${templateId}.pdf"`);
  response.body.pipe(res);
});

Python with Flask

Same concept in Python. Check out our Python integration guide:

@app.route('/generate-pdf', methods=['POST'])
def generate_pdf():
    template = request.json.get('template')
    data = request.json.get('data')
    
    html = render_template_string(template, **data)
    
    response = requests.post(
        'https://api.snapapi.pics/v1/screenshot',
        json={'html': html, 'format': 'pdf', 'pdf_page_size': 'A4'},
        headers={'Authorization': f'Bearer {SNAPAPI_KEY}'}
    )
    
    return send_file(
        io.BytesIO(response.content),
        mimetype='application/pdf',
        download_name='document.pdf'
    )

Pricing for HTML to PDF Conversion

PDF generation uses the same credits as screenshots. SnapAPI's pricing starts at:

Unlike competitors that charge extra for PDF generation or require higher-tier plans, SnapAPI includes PDF conversion in every plan โ€” including the free tier.

๐Ÿ“„ Start Converting HTML to PDF

Full Chromium rendering. Custom page sizes, headers, footers. 200 free conversions/month.

Get Free API Key โ†’

Frequently Asked Questions

Can I convert HTML to PDF without installing anything?

Yes. SnapAPI is a cloud API โ€” just send an HTTP request with your HTML or URL, and get a PDF back. No libraries, no servers, no Chromium installation needed.

Does the API support CSS Grid and Flexbox?

Absolutely. SnapAPI uses the latest Chromium engine, which has full support for all modern CSS features including Grid, Flexbox, custom properties, and container queries.

How fast is the conversion?

Typical conversion time is 1-3 seconds depending on page complexity. Static HTML templates convert in under 1 second.

Can I add page numbers to the PDF?

Yes. Use the pdf_footer parameter with the built-in pageNumber and totalPages CSS classes to add automatic page numbering.

What's the maximum page size?

There's no hard limit on page count. Full-page PDFs of very long content (100+ pages) are supported. For extremely large documents, consider splitting into sections.

Last updated: February 14, 2026

Related Reading

Ready to Get Started?

Start capturing screenshots for free โ€” no credit card required.

Start Free โ†’ 200 Screenshots/Month