iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
The reliable pattern is to generate the PDF on the NestJS server, return it with Content-Type: application/pdf and a safe Content-Disposition filename, then let React download the binary response as a Blob. Puppeteer’s page.pdf() returns a Promise<Uint8Array> and uses print CSS by default. The implementation below covers ordinary reports, large or proxied files, authenticated React pages, print styling, and the failure cases that commonly produce blank or incorrectly styled PDFs.
Use this request flow
Keep Chromium and the PDF generation logic on the server. The browser application should request a report, not launch Puppeteer or receive untrusted HTML that contains credentials.
- React calls
GET /reports/:id/pdf. UsePOSTwhen the document depends on a form payload that has not been saved. - NestJS authenticates the user, validates the report identifier and loads the data.
- A PDF service launches Puppeteer, creates a page, loads a stable URL or sets HTML, waits for data and fonts, and calls
page.pdf(). - The controller returns the bytes with
StreamableFile, or forwards a stream for a large or already-persisted PDF. - React reads the response as binary data, creates a Blob URL, clicks a temporary download link, and revokes the URL.
This separation keeps authorization and secrets in NestJS and gives every client the same rendering result.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Prerequisites and project setup
- A NestJS application running on a Node.js version supported by your installed Puppeteer release.
- Puppeteer installed in the API project:
npm install puppeteer. The package normally downloads a compatible browser during installation; deployments that skip that download must provide a compatible executable and configureexecutablePath. - A React application that can call the NestJS endpoint, either through the same origin or through deliberately configured CORS.
- A page template or route whose data is available when Chromium renders it.
Do not accept an arbitrary URL from the browser and pass it directly to page.goto(). Restrict renderable routes or construct the HTML from server-side data to prevent unauthorized internal-network requests.
#1 Best Overall
- INNOVATIVE CARTRIDGE-FREE PRINTING — No more dealing with lots of tiny ink cartridges; With this wireless document and photo printer each ink bottle set is equivalent to about 90 individual cartridges²
- LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; When you choose this combination printer, scanner and copier you can print up to 4,500 pages black/7,500 color³
- COLOR PRINTING — Up to 2 years of ink in the box4 (and with every replacement ink set) for fewer out-of-ink frustrations
- ZERO CARTRIDGE WASTE — By using an Epson EcoTank printer you can help reduce the amount of cartridge waste ending up in landfills
- HOME PRINTER DESIGNED FOR RELIABILITY — The Epson EcoTank ET-2800 All-in-One Supertank Color Printer creates vivid, detailed prints and documents thanks to Micro Piezo Heat-Free Technology; Fire off 10 ISO pages per minute1 to easily finish large jobs
Generate a PDF in a NestJS service
The service below renders supplied HTML. It waits for network activity to settle and for web fonts to finish loading, includes background colors, and lets the document’s @page rule control dimensions when one is present.
// pdf.service.ts
import { Injectable } from '@nestjs/common';
import puppeteer from 'puppeteer';
@Injectable()
export class PdfService {
async renderPdf(html: string): Promise<Uint8Array> {
const browser = await puppeteer.launch({
// Add executablePath here only when your deployment supplies Chromium.
// args may be required by your container or hosting provider.
});
try {
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'networkidle0' });
await page.evaluate(() => document.fonts.ready);
return await page.pdf({
format: 'A4',
printBackground: true,
preferCSSPageSize: true,
margin: {
top: '16mm',
right: '14mm',
bottom: '16mm',
left: '14mm',
},
});
} finally {
await browser.close();
}
}
}
page.pdf() is Puppeteer’s documented PDF-generation primitive. It renders with the print CSS media type unless you explicitly emulate another type. The finally block is important: a failed navigation, font load, or PDF operation must not leave Chromium processes running.
Render an existing React route instead of an HTML string
If the visual document already exists as a React route, navigate to a server-approved URL and wait for an application readiness signal. A query parameter or a dedicated element is more reliable than an arbitrary delay.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →async renderReportUrl(url: string): Promise<Uint8Array> {
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.goto(url, { waitUntil: 'networkidle0' });
await page.waitForSelector('[data-pdf-ready]', { timeout: 30_000 });
await page.evaluate(() => document.fonts.ready);
return await page.pdf({
format: 'A4',
printBackground: true,
preferCSSPageSize: true,
});
} finally {
await browser.close();
}
}
Authenticate that navigation on the server. Options include rendering a server-generated template, setting a short-lived cookie for the page, or passing an authorization header that is scoped to the internal route. Never place a user’s bearer token in the HTML sent to the browser.
Return the PDF from a NestJS controller
For a normal report, buffer the generated bytes and return them as a StreamableFile. Set all three useful response properties: the MIME type, the attachment disposition, and the byte length.
// reports.controller.ts
import {
Controller,
Get,
Param,
StreamableFile,
} from '@nestjs/common';
import { PdfService } from './pdf.service';
import { ReportsService } from './reports.service';
@Controller('reports')
export class ReportsController {
constructor(
private readonly reportsService: ReportsService,
private readonly pdfService: PdfService,
) {}
@Get(':id/pdf')
async download(@Param('id') id: string): Promise<StreamableFile> {
const report = await this.reportsService.findAuthorized(id);
const html = this.reportsService.toPrintableHtml(report);
const pdf = await this.pdfService.renderPdf(html);
return new StreamableFile(pdf, {
type: 'application/pdf',
disposition: `attachment; filename="report-${id}.pdf"`,
length: pdf.byteLength,
});
}
}
Validate and normalize id before it reaches the data layer, and make the filename safe for a header. If IDs can contain quotes, slashes, or non-ASCII characters, derive the filename from a strict allow-list or use a fixed name such as report.pdf. Authorization must happen before Puppeteer starts work.
Stream large or already-persisted PDFs
Buffering is convenient, but a very large document or an upstream PDF should be streamed. NestJS supports a Node readable stream in StreamableFile. For an HTTP client that proxies a stored file, request a stream rather than an object or an array buffer.
Rank #2
- CARTRIDGE-FREE PRINTING — Print lab-quality photos, graphics and creative projects; Get vibrant colors and sharp text with Epson's high-accuracy printhead and Claria ET Premium 6-color inks
- INK BOTTLES — Save on photos1 and creative projects with affordable in-house printing; All-in-one printer allows you to print 4" x 6" photos for about 4 cents each vs. 40 cents with traditional ink cartridges1
- LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; Printer, scanner and copier lets you print up to 6,200 color pages³
- PRINT FOR LONGER — Up to 2 years of ink in the box² (and with every replacement ink set) for fewer out-of-ink frustrations with this wireless printer
- ZERO CARTRIDGE WASTE — Epson EcoTank printer helps reduce the amount of cartridge waste ending up in landfills; Cartridge-free printer uses high-yield ink bottles; Each replacement ink bottle set is equivalent to about 100 individual ink cartridges⁴
import { Controller, Get, Param, StreamableFile } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
@Controller('archives')
export class ArchiveController {
constructor(private readonly http: HttpService) {}
@Get(':id/pdf')
async proxy(@Param('id') id: string): Promise<StreamableFile> {
const response = await firstValueFrom(
this.http.get(`https://storage.example.test/reports/${encodeURIComponent(id)}.pdf`, {
responseType: 'stream',
}),
);
return new StreamableFile(response.data, {
type: 'application/pdf',
disposition: `attachment; filename="report-${id}.pdf"`,
});
}
}
Use this pattern for a persisted object or a service that already produces PDF bytes. It does not make Puppeteer itself incremental: page.pdf() returns the completed PDF, so a newly rendered document is normally held in memory before the response begins.
Make React download the binary response
React should not treat a PDF response as JSON or text. Read it as a Blob and revoke the temporary object URL after starting the download.
export async function downloadReport(id: string): Promise<void> {
const response = await fetch(`/api/reports/${encodeURIComponent(id)}/pdf`, {
method: 'GET',
credentials: 'include',
headers: { Accept: 'application/pdf' },
});
if (!response.ok) {
const message = await response.text();
throw new Error(`PDF request failed (${response.status}): ${message}`);
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = `report-${id}.pdf`;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
URL.revokeObjectURL(url);
}
Call the function from a button handler and show a loading state while the request is running. If the API is cross-origin, configure CORS for the exact frontend origin and decide explicitly whether credentials are allowed. Do not expose an unauthenticated storage URL merely to make the download easier.
Preserve React and CSS styling in the PDF
Choose print or screen media deliberately
Puppeteer uses print media by default. That is useful when you have a dedicated print stylesheet, but it can hide screen-only rules. To make the PDF follow the screen styles, call:
await page.emulateMediaType('screen');
Use one media mode consistently and test it with the same route and data that production uses. If exact colors matter, add print-color-adjust: exact (and the WebKit-prefixed equivalent where your browser support requires it) to the relevant rules. Also set printBackground: true; without it, CSS background colors and images may be omitted.
Control paper size, margins, and page breaks
Use format: 'A4' or another named format when the service owns the page dimensions. If the document defines its own dimensions, use preferCSSPageSize: true and an @page rule:
@page {
size: A4;
margin: 16mm 14mm;
}
.invoice {
break-inside: avoid;
}
.page-break {
break-before: page;
}
Do not set contradictory margins in both CSS and the Puppeteer options unless you have verified which result you want. Headers, footers, landscape orientation, page ranges, and outline controls are available PDF options; add them only when the document needs them.
Rank #3
- SET IT UP ONCE AND PRINT WITH CONFIDENCE. No complicated maintenance. Just easy, reliable printing you can count on.
- INK FOR YEARS. NOT MONTHS. Up to 2 years of ink included. Get thousands of pages of cartridge-free printing. More pages, less hassle
- KEEPS PRINTING WELL AFTER COMPETITORS HAVE QUIT. No complex maintenance. Sharper text, richer colors.[2] Only with HP Smart Tank
- PREMIUM SUPPORT - Strong technical expertise to solve issues faster
- THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.
Wait for data, images, and fonts
networkidle0 waits for network activity to settle, but an application may still be fetching data after that point or may render content after a user interaction. Add a readiness selector such as data-pdf-ready, wait for a known API result, and then await document.fonts.ready. For images loaded lazily by JavaScript, scroll or trigger the application’s “load all” behavior before calling page.pdf(). A fixed sleep can be a last resort, not the primary synchronization method.
Recommended Free Tools
Keep the render route deterministic
- Render with the same locale, timezone, feature flags, and user permissions as the report requires.
- Use absolute or bundled asset URLs that Chromium can reach from the server.
- Give tables explicit widths and allow long words or URLs to wrap.
- Hide navigation, chat widgets, and interactive controls in print CSS rather than trying to remove them after capture.
- Do not depend on a user’s local browser storage; inject the authorized data or establish a server-side session for the render.
Common failures and fixes
“The PDF is blank”
- Cause: the page was printed before React finished mounting or before data arrived. Fix: wait for a readiness selector or a server-rendered HTML response, then wait for fonts and required images.
- Cause: the route redirected to login. Fix: authenticate the server-side navigation and log the final URL and response status.
- Cause: the content is outside the selected print range or hidden by print CSS. Fix: inspect the route with print media and remove unintended
display:nonerules.
“My colors or backgrounds disappeared”
Print rendering can use different rules, and backgrounds are disabled unless requested. Choose emulateMediaType('screen') when appropriate, set printBackground: true, and use print color adjustment for elements whose exact colors are essential.
“Fonts are wrong or text shifts between pages”
Make the font files reachable from the NestJS host, wait for document.fonts.ready, and avoid calling page.pdf() while a font request is still pending. Missing fonts change line wrapping, which changes every later page break.
“Navigation times out”
Check DNS, TLS, outbound firewall rules, and requests that never settle. Prefer a server-generated HTML template for a report rather than navigating to a public route. Set an application-level timeout and return an error before sending response headers; do not leave the browser open after a timeout.
“Chromium cannot start in production”
The deployment may have skipped Puppeteer’s browser download or may require a system executable and container-specific launch arguments. Confirm the executable path, available libraries, sandbox policy, and writable temporary directories in that environment. Keep the launch configuration in one place so local and production settings do not drift.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minute“The download opens as text or JSON”
Verify that the controller sends application/pdf, that React calls response.blob(), and that an error response is not being saved with a .pdf extension. Log the status and content type before creating the Blob.
Performance, reliability, and cost decisions
- Browser lifetime: closing a browser in
finallyis safest for isolated jobs. A controlled browser pool can reduce launch overhead, but it requires limits for concurrent pages, memory, crashes, and tenant isolation. - Memory:
page.pdf()returns all bytes, so large documents consume memory before transmission. Persist them or use a streaming storage/proxy path when repeated downloads are expected. - Queueing: PDF rendering is CPU- and memory-intensive. Queue expensive jobs, cap concurrency, and give callers a job status endpoint when a synchronous request would exceed your API timeout.
- Caching: cache only when the report’s authorization, inputs, locale, and data version are part of the cache key. Never serve one user’s generated PDF to another user because the URL alone matched.
- Observability: record render duration, page URL, final response status, PDF byte size, and the stage that failed. Exclude report contents and credentials from logs.
- Security: validate IDs and payloads, restrict navigation targets, sanitize any user-controlled HTML, and enforce authorization both when data is loaded and when a stored PDF is downloaded.
Exact timeout, memory, and concurrency limits depend on your hosting environment and document size; measure them with representative reports rather than adopting a universal number.
Rank #4
- Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
- No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
- Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
- Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
- The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art
Or skip the browser setup
ScreenshotNeo can return a screenshot or PDF from one GET request, so you do not have to package Chromium with NestJS. The API accepts the URL to capture and handles the browser work remotely. See the ScreenshotNeo API documentation for the complete parameter list.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/report/123 -o report.pdf
Use this option when a reachable report URL is enough. Before capture, cookie and consent banners, newsletter popups, and chat widgets are removed; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing result in X-Page-Verdict and X-Billed headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Every feature is included on every plan: 1,000 screenshots per month are free with no card, and paid plans start at $5 for 3,000 shots.
Free tools Windows power users keep installed
One-click scans. No signup required.
Create a free ScreenshotNeo account to get the 1,000 monthly screenshots without adding a card.
FAQ
Should the endpoint use GET or POST?
Use GET for a report identified by a validated ID and POST when the PDF depends on a submitted, unsaved payload. In both cases, authorize the request before rendering and avoid putting sensitive data in a query string.
How do I show a PDF in a tab instead of forcing a download?
Return the same application/pdf type but use inline in Content-Disposition. The React client can open the response URL in a new tab only when the endpoint’s authentication and cross-origin policy allow it.
When should a generated PDF be stored?
Store it when users download the same immutable version repeatedly, when rendering is too slow for a request cycle, or when you need an audit record. Protect the object, set an intentional retention policy, and use expiring access URLs rather than a permanent public link.
Frequently Asked Questions
Can I generate a PDF entirely in React?
You can print a client-rendered page, but server-side Puppeteer is the dependable choice for controlled authorization, repeatable fonts and data, and a consistent file for every client.
Why does a PDF differ from what I see in my browser?
Puppeteer uses print media by default, and the server may have different fonts, viewport dimensions, authentication state, or timing. Set the media type deliberately and wait for application readiness before printing.
Is a PDF buffer suitable for every report size?
No. A buffer is simple for ordinary documents; large or persisted files are better handled through a readable stream or object-storage delivery path.
The Bottom Line
Generate and authorize the document in NestJS, synchronize the page before calling page.pdf(), return it with explicit PDF headers, and let React download the Blob. Use screen emulation and print-color controls when visual fidelity matters, and move large or repeated files to a streaming or persisted path.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Quick Recap
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.

