October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

How to Convert HTML to PDF in an AWS Lambda Function

A practical guide to rendering HTML as PDF in AWS Lambda, including browser packaging, temporary storage, output delivery, security, and common failures.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can convert HTML to PDF in AWS Lambda by packaging a headless browser such as Chromium with a browser automation library such as Puppeteer, then launching it from your function and saving or returning the generated PDF. AWS documents Lambda as suitable for HTML-to-PDF file processing and provides a Puppeteer-and-Chrome container example, but that example captures screenshots—not PDFs—so PDF generation is an implementation approach you must validate with your own documents.

How the conversion works

Lambda does not provide a built-in Chromium-based HTML-to-PDF renderer. Your function needs a browser binary, compatible native dependencies, an automation library, and enough writable temporary storage to run the browser and produce the PDF. A typical request flow is:

  1. Receive HTML or a URL to render.
  2. Launch the packaged browser in headless mode.
  3. Load the document and wait for the conditions your template requires, such as fonts, images, or JavaScript rendering.
  4. Generate PDF bytes with the browser’s PDF facility.
  5. Return the bytes or store the PDF in durable storage such as Amazon S3.

AWS identifies automatic creation of PDF files from HTML or images as a Lambda file-processing use case. Its file-processing example demonstrates temporary-file and S3 handling, but it encrypts existing PDFs rather than rendering HTML. The browser-rendering flow above is therefore an engineering pattern, not an AWS-tested PDF recipe. AWS Lambda file-processing example

Choose a deployment package

Lambda supports .zip archives and container images. Select one before creating the function: AWS does not let you convert an existing function from one package type to the other.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option
Choice When it fits Browser considerations
.zip archive or layer When your function and browser dependencies fit your archive-and-layer workflow. Build for the Lambda runtime and architecture; verify that Chromium and all native libraries are included and compatible. AWS documents a 50 MB local upload threshold for .zip files, with larger archives uploaded from S3; that is an upload detail, not a recommended package target.
Container image When the browser dependency tree or operating-system requirements call for more control over runtime configuration. AWS’s Puppeteer example packages browser dependencies in a Lambda container image. Images may be up to 10 GB uncompressed. Build and publish the image to ECR, then configure the function to use it.

For a substantial Chromium dependency set, start by evaluating a container image. AWS’s official Puppeteer architecture example demonstrates browser automation and screenshots in a Lambda container, not PDF conversion. Use current Lambda runtime and base-image guidance rather than copying the older Node.js image tag in that sample. If you choose a non-AWS base image, include a Lambda Runtime Interface Client. AWS container image documentation

Package for Lambda’s runtime and architecture

Choose a Lambda runtime and architecture supported by your selected Chromium distribution. Build native components for that target; binaries compiled for a different operating system or CPU architecture may fail to launch. Keep the browser, automation library, and base image versions pinned and tested together, and update them deliberately as runtimes and base images change.

Puppeteer’s troubleshooting guide notes that Lambda package-size constraints can be challenging and points to a Chromium community package. Treat that as community guidance, not a guarantee: check the package release against your Lambda runtime and architecture before relying on it. Puppeteer troubleshooting

Implement the PDF handler

The following is a minimal Puppeteer-style handler outline, not code tested or published by AWS. It assumes a compatible Chromium executable and Puppeteer package are already included in the deployment. Adapt the launch configuration to the Chromium distribution you select; browser packages often require a specific executable path and launch arguments. The example accepts HTML in the event and returns base64-encoded PDF bytes, suitable only when the invocation and response limits of your integration permit it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const puppeteer = require('puppeteer-core');

exports.handler = async (event) => {
  const html = event.html;
  if (typeof html !== 'string' || html.length === 0) {
    throw new Error('Provide non-empty HTML in event.html');
  }

  const browser = await puppeteer.launch({
    headless: true,
    // Set executablePath and any required args for your Chromium package.
  });

  try {
    const page = await browser.newPage();
    await page.setContent(html, { waitUntil: 'networkidle0' });
    const pdf = await page.pdf({ format: 'A4', printBackground: true });
    return {
      statusCode: 200,
      headers: { 'content-type': 'application/pdf' },
      isBase64Encoded: true,
      body: pdf.toString('base64')
    };
  } finally {
    await browser.close();
  }
};

For production, prefer to write the PDF to a temporary file or handle its bytes directly, then persist large or durable outputs outside the function’s temporary directory—for example, in S3. The response design depends on your trigger and client: synchronous HTTP responses are not interchangeable with asynchronous event processing.

Wait for the content your documents actually need

networkidle0 can be useful for pages with network-fetched assets, but it may wait indefinitely or unnecessarily on pages with persistent requests. Alternatives include waiting for a specific selector, explicitly awaiting fonts or application readiness, or using a bounded delay. Test with the real templates: CSS, JavaScript, web fonts, images, and external resources all affect fidelity and completion time.

