How to Convert HTML to PDF or DOCX in a Workflow

How to Convert HTML to PDF or DOCX in a Workflow

Summary

  • A 100-page PDF should render in seconds to tens of seconds, not two to three hours; the bottleneck is the workflow architecture, not the renderer itself.
  • Self-hosted tools such as Puppeteer, Gotenberg, and WeasyPrint offer control and data residency, while commercial APIs offload scaling and add storage/delivery features.
  • Treat document generation as an async background job: author print CSS explicitly, serve fonts from the same origin, and handle authenticated templates with framework bridges or pre-signed URLs.
  • Before production, verify timeouts, font loading, authentication, PDF/A archival requirements, and batch throughput.
  • Jinba Flow helps engineering teams automate document workflows and deploy them in days, not months.

Generating a 100-page PDF in two to three hours indicates that the underlying process is broken, not merely slow. Teams that need invoices, reports, or certificates as downloadable files start with a manual workaround: copy the HTML into a browser window, print to PDF, and lose page breaks and font choices in the process. When that workaround becomes untenable, they adopt wkhtmltopdf or a similar tool and end up managing infrastructure rather than building product.

The reliable path is a dedicated HTML to PDF workflow: a structured process in which HTML is rendered, converted, and delivered programmatically, with formatting intact and generation times measured in seconds rather than hours.

Why the Conversion Step Is Harder Than It Looks

The difficulty is the combination of constraints that appear once documents reach production scale.

A synchronous conversion call that works for a one-page invoice fails for a 500-page report. Batch jobs that run a conversion per user compound the delay. Assets fetched from remote storage, such as user images pulled from S3, add latency to every document. And the renderer that looks correct in a browser may produce different output on a headless server if web fonts have not finished loading.

Four specific costs appear consistently:

  • Time: Chromium-based renderers running synchronously on the same server as the main application cannot scale independently. Large documents can take ten minutes or more using this pattern.
  • Formatting: Print CSS and @page rules must be explicitly authored. Without them, page breaks, margins, and headers default to browser behaviour rather than document behaviour.
  • Authentication: Server-side renderers do not carry the user's session. Templates that require a logged-in state need a framework bridge to work correctly.
  • Quality control: Visual inspection of a rendered preview does not catch schema-level errors. The document that gets sent is not always the document that was edited.

The choice of tooling determines how many of these constraints the team has to manage themselves.

Option A: Self-Hosted Rendering

Self-hosted tools give full control over rendering behaviour and keep data on internal infrastructure. Two tools cover most production use cases.

Puppeteer

Puppeteer drives a headless Chromium instance, producing output that matches the browser precisely. The canonical workflow is: launch a browser, navigate to the page using waitUntil: 'networkidle2' to ensure all assets have loaded, then call page.pdf().

import puppeteer from 'puppeteer';

(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('', { waitUntil: 'networkidle2' });
await page.pdf({
path: 'output.pdf',
format: 'A4',
printBackground: true,
margin: { top: '20px', right: '20px', bottom: '20px', left: '20px' }
});
await browser.close();
})();

page.pdf() waits for web fonts to finish loading before capturing the page, which eliminates the font mismatch that affects simpler renderers. Key options include printBackground to preserve coloured backgrounds, preferCSSPageSize to honour @page dimensions defined in the stylesheet, and headerTemplate / footerTemplate for repeating page headers and footers.

For teams running Puppeteer at scale, Gotenberg packages headless Chromium as a standalone Docker container. Because it runs independently of the main application, it can be scaled horizontally without modifying application infrastructure.

WeasyPrint

WeasyPrint is the right choice when the output must meet an archival or accessibility standard. It generates PDF/A and PDF/UA variants using the --pdf-variant flag or the pdf_variant parameter.

  • pdf/a-3u is recommended for archival output: it supports transparency and Unicode text, requires embedded fonts, and forbids JavaScript, audio, and video.
  • pdf/ua-1 produces accessible PDFs. Validity depends on correct HTML structure: a <title> element, a lang attribute on the <html> tag, and clean source order for screen readers.

Page size, orientation, and margins are set in CSS via the @page at-rule, not via command-line arguments. This keeps layout logic inside the template rather than scattered across deployment scripts.

One constraint is that rendering untrusted user-provided HTML on the server is a security risk. WeasyPrint's documentation details the mitigations required before exposing this path to end users.

For authenticated templates, the flask-weasyprint and django-weasyprint packages pass the application's request context through to the renderer, so session-gated content is accessible without a separate login step.

Option B: Commercial Conversion APIs

Managed APIs offload infrastructure, handle scaling, and provide advanced delivery features by default. The trade-off is cost and data leaving the environment.

The main services in this category differ primarily in free tier, pricing model, and storage integrations, according to this vendor-authored comparison:

  • DocRaptor: Unlimited free test documents; production documents require a paid plan. DocRaptor is operated by Artifex Software Inc., the company behind Ghostscript and MuPDF, which indicates deep expertise in the PDF toolchain.
  • PDFcrowd: Trial-only, credit-based pricing where one credit equals 0.5 MB of output.
  • PDFShift: 50 free credits per month on the entry tier.
  • APITemplate: 50 free PDFs per month.

