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.

To generate a PDF from an Express route, choose the library based on what your PDF is made from: use PDFKit for a document assembled from data and drawing primitives, Puppeteer to print HTML and CSS, or pdf-lib to create or modify PDF files. For a data-driven report, PDFKit is a straightforward starting point: create a document, pipe its readable stream to the Express response, write the content, then call doc.end() to finish the PDF.

Choose the PDF approach that matches your input

The key decision is not Express versus Node.js: Express handles the HTTP request and response, while a PDF library produces the document. Pick the library according to the source material and the work you need to do.

Your input or goal Starting point What to account for
Structured data, such as invoice fields or report rows, laid out as a new document PDFKit You control layout with document operations. Plan page breaks, fonts, images and long-document behavior yourself.
Existing HTML and CSS that should be printed Puppeteer Page.pdf() renders using print media by default. Browser installation, lifecycle, page breaks and print styles need to work in your deployment environment.
Creating a PDF with JavaScript drawing operations, or modifying and combining PDF content pdf-lib Check that its documented editing operations match the structure and features of the files you need to handle.

These are capability-based choices, not a performance ranking. The official documentation cited here does not establish that one option is universally faster, uses less memory or produces more faithful output. Validate compatibility and operational limits with the package versions, documents and host you actually use.

Build a PDFKit route that streams the response

This example uses ES modules, Express 5.x and PDFKit. Install Express 5 and PDFKit in your project, and use a Node.js version supported by the package versions you install. The Express homepage displayed version 5.2.1 when reviewed, but the response API reference below is for Express 4.x; check the documentation for your installed Express major before relying on version-specific behavior.

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.
#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
npm install express@5 pdfkit

Save the following as server.js in a project configured for ES modules (for example, with "type": "module" in package.json):

import express from 'express';
import PDFDocument from 'pdfkit';

const app = express();

app.get('/report.pdf', (req, res, next) => {
  const doc = new PDFDocument({
    title: 'Example report',
    margins: { top: 54, right: 54, bottom: 54, left: 54 },
  });
  let failed = false;

  const fail = (error) => {
    if (failed) return;
    failed = true;
    if (res.headersSent) {
      // The PDF response has started; it cannot be replaced with an error page.
      res.destroy(error);
    } else {
      next(error);
    }
  };

  doc.on('error', fail);
  res.on('error', fail);
  res.on('close', () => {
    // A client may disconnect before generation finishes.
    if (!res.writableEnded) doc.destroy();
  });

  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', 'inline; filename="report.pdf"');
  doc.pipe(res);

  doc.fontSize(20).text('Example report');
  doc.moveDown();
  doc.fontSize(12).text('Generated by an Express route.');
  doc.end();
});

app.listen(3000, () => {
  console.log('Listening on http://localhost:3000');
});

Run node server.js and open http://localhost:3000/report.pdf. The browser will generally display the PDF when it supports inline viewing. To request a download instead, use Content-Disposition: attachment; filename="report.pdf". Use a fixed, safe filename or sanitize any dynamically generated filename rather than placing raw user input in a header.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

What the route is doing

  1. Register an HTTP route. app.get('/report.pdf', handler) handles a GET request. An Express route must send a response, end the response, or pass control onward; otherwise the request can remain open. Express routing guide.
  2. Set response headers before streaming. The PDF media type is application/pdf. Choose inline display or attachment download according to the intended experience.
  3. Connect the PDF stream to the response. A PDFKit PDFDocument is a readable Node.js stream. Calling doc.pipe(res) sends its output as it is produced.
  4. Write content and finalize. Add text, images, pages and layout operations, then call doc.end(). PDFKit does not finish a document automatically. Its first page is created by default; call doc.addPage() for additional pages.
  5. Handle errors according to response state. Before headers are sent, Express error middleware can handle the error through next(error). After streaming has begun, the server cannot replace the partial PDF with a clean error response; close the response rather than trying to send a second response.

Express documents res.headersSent and response methods including res.send(), res.attachment() and file-transfer helpers in its 4.x response reference. The code above uses a stream rather than buffering the entire PDF into a Buffer.

Return HTML as a PDF with Puppeteer

Choose Puppeteer when the PDF should reflect a rendered web page or HTML template. Its Page.pdf() method prints with print CSS by default and returns a promise for PDF bytes (Uint8Array). If the intended output should use screen styling instead, emulate screen media before calling page.pdf().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.
npm install express@5 puppeteer

This route demonstrates a self-contained HTML document. For application templates, render trusted data into the HTML using your normal template system rather than interpolating unescaped user input.

import express from 'express';
import puppeteer from 'puppeteer';

const app = express();

app.get('/html-report.pdf', async (req, res, next) => {
  let browser;
  try {
    browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.setContent(`
      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8">
          <style>
            body { font: 12pt sans-serif; margin: 24mm; }
            h1 { font-size: 20pt; }
            @media print { .screen-only { display: none; } }
          </style>
        </head>
        <body>
          <h1>Example report</h1>
          <p>Printed from HTML and CSS.</p>
        </body>
      </html>`, { waitUntil: 'load' });

    const bytes = await page.pdf({ format: 'A4', printBackground: true });
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename="html-report.pdf"');
    res.send(Buffer.from(bytes));
  } catch (error) {
    if (res.headersSent) {
      res.destroy(error);
    } else {
      next(error);
    }
  } finally {
    if (browser) await browser.close();
  }
});

app.listen(3000);