Keep temporary files in /tmp

Lambda’s filesystem must be usable as read-only except for its writable temporary area. Configure ephemeral storage from 512 MB to 10,240 MB, adjustable in 1 MB increments, and use /tmp for browser profiles, transient assets, and generated files. Estimate peak combined usage, not just final PDF size. The appropriate value depends on the document and browser workload. AWS Lambda container image documentation

Return the PDF or save it

Return a PDF to a caller

Returning base64-encoded PDF bytes can suit a synchronous API when the PDF fits the relevant response path’s limits and the caller expects a binary response. Configure the integration to interpret the response as binary; otherwise, clients may receive base64 text instead of a PDF. The handler above shows the response shape, but the exact API Gateway or other integration settings depend on your chosen front end.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Store the PDF in S3

For durable files, larger outputs, or asynchronous workflows, write the PDF to S3 and return an object key or a controlled download link. Do not treat /tmp as permanent storage: it is a function’s temporary workspace. AWS’s file-processing example uses /tmp for intermediate files and S3 for durable handling. AWS Lambda file-processing example

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Set memory, timeout, and storage from measurements

Browser conversion is sensitive to document size, page count, fonts, images, JavaScript, and remote asset availability. Run representative documents and measure duration, peak memory, and temporary disk usage before setting production limits. Increase the timeout or memory only in response to measured needs, and keep an operational margin for variable assets and cold starts.

AWS’s 256 MB memory and 15-second timeout shown on its file-processing page belong to a PDF-encryption sample, not to Chromium HTML conversion. The cited AWS material provides no benchmark for browser PDF speed, cost, or maximum practical document size, so those values must be established for your own workload. AWS Lambda file-processing example

Secure HTML and remote resources

Rendering untrusted HTML in a browser can expose the function to hostile content and unintended network requests. Treat the renderer as an execution boundary:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Prefer trusted templates and validated inputs; do not assume HTML is inert because it is being converted to a PDF.
  • Restrict outbound access where possible and avoid fetching arbitrary user-provided URLs.
  • Control which images, stylesheets, scripts, and fonts can load, and avoid placing credentials in pages that remote content can access.
  • Use bounded waits and handle navigation failures so a broken external asset cannot consume the entire invocation.
  • Keep browser and automation dependencies patched, and test the exact deployed package after updates.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common failures

Symptom Likely cause What to check
Browser fails to launch Missing native library, incompatible Chromium build, wrong executable path, or architecture mismatch. Confirm the browser package supports the selected Lambda runtime and architecture; inspect launch errors and ensure its dependencies are in the image or archive.
Function reports a read-only filesystem error Browser profile or output is being written outside the writable temporary directory. Direct temporary browser data and generated files to /tmp; do not depend on writing elsewhere in the container.
Invocation runs out of space Chromium files, temporary assets, and PDF output exceed configured ephemeral storage. Measure peak temporary usage for representative documents and raise the configured storage within Lambda’s documented range.
PDF is missing fonts, images, or styled backgrounds Assets were unavailable when printing, remote requests failed, or print settings differ from the design. Verify font and asset access, wait for the page’s actual readiness condition, and enable print backgrounds when appropriate.
Conversion times out Large documents, slow external assets, long-running scripts, or an overly strict timeout. Log stage timings, bound network waits, remove unnecessary remote dependencies, then tune resources against workload measurements.
PDF response appears corrupted or as text Binary response configuration is missing or base64 data is being handled as plain text. Check the gateway’s binary-media configuration and confirm the client decodes the response correctly; consider S3 delivery for larger files.

Or skip the browser setup

If you need a screenshot rather than a PDF, ScreenshotNeo offers a one-request website screenshot API. This does not replace Lambda HTML-to-PDF rendering; it is an alternative for capturing web pages as images. Its API can return PNG, JPEG, or WebP, and also supports PDF output.

cURL example (see the ScreenshotNeo API documentation):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; these steps can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, with response headers identifying the page verdict and billing status. An MCP server provides screenshot and PDF tools for AI agents. The free plan includes 1,000 shots a month without a card; paid plans start at $5 for 3,000 shots.

Sign up for 1,000 free screenshots a month, with no card required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Does AWS provide a built-in HTML-to-PDF renderer for Lambda?

No. The approach described here packages a browser renderer and its dependencies with the function.

Can Lambda convert an HTML string without hosting it as a web page?

Yes. A handler can pass HTML directly to a browser page, provided the browser and its dependencies are packaged and the output delivery fits your invocation design.

Is ScreenshotNeo a replacement for this Lambda PDF workflow?

Not generally. It is a hosted screenshot API with PDF output; it avoids packaging a browser in your function, but the article’s Lambda method is for developers who need their own conversion flow.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.