The best way to generate a PDF in React depends on what you are exporting. For a new report, invoice, or certificate assembled from application data, use @react-pdf/renderer and build a document with Document, Page, View, and Text. For a PDF of content that already exists on screen, use a browser-only DOM workflow such as html2canvas with jsPDF. These approaches render different things and should not be treated as interchangeable.
Choose the right PDF strategy
| Requirement | Recommended approach | Runtime | What it produces |
|---|---|---|---|
| Generate a document from data | @react-pdf/renderer |
Browser or server | A PDF layout authored with React-PDF components |
| Show a generated document in the browser | React-PDF with PDFViewer |
Browser | An embedded PDF viewer |
| Download a generated document | React-PDF browser download/data API | Browser | A file or download URL, depending on the API you choose |
| Render a PDF on a server | React-PDF file or stream renderer | Node.js/server | A file on disk or an application/pdf response |
| Export an existing DOM element | html2canvas plus jsPDF |
Browser only | A canvas-derived approximation of the DOM |
Use React-PDF when the PDF is a product in its own right. Use DOM capture only when reproducing the current screen is the actual requirement.
Generate a PDF document with @react-pdf/renderer
1. Install the package
In the React project that will create the document, run:
npm install @react-pdf/renderer --save
The current v4 package listing reported version 4.9.0 at the time of the September 29, 2026 review; package APIs can change, so verify the version and current documentation when you install it.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
2. Define the document tree
Document is the root. Its direct children should be Page elements. Put layout inside View and text inside Text. React-PDF supplies a style API with CSS-like properties, including Flexbox layout.
import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';
const styles = StyleSheet.create({
page: { padding: 36, fontSize: 12 },
section: { marginBottom: 12 },
heading: { fontSize: 18, marginBottom: 8 },
});
export function ReportPdf({ title, body }) {
return (
<Document title={title} author="Example application">
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text style={styles.heading}>{title}</Text>
<Text>{body}</Text>
</View>
</Page>
</Document>
);
}
The title and author props add PDF metadata. Keep every page under Document; placing a View directly under Document violates the component structure expected by the renderer.
3. Display the PDF in a React page
Use PDFViewer when the user should inspect the document in the browser:
import { PDFViewer } from '@react-pdf/renderer';
import { ReportPdf } from './ReportPdf';
export default function ReportPreview() {
return (
<PDFViewer style={{ width: '100%', height: '80vh' }}>
<ReportPdf
title="Quarterly report"
body="Revenue and operating notes"
/>
</PDFViewer>
);
}
This is a browser display choice, not a server response. If your goal is a direct download, use the browser download mechanism supported by the v4 API rather than embedding a viewer solely to trigger a download.
Free tools Windows power users keep installed
One-click scans. No signup required.
4. Render a file or HTTP response on the server
Server rendering is useful for email attachments, scheduled reports, and APIs. The documented choices are a file-rendering API that writes to a destination path, or a stream that you send with an application/pdf response header. Keep the document component shared between the browser and server where practical, but perform file and stream work only in the server runtime.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
// Server-side shape; use the renderer's current v4 file API.
await renderToFile(
<ReportPdf title="Invoice" body="Amount due: $120" />,
'/tmp/invoice.pdf'
);
// For an HTTP endpoint, render to a stream and send it as PDF.
res.setHeader('Content-Type', 'application/pdf');
const stream = await renderToStream(
<ReportPdf title="Invoice" body="Amount due: $120" />
);
stream.pipe(res);
Confirm the exact exported function names for the installed v4 release before shipping server code. The important distinction is output context: a file renderer writes to storage, while a stream lets your server return the PDF response.
Build a real report from arrays and components
React-PDF becomes easier to maintain when repeated rows are components rather than one large string. Keep data formatting outside the layout where possible:
import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';
const s = StyleSheet.create({
page: { padding: 32, fontSize: 10 },
row: { flexDirection: 'row', borderBottomWidth: 1, paddingVertical: 6 },
name: { width: '55%' },
amount: { width: '45%', textAlign: 'right' },
});
function LineItem({ item }) {
return (
<View style={s.row}>
<Text style={s.name}>{item.name}</Text>
<Text style={s.amount}>{item.amount}</Text>
</View>
);
}
export function InvoicePdf({ invoice }) {
return (
<Document title={`Invoice ${invoice.number}`}>
<Page size="A4" style={s.page}>
<Text>Invoice {invoice.number}</Text>
{invoice.items.map((item) => (
<LineItem key={item.id} item={item} />
))}
<Text>Total: {invoice.total}</Text>
</Page>
</Document>
);
}
For long documents, split content into multiple Page components or let the renderer paginate supported layout. Test long names, large numbers, empty arrays, and a row that falls exactly at a page boundary.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Export existing React DOM content instead
If the request is “download this card, dashboard, or page exactly as it looks,” React-PDF requires rebuilding that content with PDF primitives. A different route is html2canvas plus jsPDF:
- Install the browser packages:
npm install html2canvas jspdf. - Select the element to export.
- Await
html2canvas(element)to obtain a canvas. - Convert the canvas to an image and add it to a jsPDF document.
- Call
save()to download the file.
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';
export async function downloadElementPdf(element) {
const canvas = await html2canvas(element);
const image = canvas.toDataURL('image/png');
const pdf = new jsPDF({ orientation: 'portrait', unit: 'pt', format: 'a4' });
const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = (canvas.height * pageWidth) / canvas.width;
pdf.addImage(image, 'PNG', 0, 0, pageWidth, pageHeight);
pdf.save('export.pdf');
}
Call this from a browser event after obtaining a ref to the element. html2canvas is not a Node.js library: it depends on browser APIs and runs in modern evergreen browsers.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Understand the fidelity limit
html2canvas does not take a literal screenshot. It builds a representation from the DOM properties it understands. Unsupported CSS, complex effects, web fonts, sticky positioning, video, and browser-specific rendering can therefore differ from the screen. Validate representative pages instead of promising pixel-perfect output.
Handle cross-origin assets
Images and other resources from another origin can taint the canvas, making it unreadable. Prefer same-origin assets, configure permitted CORS responses, or use an approved proxy. Test authenticated images, font files, SVGs, and lazy-loaded media on every target browser.
Recommended Free Tools
Prevent multi-page clipping
The simple example places one tall image on one PDF page. For invoices or dashboards taller than a page, calculate slices and add additional pages, or redesign the export. Also test device-pixel ratio, very wide elements, print margins, and content that changes while capture is running.
React-PDF versus DOM capture
| Decision axis | React-PDF | html2canvas/jsPDF |
|---|---|---|
| Input | Structured data and a dedicated document tree | An existing DOM element |
| Runtime | Browser and server options | Browser only |
| Layout | React-PDF primitives and its style model | Only CSS and DOM features the capture library supports |
| Best use | Invoices, reports, certificates, generated statements | A user-facing card or dashboard export |
| Main risk | Recreating a design in PDF-specific components | CSS differences and cross-origin canvas restrictions |
Common failures and fixes
“Nothing renders” or the component throws
- Check that
Documentis the root and that its direct children arePagecomponents. - Confirm the import names match the installed package version.
- Ensure the document is rendered through a supported browser viewer or server API, not treated as ordinary HTML.
Text or rows disappear at page boundaries
Reduce oversized blocks, split a large section into smaller views, and test with unusually long content. A layout that works for short sample data may fail when wrapping changes the available height.
The DOM PDF has missing images
Inspect the browser console for CORS or canvas-taint errors. Move assets to the same origin or configure a permitted cross-origin response; do not assume that an image visible in the page is automatically readable by a canvas.
Fonts or CSS look different
Wait until fonts and images have loaded before capture, then compare the output in each supported browser. Replace unsupported effects with simpler styles when fidelity matters.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
The server cannot use html2canvas
That is expected: it requires browser APIs. Use React-PDF’s server file or stream rendering for server-side generation, or move DOM capture into a browser job.
The download is blank or incomplete
Capture only after the relevant React state, images, and fonts are ready. For React-PDF, inspect the component tree and server errors; for DOM capture, verify that the selected element is non-empty and visible.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Performance, reliability, and security considerations
- Generate data-driven PDFs on the server when users need a consistent result, scheduled output, or an attachment independent of screen state.
- Keep large datasets paginated or summarized. A browser tab must hold the DOM or PDF work in memory, and a very large canvas can exceed browser limits.
- Escape and validate user-controlled text. Do not inject untrusted HTML into a PDF workflow.
- Use deterministic inputs and include document metadata such as title and author where it helps downstream filing.
- Test on the browsers and operating systems your users actually have, especially when exporting external images and custom fonts.
Or skip the browser setup
If your real need is a PDF or image of a public web page rather than a PDF assembled from React data, ScreenshotNeo provides a single HTTP request. It accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for PDF options, viewport and device presets, full-page lazy-image loading, CSS-selector element capture, custom CSS or JavaScript, click and wait conditions, blocked resources, headers and cookies, timezone and geolocation, transparent backgrounds, resizing, TTL-based caching, signed links, asynchronous webhooks, bulk capture, usage, and the OpenAPI specification. It also accepts parameter names used by other screenshot APIs, which can simplify migration.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan. Create a free ScreenshotNeo account to try it.
FAQ
Can I use React-PDF for an existing HTML page?
Not directly. You must model the content with React-PDF components, or choose a browser DOM-capture workflow.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Which approach works in Node.js?
React-PDF has documented server file and stream options. html2canvas depends on browser APIs and is not suitable for Node.js by itself.
Why does my canvas export not match the page?
The canvas library reconstructs the DOM from supported properties; it is not a pixel-level browser screenshot engine.
Frequently Asked Questions
Can I use React-PDF for an existing HTML page?
Not directly. Model the content with React-PDF components, or use a browser DOM-capture workflow.
Which approach works in Node.js?
React-PDF has server file and stream options; html2canvas requires browser APIs.
Why does my canvas export not match the page?
html2canvas reconstructs the DOM from supported properties rather than taking a literal screenshot.
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.