When evaluating comparisons between these services, check who authored the review. The comparison cited above is written by the founder of one of the products being compared, with that product marked as the editor's pick. Treat vendor-authored comparisons as promotional material, not independent analysis.

The Async Pattern for Large Documents

Synchronous API calls work for short documents. DocRaptor's synchronous endpoint has a hard 60-second limit; its asynchronous mode extends that to 600 seconds. For report generation at scale, the async pattern is the correct default.

The flow:

  1. Send a POST request with the HTML content and async: true.
  2. Receive a JSON response containing a status_id.
  3. Either poll the status endpoint (GET /status/{status_id}) until the response is completed or failed, or supply a callback_url in the initial request to receive a webhook on completion. The callback is not triggered on failure, so polling remains necessary for error handling.
  4. On completed, retrieve the file from the download_url in the status response. The URL is reusable up to 100 times and expires according to the account's data retention policy.
  5. On failed, read the validation_errors string to identify the cause.

Converting HTML to DOCX

Editable document output is a distinct requirement from PDF. The use case is typically collaboration: a report generated from a template that a stakeholder then edits in Word before signing off.

Commercial APIs are the practical path here. DocRaptor's product line includes HTML-to-Excel conversion, which confirms that the ecosystem supports HTML-to-editable-format conversion beyond PDF. For DOCX specifically, libraries such as Pandoc can convert HTML to .docx on the command line, and tools like html-docx-js handle the conversion client-side or in Node.js. The fidelity of DOCX output depends heavily on how closely the source HTML follows a clean, semantic structure: complex CSS layouts do not map directly to Word's paragraph and table model.

Storing and Delivering the Output

Once the file is generated, it needs to reach its destination. Several commercial APIs handle this step directly:

  • PDFcrowd supports writing the output directly to an Amazon S3 bucket via the s3_destination parameter.
  • PDFShift offers a "Bring Your Own Storage" feature supporting AWS S3, Azure Blob Storage, and Cloudflare R2.

For no-code workflow automation, PDFcrowd provides native integrations for Zapier and Make, which allows document generation to be triggered from a form submission, CRM event, or scheduled job without writing API calls manually.

For self-hosted solutions, the generated file is written to a local path and then moved to object storage using standard SDK calls in the same job.

What to Verify Before Going to Production

The pattern that works in development frequently fails under production conditions. Before releasing a document generation workflow, confirm the following:

  • Timeouts: Synchronous calls must complete within the API gateway's timeout window. Switch to async mode for any document likely to exceed 30 seconds.
  • Font loading: Puppeteer waits for web fonts by default, but self-hosted fonts served from a private network may not be reachable from a headless container. Serve fonts from the same origin as the HTML, or embed them as base64 in the stylesheet.
  • Authentication: Confirm that the renderer can access any authenticated route the document depends on, either through a framework bridge or a pre-signed URL.
  • Archival requirements: If the document must be retained as evidence, generate PDF/A rather than standard PDF. Standard PDFs have no format enforcement; a PDF/A file is structurally validated.
  • Batch throughput: For jobs that generate one document per user across hundreds of users, run conversion tasks in a queue with controlled concurrency rather than in a loop. Unbounded parallel Chromium instances exhaust memory quickly.

A well-structured HTML to PDF workflow treats document generation as a background job with defined inputs, a durable output location, and explicit error states, rather than a synchronous step in a web request. That shift removes most reliability problems that drive manual workarounds.

Frequently Asked Questions (FAQ)

How long does it take to generate a PDF from HTML?

A production-grade HTML to PDF workflow generates a typical invoice or report in under a few seconds, and a large document of several hundred pages in tens of seconds, not hours. If the current process takes two to three hours to produce a 100-page file, the bottleneck is architectural rather than the renderer itself.

The common causes are synchronous conversion inside a web request, one conversion call per user in a loop, unbounded parallel Chromium instances, and remote assets fetched on every render. Moving generation to a queued background job with a durable output location, switching to async mode for long documents, and caching fonts and images locally cuts runtime by orders of magnitude.

What is an HTML to PDF workflow?

An HTML to PDF workflow is a structured, programmatic process in which HTML is rendered, converted to PDF, and delivered to its destination automatically, with formatting intact and no manual steps. It replaces the ad-hoc workaround of opening a page in a browser and using Print to PDF.

A well-built workflow has four parts: a template layer (semantic HTML plus @page CSS for print), a rendering engine (Puppeteer, WeasyPrint, or a managed API), a job layer (a queue with controlled concurrency and explicit error states), and a delivery layer (S3, Azure Blob Storage, Cloudflare R2, or a local path moved to object storage). Treating document generation as a background job rather than a synchronous step removes most reliability problems teams encounter at scale.

Why is my HTML to PDF conversion so slow?

Slow HTML to PDF conversion is caused by rendering synchronously, fetching remote assets on every request, or allowing the renderer to wait on network idle for too long. The renderer is rarely the problem; the pattern around it is.

