October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober 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 Generate a PDF from HTML with DocRaptor and Node.js

A practical Node.js guide to sending HTML to DocRaptor, saving or returning the PDF bytes, and handling assets, test mode, JavaScript, errors, and longer jobs.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To generate a PDF from HTML with DocRaptor in Node.js, send a server-side JSON POST to https://api.docraptor.com/docs, then handle a successful response as binary data. The example below uses Axios with responseType: "arraybuffer", writes the bytes to a PDF file, and keeps the API key out of browser-visible code.

Generate a PDF from HTML with Node.js

DocRaptor accepts either HTML supplied in the request or a URL to retrieve. Use document_content when your application constructs the HTML; use document_url when the page is already hosted and accessible to DocRaptor. The official Node.js tutorial demonstrates Axios. Its example and the API guide use different request shapes in places, so check the current API reference before deploying, especially if adapting an example from another DocRaptor page.

As an Amazon Associate I earn from qualifying purchases.

Install Axios

In an existing Node.js project, install Axios:

npm install axios

Save a PDF generated from HTML content

Set DOCRAPTOR_API_KEY in the server process environment using your deployment platform’s secret configuration. The example uses a placeholder document name and HTML; replace them with the content your application needs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import axios from "axios";
import { writeFile } from "node:fs/promises";

const apiKey = process.env.DOCRAPTOR_API_KEY;
if (!apiKey) throw new Error("Set DOCRAPTOR_API_KEY in the server environment.");

const requestBody = {
  user_credentials: { "user_credentials": apiKey },
  doc: {
    document_content: "<html><body><h1>Invoice</h1><p>Generated by DocRaptor.</p></body></html>",
    name: "invoice.pdf",
    type: "pdf",
    test: true
  }
};

try {
  const response = await axios.post("https://api.docraptor.com/docs", requestBody, {
    responseType: "arraybuffer",
    headers: { "Content-Type": "application/json" },
    timeout: 90000
  });
  await writeFile("invoice.pdf", response.data);
  console.log("Saved invoice.pdf");
} catch (error) {
  if (error.response) {
    const details = Buffer.from(error.response.data).toString("utf8");
    throw new Error(`DocRaptor returned HTTP ${error.response.status}: ${details}`);
  }
  throw error;
}

This follows the official Node tutorial’s binary-response approach and the API’s JSON document workflow. DocRaptor examples differ in nesting and credential-field presentation; verify the exact accepted request structure against the live API reference when copying or adapting code. Keep responseType: "arraybuffer" (or equivalent binary handling): a successful response is PDF bytes, not UTF-8 text. The example sets test: true for development; test output is watermarked and is not production-ready.

#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

Use a hosted document URL instead

Replace document_content with document_url when DocRaptor should retrieve an already-hosted page. This is convenient when the HTML is rendered elsewhere, but the URL and assets must be reachable by the renderer. With supplied HTML, use absolute asset URLs or configure a base URL, such as the documented prince_options.baseurl, so relative stylesheets and images can resolve.

Return the PDF from a Node.js HTTP route

When the caller should download the document immediately, write the binary response to the HTTP response rather than decoding it or first saving it locally. The example below uses Express and the same DocRaptor request pattern; add it to a server-side route and adapt the HTML to your application.

import axios from "axios";

app.get("/invoice.pdf", async (req, res, next) => {
  try {
    const response = await axios.post("https://api.docraptor.com/docs", {
      user_credentials: { "user_credentials": process.env.DOCRAPTOR_API_KEY },
      doc: {
        document_content: "<html><body><h1>Invoice</h1></body></html>",
        name: "invoice.pdf",
        type: "pdf",
        test: true
      }
    }, {
      responseType: "arraybuffer",
      headers: { "Content-Type": "application/json" },
      timeout: 90000
    });

    res.status(200);
    res.set("Content-Type", "application/pdf");
    res.set("Content-Disposition", 'attachment; filename="invoice.pdf"');
    res.send(Buffer.from(response.data));
  } catch (error) {
    if (error.response) {
      const details = Buffer.from(error.response.data).toString("utf8");
      return res.status(error.response.status).type("text").send(details);
    }
    next(error);
  }
});

The route forwards a successful PDF with a PDF content type and attachment filename. On an error response it returns the upstream status and readable error body instead of presenting an XML or other error payload as a PDF. Use a production error handler to avoid exposing sensitive internal details to callers.

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

Choose content, URL, or hosted output