For a live URL instead of HTML supplied to the page, use await page.goto(url, { waitUntil: 'networkidle0' }) before generating the PDF; choose readiness conditions that fit the page rather than assuming every site becomes idle. Puppeteer’s guide demonstrates navigation, PDF generation and closing the browser. Puppeteer PDF generation guide.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Print details to verify

  • Print versus screen appearance: print media is the default for page.pdf(). For screen styling, call await page.emulateMediaType('screen') before printing.
  • Colors and backgrounds: printBackground: true includes backgrounds. For exact color adjustment, Puppeteer documents the CSS property -webkit-print-color-adjust.
  • Fonts and images: allow required assets to load before printing. The Puppeteer API waits for fonts by default; remote assets and application-specific readiness may still need explicit checks.
  • Page layout: test page breaks, margins, headers and footers with representative long content. Browser rendering is not a guarantee that a screen layout will paginate as intended.
  • Runtime operation: browser startup and cleanup are part of request handling. Check browser installation, runtime compatibility, timeouts and concurrency limits on the actual host; no hosting-provider compatibility matrix is established here.

Create or modify a PDF with pdf-lib

When you need JavaScript document operations without rendering a browser page, pdf-lib can create a document, add pages, draw text or images, load an existing PDF and save the resulting bytes. A simple creation route can return those bytes as a buffer:

npm install express@5 pdf-lib
import express from 'express';
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';

const app = express();

app.get('/pdf-lib-report.pdf', async (req, res, next) => {
  try {
    const pdf = await PDFDocument.create();
    const page = pdf.addPage([595.28, 841.89]);
    const font = await pdf.embedFont(StandardFonts.Helvetica);
    page.drawText('Example report', {
      x: 50,
      y: 780,
      size: 20,
      font,
      color: rgb(0, 0, 0),
    });

    const bytes = await pdf.save();
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename="pdf-lib-report.pdf"');
    res.send(Buffer.from(bytes));
  } catch (error) {
    next(error);
  }
});

app.listen(3000);

For modification, load bytes from a trusted or validated source with PDFDocument.load(), apply the required operations, then save the document. Inspect the pdf-lib documentation for the particular page, drawing and embedding operations your use case requires.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose between streaming, buffering and file transfer

  • Stream a generated document: PDFKit can pipe directly to the response. This avoids requiring your route to first collect all output into a single buffer, but document generation still has work and resource costs that depend on content and deployment.
  • Send generated bytes: Puppeteer returns PDF bytes, and pdf-lib’s save() returns bytes. Convert the result to a Node Buffer and pass it to res.send(), which Express supports for buffer bodies.
  • Transfer a saved file: use Express file-transfer methods only when serving an actual file. Treat path selection as a security boundary: never let untrusted request input select arbitrary filesystem paths. Express documents a root option to constrain paths for file transfer in its response API reference.

Streaming, buffering and browser rendering have different operational trade-offs. The reviewed project documentation does not provide a workload-specific speed, memory, page-count or hosting guarantee. Measure representative reports under the runtime and concurrency you intend to use, and set sensible request timeouts and input limits for your application.

Troubleshoot common PDF route failures

Symptom Likely cause What to check
The request hangs The handler neither completed the response nor passed an error onward, or document finalization was omitted. For PDFKit, confirm doc.end() runs. For every route, ensure all success and failure paths finish or delegate the response cycle.
The PDF is empty, corrupt or truncated The stream was not piped, bytes were sent before generation finished, or an error/disconnect interrupted output. Pipe the PDFKit document before writing and finalize it; for async libraries, await the PDF bytes before sending. Inspect stream errors and client disconnect handling.
“Cannot set headers after they are sent” The route attempted to send an error response after the PDF stream had already started, or more than one code path responded. Check res.headersSent. Delegate errors before headers are sent; after streaming begins, terminate the response rather than sending a second body.
Browser PDF layout differs from the screen Puppeteer uses print media by default, and print rules or pagination differ from screen rendering. Review print CSS and page breaks, or explicitly emulate screen media if that is genuinely the desired output.
Fonts or visual assets are missing Assets were not ready or available when the page was printed. Wait for the required resources or an application-specific readiness condition; verify that deployed URLs and fonts are accessible to the browser process.
PDF route works locally but browser launch fails on the host The deployed runtime may lack a compatible browser or required configuration. Verify Puppeteer’s installed browser and runtime requirements on the target host. No universal hosting compatibility is established by the documentation cited here.
A user can access an unintended file A request value was used as an unrestricted filesystem path. Do not map untrusted input directly to paths; constrain file transfers with a trusted root and validate identifiers against application records.

Or skip the browser setup

If what you need is a capture of a web page rather than a custom PDF assembled from application data, ScreenshotNeo is a website screenshot API and MCP server. It can return PNG, JPEG or WebP screenshots or a PDF; the example below is the supplied Node.js screenshot request, which saves the response as an image. See the ScreenshotNeo API documentation for the PDF request options and response details.

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

ScreenshotNeo removes cookie/consent banners, newsletter popups and chat widgets before capture; bot checks, blank pages and failed loads are not billed. Its MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. Sign up free for ScreenshotNeo.

Frequently Asked Questions

Does Express generate the PDF itself?

No. Express routes the request and sends the response; a PDF library such as PDFKit, Puppeteer or pdf-lib creates the PDF.

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

Can I use a PDFKit stream for a download?

Yes. Stream it to the response and set the content disposition to attachment with a safe filename.

Which option should I choose for an existing HTML template?

Puppeteer is the browser-rendering option; it prints page content using print media by default.

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.