ScreenshotNeo

BlogHTML to image & PDF

How to Generate PDFs Automatically from Templates

Learn how to merge template fields with structured data and export reliable PDFs using Word, Google Docs, HTML, APIs, and ScreenshotNeo.

By the ScreenshotNeo team1 October 20268 min read

To generate PDFs automatically from templates, separate the fixed design from changing data, merge them in a repeatable workflow, then export and validate the PDF. The right implementation depends on whether your template is a Word document, Google Doc, or HTML page.

Choose the template workflow

Template source Best fit Typical merge step PDF step
Microsoft Word Contracts, invoices, proposals, letters Insert tags and merge JSON data Request PDF output from Adobe Document Generation API
Google Docs Teams already using Google Drive and Docs Copy a template and replace placeholders with Docs API Add and verify a current export step for your environment
HTML Applications that already render web views Render data into HTML, CSS, and assets Convert the resulting HTML, ZIP, or URL with a PDF service

Compare options by template format, data integration, output requirements, dynamic content, layout reliability, permissions, retries, retention, and the vendor limits you must verify. Adobe documents Word templates with JSON and PDF or Word output, Google documents template copying and placeholder replacement, and Adobe PDF Services documents PDF creation from HTML, ZIP, and URL inputs. Adobe Document Generation API · Google merge guide · Adobe PDF Services

Design a template that can be automated

  1. Keep wording, branding, page structure, and static labels in the template.
  2. Mark changing values with stable placeholders such as {{customer_name}} or the tag syntax required by your selected service.
  3. Define a data contract before writing merge code. Record required fields, optional fields, arrays, calculations, dates, currencies, and image inputs.
  4. Decide what happens when a value is missing. Use a safe default, conditionally remove the section, or fail validation before generation.
  5. Reserve space for long names, addresses, descriptions, and repeated rows. Test the longest realistic values.

Adobe’s documented Word workflow supports text, calculations, repeating elements, and conditional statements. Its Word add-in can help authors insert tags and preview merged output. See Adobe’s dynamic-content documentation.

Option 1: Generate a PDF from a Word template and JSON

Adobe’s documented flow is: author a tagged Word template, prepare JSON with matching field names and shapes, call the Document Generation API, and request a PDF or Word result. The exact authentication headers, asset-upload sequence, region, limits, and current endpoint details can change, so use the live Adobe documentation when wiring credentials and requests.

Example data contract

{
  "invoice_number": "INV-1042",
  "customer": {
    "name": "Example Company",
    "address": "42 Market Street"
  },
  "items": [
    {"description": "Consulting", "quantity": 2, "unit_price": 450},
    {"description": "Support", "quantity": 1, "unit_price": 120}
  ],
  "include_notes": true,
  "notes": "Payment due within 30 days."
}

Implementation sequence

  1. Create and review the Word template.
  2. Add tags for scalar fields, calculated totals, repeated item rows, and conditional notes.
  3. Validate the JSON shape before calling the service.
  4. Submit the template asset and JSON data using the current Adobe API operation.
  5. Save the returned PDF with a deterministic identifier and record the template version and input-data version.

Do not assume a successful API response means a correct document. Inspect missing values, totals, overflow, empty conditional sections, repeated rows, page breaks, fonts, and the final page count.

Option 2: Merge a Google Docs template

Google’s documented pattern starts with a template containing fixed text and placeholders. Copy the template with Drive API files.copy, then replace placeholders with Docs API batchUpdate and ReplaceAllTextRequest. Multiple replacements can be included in one batch update. Google recommends a dedicated account for template ownership while instances are created with end-user credentials. Read the official merge guide.

const requests = [
  {
    replaceAllText: {
      containsText: { text: '{{CUSTOMER_NAME}}', matchCase: true },
      replaceText: data.customerName
    }
  },
  {
    replaceAllText: {
      containsText: { text: '{{INVOICE_NUMBER}}', matchCase: true },
      replaceText: data.invoiceNumber
    }
  }
];

await docs.documents.batchUpdate({
  documentId: copiedDocumentId,
  requestBody: { requests }
});

The cited Google guide establishes document creation and placeholder replacement. It does not establish a complete PDF-export procedure. Add and verify the current Drive export or PDF conversion step, including scopes, permissions, file ownership, and behavior for images and page breaks, before relying on it in production.

Option 3: Render HTML, then convert it to PDF

HTML is useful when your application already produces a page from data. Keep the stages separate: validate data, render HTML and CSS, collect fonts and images, then submit supported HTML, ZIP, or URL input to a PDF conversion service. Adobe documents these input classes in PDF Services. Review supported PDF creation inputs.