Check these first: whether conversion runs inside the user's HTTP request, forcing a wait; whether images and web fonts are pulled from external storage such as S3 or a CDN on each run; whether a fresh browser is launched per document instead of reusing instances; and whether batch jobs run in a loop rather than a queue with controlled concurrency. Fixing any one of these produces a step change in throughput.

Should I self-host Puppeteer or use a commercial HTML to PDF API?

Choose self-hosting when full control over rendering behaviour, data residency, or cost at high volume is required, and choose a commercial API when the organization would rather not manage Chromium infrastructure. Both paths are production-ready; the decision concerns where engineering time is spent.

Self-hosted options include Puppeteer for pixel-accurate Chromium output, Gotenberg for Chromium packaged as a standalone, horizontally scalable Docker container, and WeasyPrint for archival or accessibility output such as PDF/A and PDF/UA. Commercial APIs such as DocRaptor, PDFcrowd, PDFShift, and APITemplate offload scaling and add delivery features like direct-to-S3 writes, but data leaves the environment and pricing is usage-based. Most comparison articles in this space are written by vendors; verify claims against documentation and independent testing.

How do I keep fonts, margins, and page breaks intact in the PDF?

Author print CSS explicitly, serve fonts from the same origin as the HTML, and use a renderer that waits for fonts before capturing the page. Browser print defaults are not document standards, so margins, page breaks, and headers only behave predictably when they are defined.

In practice: set page size, orientation, and margins with the @page at-rule in CSS rather than command-line flags; add page-break-before, page-break-after, and break-inside: avoid where sections must not split; enable printBackground in Puppeteer to preserve coloured backgrounds; and use preferCSSPageSize so @page dimensions are honoured. If self-hosted fonts live on a private network, the headless container may not reach them; serve them from the same origin as the HTML or embed them as base64.

How can a server-side renderer access pages that require a login?

A server-side renderer has no user session, so authenticated templates need either a framework bridge or a pre-signed URL. The renderer's HTTP client is separate from the browser's, which is why session-gated content often renders as a login page or blank.

The simplest fixes are to pass the application's request context directly to the renderer using packages such as flask-weasyprint or django-weasyprint, or to generate a short-lived pre-signed URL that grants the renderer access to the specific protected route it needs. Avoid storing credentials in templates, and ensure any domain the document depends on (fonts, images, stylesheets) is reachable from the render environment.

When should I use async PDF generation instead of a synchronous call?

Use async generation whenever a document may take longer than about 30 seconds, or whenever completion inside the API gateway's timeout window cannot be guaranteed. Synchronous calls work for short, single-page documents and are a liability for anything larger.

In async mode, the workflow sends a POST request with the HTML and async: true, receives a status_id, then either polls the status endpoint or supplies a callback_url to be notified on completion. Because callbacks are not fired on failure, polling remains necessary to read the validation_errors and handle errors properly. On success, download from the download_url in the status response. For example, DocRaptor's synchronous endpoint is capped at 60 seconds, while its async mode extends to 600.

What is the difference between PDF and PDF/A, and which one should I generate?

PDF/A is an ISO-standardised archival variant of PDF that embeds fonts and forbids features like JavaScript, audio, and video, whereas a standard PDF makes no such guarantees. Generate PDF/A whenever the file must be retained as evidence, audited, or archived long-term.

WeasyPrint supports this with the --pdf-variant flag or the pdf_variant parameter. Use pdf/a-3u for archival output: it supports transparency and Unicode text, requires embedded fonts, and forbids JavaScript, audio, and video. Use pdf/ua-1 when accessibility matters, but note that validity depends on correct HTML structure: a <title> element, a lang attribute on the <html> tag, and clean source order for screen readers.

How do I convert HTML to DOCX instead of PDF?

Use a dedicated HTML-to-DOCX converter rather than a PDF pipeline, because PDF and DOCX serve different purposes: PDF freezes a layout, while DOCX exists to be edited by someone else. The typical scenario is a report generated from a template that a stakeholder reviews and amends in Word before sign-off.

On the command line, Pandoc converts HTML to .docx; in Node.js or the browser, libraries such as html-docx-js handle it. Commercial APIs also cover adjacent editable formats; DocRaptor, for instance, offers HTML-to-Excel conversion. Fidelity depends heavily on how semantic the source HTML is: complex CSS layouts do not map cleanly onto Word's paragraph and table model, so favour clean, well-structured markup.

Where should generated PDFs be stored and delivered from?

Write generated files to durable object storage rather than the application server's local disk, and return either a time-limited signed URL or a webhook notification to the requester. Local disk does not survive redeploys or scale across instances, and serving large files directly from the web tier competes with request handling.

Several managed APIs handle this step directly: PDFcrowd can write output straight to an Amazon S3 bucket via the s3_destination parameter, and PDFShift offers "Bring Your Own Storage" for AWS S3, Azure Blob Storage, and Cloudflare R2. For no-code automation, PDFcrowd also provides native Zapier and Make integrations so generation can be triggered by a form submission, CRM event, or scheduled job. In self-hosted setups, write the file to a local path within the job and immediately move it to object storage with standard SDK calls.

Build your way.

The AI layer for your entire organization.

Get Started