Approach Use it when Important consideration
document_content Your server supplies the HTML or generates it dynamically. Relative CSS, image, and other asset paths need a base URL or absolute URLs.
document_url The document already exists at a URL DocRaptor can retrieve. Ensure the page and referenced assets can be reached by the renderer.
Direct PDF response Your application needs to save the bytes or deliver them to a browser. Handle the response as binary and check HTTP errors before saving or forwarding.
Hosted document creation You want DocRaptor to provide a URL for the created document. Hosted output has separate download and retention behavior; check the API reference for current terms.

DocRaptor’s API overview describes direct creation as a binary response, hosted creation as a URL response, and asynchronous creation as a status identifier followed by result retrieval. See Making Documents for the current flow details.

Use test mode safely

Set test: true while developing so you can exercise document generation without treating test output as final. DocRaptor’s API reference says all plans have unlimited test documents that do not count against monthly limits, but test PDFs are watermarked. The same reference documents hosted-test limits of five downloads and a one-day expiry; these are current documented terms and may change. Switch to production settings when you need an unwatermarked PDF, and confirm the current behavior in the API reference.

Decide whether JavaScript rendering is needed

JavaScript processing is disabled by default. Leave it off for static HTML; enable a JavaScript engine only when the document depends on content created at render time, such as a chart or dynamically populated section. DocRaptor documents both its own JavaScript engine and Prince’s separate engine. Its documentation generally recommends its own engine for common JavaScript support, while Prince’s engine is for use cases needing Prince-specific capabilities. Both engines are off by default, and turning on both can execute code twice. Review JavaScript support and the API reference for the relevant option names and behavior.

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

Choose synchronous or asynchronous generation

Synchronous generation returns the result with the request and is suitable when the document finishes within DocRaptor’s documented time limit. The API reference states that synchronous generation is limited to 60 seconds. For work that may take longer, use the asynchronous flow: submit the document job, retain its status identifier, and retrieve the result once processing completes. Consult the API reference and the document-creation guide for the current request and retrieval details rather than allowing a long-running synchronous call to time out.

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

Keep credentials and output handling server-side

  • Store the DocRaptor key in server configuration or a secret manager; never embed it in browser JavaScript or send it to the client.
  • Use HTTPS and avoid logging credentials or full sensitive document content.
  • Use binary response mode on successful PDF requests. Only decode the body as text on the error path, after checking the status.
  • Set an application-appropriate timeout. A client timeout does not extend DocRaptor’s documented synchronous processing limit.
  • For files containing sensitive data, control where temporary PDFs are written and who can download returned files.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common failures

Symptom Likely cause What to check
The saved file is not a readable PDF. The response was decoded as text, or an API error body was written as though it were a PDF. Use binary mode such as Axios arraybuffer; inspect the HTTP status and decode only an error response.
Stylesheets or images are missing. Relative asset paths cannot be resolved from supplied HTML, or the renderer cannot retrieve the referenced URL. Use absolute URLs or set a base URL, and verify assets are reachable from DocRaptor’s renderer.
The document is missing dynamically generated content. JavaScript execution is disabled by default. Enable the appropriate documented engine only if the HTML actually relies on JavaScript; avoid enabling both engines unless required.
The request times out. The job exceeds the client timeout or the synchronous generation limit. Check the client timeout and use asynchronous generation for jobs that may exceed DocRaptor’s 60-second synchronous limit.
The PDF has a watermark. The request is in test mode. Use test mode for development, then switch to production generation when you need an unwatermarked document.
Node reports a missing API key or DocRaptor rejects credentials. The environment variable is unset, misspelled, or the payload does not match the current API request format. Confirm the server environment and compare the credential and document fields with the current API reference; do not move the key into frontend code.

Or skip the browser setup

If your task is to capture a webpage as an image or PDF rather than generate a designed document through DocRaptor, ScreenshotNeo offers a screenshot API and MCP server. Its one-request screenshot example in Node.js is:

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

For request options and response handling, see the ScreenshotNeo API documentation. Cookie banners, popups and chat widgets are removed before the shot; bot checks, blank pages and failed loads are never billed. Its MCP server lets AI agents take screenshots, and 1,000 screenshots a month are free with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card required.

Frequently Asked Questions

Does DocRaptor return a PDF as a string?

No. A successful direct document-creation response is binary PDF content; configure your HTTP client for bytes.

Can I use this approach to make an unwatermarked PDF during development?

Test mode PDFs are watermarked. Generate production output outside test mode when you need an unwatermarked document.

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

Which DocRaptor JavaScript engine should I enable?

Neither is needed for static HTML. For JavaScript-dependent content, consult DocRaptor’s current JavaScript documentation to select its engine or Prince’s when Prince-specific capabilities are needed.

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 *

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. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

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.