Minimal HTML template

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    @page { size: A4; margin: 18mm; }
    body { font: 11pt Arial, sans-serif; color: #222; }
    h1 { margin-bottom: 4mm; }
    .meta { color: #555; margin-bottom: 12mm; }
    table { width: 100%; border-collapse: collapse; }
    th, td { border-bottom: 1px solid #ddd; padding: 6px; text-align: left; }
    .total { text-align: right; font-weight: bold; margin-top: 8mm; }
  </style>
</head>
<body>
  <h1>{{title}}</h1>
  <div class="meta">Prepared for {{customer_name}} · {{invoice_number}}</div>
  {{rows}}
  <div class="total">Total: {{total}}</div>
</body>
</html>

Escape untrusted values before inserting them into HTML. Treat CSS, fonts, external assets, authentication, page breaks, headers, and footers as implementation details to verify with the selected converter.

Build a reliable generation pipeline

  1. Validate input. Check required fields, types, ranges, currency precision, dates, and allowed enum values.
  2. Pin template versions. Store a version or content hash with every generated file.
  3. Generate idempotently. Derive a request key from the template version and normalized input so retries do not create confusing duplicates.
  4. Use bounded retries. Retry transient network or service failures with exponential backoff; do not retry validation errors indefinitely.
  5. Capture diagnostics. Store request identifiers, status, duration, template version, and sanitized error details without logging secrets.
  6. Validate the artifact. Check that the file exists, has the expected PDF signature, opens successfully, and contains required text or page sections.
  7. Protect outputs. Apply access control and retention rules appropriate for invoices, contracts, and personal data.

Common failure modes and fixes

Symptom Likely cause Fix
Placeholder remains visible Name or tag syntax does not match input Compare the exact tag spelling and nesting with the JSON contract.
Repeated rows are empty Array shape or repeat tag is wrong Use the documented repeating-element syntax and pass an array, not a serialized string.
Optional section leaves a blank gap Conditional logic hides text but not its container Put the condition around the entire paragraph, table row, or block.
Totals differ from the source system Rounding or numeric strings are handled inconsistently Define decimal precision and rounding once, then pass normalized values.
Text overlaps or moves to another page Long content exceeds the designed layout Test worst-case data, allow natural expansion, and inspect page breaks.
Images or fonts are missing Assets are inaccessible or unsupported Package assets where required, use accessible URLs or embedded resources, and verify licensing.
Google copy succeeds but replacement fails Wrong document ID, scope, or placeholder text Use the copied file ID, confirm permissions, and match the exact placeholder.
PDF export is not available The merge guide does not cover your export path Implement and verify the current Drive export or a separate converter.
Conversion times out Large assets, complex CSS, or an unreachable URL Reduce asset size, package dependencies, check network access, and use bounded retries.

Performance, reliability, and cost considerations

  • Reuse authenticated clients and connections where the SDK supports it.
  • Keep templates and assets small; large images and web fonts increase conversion time.
  • Queue bursts and apply provider-specific concurrency limits after checking current documentation.
  • Cache immutable template assets, but never reuse a PDF when input data or template version changed.
  • Measure generation duration, failure rate, retry count, output size, and manual correction rate in your own environment.
  • Estimate cost from document volume, conversion operations, storage, and any required queue or worker infrastructure. Confirm current vendor pricing rather than assuming a rate.

Or skip the browser setup

If your template is a public HTML page or a rendered URL, ScreenshotNeo can return a PDF from one GET request. It handles the capture step without maintaining browser automation.

Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and the response reports the result through X-Page-Verdict and X-Billed headers. ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Every plan includes the features; 1,000 screenshots per month are free with no card, and paid plans start at $5 for 3,000 shots.

See the ScreenshotNeo API documentation for PDF options such as paper size, margins, landscape mode, and page ranges.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/invoice/1042 -d format=pdf -o invoice-1042.pdf

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={
        "access_key": "YOUR_API_KEY",
        "url": "https://example.com/invoice/1042",
        "format": "pdf",
    },
    timeout=90,
)
r.raise_for_status()
open("invoice-1042.pdf", "wb").write(r.content)

Node.js

import { writeFile } from 'node:fs/promises';

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com/invoice/1042', format: 'pdf' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`ScreenshotNeo returned ${res.status}`);
await writeFile('invoice-1042.pdf', Buffer.from(await res.arrayBuffer()));

Use a stable, authenticated rendering route when documents contain private data, and configure headers, cookies, or authorization as described in the docs. For repeated jobs, use caching with a deliberate TTL, async jobs with signed webhooks, or bulk capture for up to 100 URLs per call where those options fit your workflow. Create a free ScreenshotNeo account with 1,000 screenshots per month and no card.

Production checklist

  • Template fields and input schema are versioned together.
  • Required and optional values are validated before generation.
  • Long text, empty arrays, missing images, and multi-page output are covered by fixtures.
  • PDFs are checked for openability, required content, and expected metadata.
  • Retries are bounded and idempotent.
  • Secrets are kept out of logs and client-side code.
  • Access, retention, and deletion rules are documented.
  • Current API authentication, limits, export behavior, pricing, and regional availability are verified from vendor documentation.

FAQ

Should the template be Word, Google Docs, or HTML?

Use the format your team can author and review reliably. Word fits tagged business documents, Google Docs fits Drive-centered workflows, and HTML fits applications that already render web content.

Can a template generate both Word and PDF?

Adobe documents PDF and Word output for its Document Generation API. Confirm the current operation and output settings before implementation.

Does Google’s merge guide export a PDF?

The cited guide documents copying a Docs template and replacing text. It does not establish the final PDF-export mechanism, so verify and implement that step separately.

How do I handle changing template designs?

Version templates, keep old versions available for historical regeneration, and record the version used for every output.

When is ScreenshotNeo useful?

It is useful when the document already exists as a rendered URL and you want a PDF capture without running your own browser setup.

Sources: Adobe Document Generation getting started; Adobe PDF Services document generation; Adobe dynamic content and tags; Google merge text into a document; Google Docs API overview.