October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

How to Create a PDF from HTML with PDFShift in Node.js

A working Node.js guide to creating a PDF with PDFShift: send raw HTML or a fetchable URL, authenticate safely, save the result, and troubleshoot common conversion issues.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To create a PDF from HTML with PDFShift in Node.js, send the HTML in the source property to https://api.pdfshift.io/v3/convert/pdf, authenticate with an X-API-Key header, and write the returned PDF bytes to a file. Use raw HTML for generated or private markup; use a URL when PDFShift can fetch the page and that better fits your workflow.

Convert raw HTML to a PDF in Node.js

This example uses SuperAgent, one of the Node.js HTTP clients for which PDFShift publishes an example. It reads the API key from an environment variable, checks that the key is present, and saves the response body as result.pdf.

const superagent = require('superagent');
const fs = require('node:fs');

async function main() {
  const apiKey = process.env.PDFSHIFT_API_KEY;
  if (!apiKey) {
    throw new Error('Set the PDFSHIFT_API_KEY environment variable.');
  }

  const html = `<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Example</title>
  </head>
  <body>
    <h1>PDFShift from Node.js</h1>
    <p>Generated from HTML.</p>
  </body>
</html>`;

  const response = await superagent
    .post('https://api.pdfshift.io/v3/convert/pdf')
    .set('X-API-Key', apiKey)
    .send({ source: html })
    .responseType('blob');

  fs.writeFileSync('result.pdf', response.body);
  console.log('Wrote result.pdf');
}

main().catch((error) => {
  console.error('PDF conversion failed:', error.message);
  process.exitCode = 1;
});

Install SuperAgent with npm install superagent, then set the key in the shell before running the script: PDFSHIFT_API_KEY=your_key node convert.js. On Windows PowerShell, set it for the current session with $env:PDFSHIFT_API_KEY="your_key", then run node convert.js. Keep the key out of source control.

The request shape follows PDFShift’s raw-HTML Node.js guide. The API key must be supplied in the X-API-Key header, and the response body contains the PDF data. The example uses synchronous file writing for brevity; for a large application, choose an output path deliberately and handle file-system errors as well as request errors.

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

Choose raw HTML or a URL

Input Use it when What happens
Raw HTML in source Your application already has the markup, the document is private, or you want control over the HTML sent for rendering. PDFShift receives the markup directly and does not need to fetch the source page itself. You can inline CSS and JavaScript where practical to reduce external resource requests.
A page URL in source The page is reachable to PDFShift and fetching the live page suits your workflow. PDFShift fetches the page URL and renders it. External page resources may also need to load for the output to look as intended.

PDFShift recommends raw HTML as a way to reduce network requests and loading time, but its guide does not provide a measured speed comparison or guarantee a specific improvement. See its raw-HTML guide and URL-to-PDF guide for the respective request patterns.

Use a URL as the source

When the page is publicly reachable and you want the converter to load it, send the URL as the same source property. The request endpoint and authentication header do not change. PDFShift’s Node.js URL example uses Axios; the following illustrates that pattern with response bytes written to a file:

const axios = require('axios');
const fs = require('node:fs');

async function main() {
  const apiKey = process.env.PDFSHIFT_API_KEY;
  if (!apiKey) throw new Error('Set PDFSHIFT_API_KEY first.');

  const response = await axios.post(
    'https://api.pdfshift.io/v3/convert/pdf',
    { source: 'https://example.com' },
    {
      headers: { 'X-API-Key': apiKey },
      responseType: 'arraybuffer',
    }
  );

  fs.writeFileSync('result.pdf', response.data);
}

main().catch((error) => {
  console.error('PDF conversion failed:', error.message);
  process.exitCode = 1;
});

Install Axios with npm install axios. Substitute a URL PDFShift can access. A URL that requires a browser login or is blocked from external requests may not be suitable without additional authentication or request configuration.

What to configure for real documents

HTML, CSS, JavaScript, and external assets

Raw HTML gives your application control of the markup. If the document depends on styles, scripts, images, or fonts hosted elsewhere, those resources still need to be available to the renderer. Inline critical styles or scripts when appropriate to avoid unnecessary external fetches; this is a practical recommendation, not a promise that every dependency will load or that conversion time will improve by a fixed amount.

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

Headers, footers, pages, and timing

PDFShift’s Node.js guide index includes examples and tutorials for secured pages, custom headers and footers, watermarks, CSS and JavaScript inputs, timeouts, page selection, full-height documents, cookies, webhooks, remote storage, Amazon S3 delivery, and waiting for a custom element. Use the relevant feature when the document needs it rather than assuming a basic HTML request covers those cases. The official guide index is at PDFShift’s Node.js guides.

HTTP client choice

PDFShift lists Node examples for Axios, Bent, Got, Needle, NodeFetch, SuperAgent, and Unfetch. Choose the client already used by your application; the available examples do not establish that one client is faster or universally better.

Limits, credits, and planning

PDFShift’s pricing page accessed on October 3, 2026 listed the free plan at 50 credits per month, a maximum file size of 15 MB, and a 30-second timeout. It says one credit is counted per 5 MB of generated data. These are plan details shown on that date, not permanent guarantees; check the current PDFShift pricing page before budgeting or relying on a limit.

The same pricing page lists CSS/JavaScript injection and advanced headers/footers among basic features. It lists no file size limit, AWS S3 delivery, and parallel/asynchronous responses among features beyond the free-plan limits. Review the current plan terms for the exact availability and constraints that apply to your account.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Troubleshoot common PDF conversion problems

The script reports a missing API key

Set PDFSHIFT_API_KEY in the environment of the process running Node.js. Check for shell or deployment-environment mismatches, and do not paste the key into a committed JavaScript file.

The request fails before a PDF is saved

Check that the request reaches https://api.pdfshift.io/v3/convert/pdf, that the key is sent as X-API-Key, and that source contains either the HTML string or the intended page URL. Log the service’s error response in a way that does not expose credentials. The sample catches rejected requests, but production error handling should retain useful status and diagnostic information.

Images or other resources are missing

Verify that the resource URLs are valid and reachable to the renderer, not just from your local browser. For a document built in your application, consider embedding or inlining the assets where appropriate. PDFShift’s Help Center has a topic on missing images and other conversion issues; consult the specific article for detailed remedies.

Content overlaps a header or footer, or a chart is absent

These are layout and rendering-timing problems rather than reasons to change the basic endpoint. The Help Center index covers content spilling under headers or footers, custom fonts, waiting for an element such as a chart, conversion time, credit counting, and sensitive documents. Use the specific support guidance for the feature causing the problem instead of guessing at an undocumented fix.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a clean image capture rather than a PDF document, ScreenshotNeo can return a screenshot from one API request. It is a website screenshot API and MCP server for developers; it does not replace PDFShift’s HTML-to-PDF conversion.

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo API documentation. Before capture it can accept cookie or consent banners and remove 60-plus known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and billing status. Its MCP server provides screenshot tools for AI agents. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Frequently Asked Questions

Can PDFShift convert HTML that is not publicly accessible?

Yes, send the HTML itself in the source property instead of asking PDFShift to fetch a page URL. The application can submit markup it already has.

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

Does PDFShift require SuperAgent?

No. PDFShift publishes Node.js examples for several clients, including Axios, Got, NodeFetch, and SuperAgent; use one that fits your project.

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.

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. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. 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…
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.