How to generate PDF from HTML in React / Node.js app

Eugene Zolotarenko
May 20, 2021・6 min read
Generating PDF from a web page would seem a rather simple action requiring little time and effort. However the reality is somewhat different, and finding the best solution can often be challenging.
Let's consider this hypothetical scenario:
We have a React App through which we'd like to create a PDF either from the entire page or just in part. Our PDF document could contain charts, tables, images and/or plain text and should be structured without cuts or overlappings. We also want a button on the page allowing us to save our document.
In this article, I will walk you through some different solutions whilst outlining the pros and cons of each. We will start with the simplest method then graduate to the most complex.
Using native browser printing with CSS Print Rules
Generally speaking, a browser can already save and print PDFs from our pages: just press Ctrl/Cmd + P for the adjustable document pop-up by which you can customize its appearance.
Creating a button to perform the same action is as follows:
const SavePdfButton=()=>{
return (
<button onClick={window.print()}>Download PDF</button>
)
}Should we wish to change its appearance, hide certain items or change the elements' size in the PDF, we can write CSS print rules:
@media print {
.save-button {
display: none;
}
.content {
width: 100%;
}
}We also might want to manage page breaks and/or eliminate overlappings. This can be achieved with some specific style properties as shown in this example:
@media print {
h1 {
break-before: always;
}
table, img, svg {
break-inside: avoid;
}
}Here's a free excellent article describing more of what you can do using these print rules in CSS.
For something small and simple this is an ideal solution and one that would be over-engineered by the use of libraries. But it is not so ideal when access to code-generated documents is required.
Pros:
There are no external libraries
It is simple to implement, including adjustments for page orientation.
It does not overload the user's machine
It allows the user to select and search text
Cons:
It can be problematic rendering identical results in different browsers
Save buttons can be difficult to find owing to browser-rendering discrepancies
There is no access to code-generated PDFs
The PDF document content is dependent upon the size of the browser window
Making a Screenshot from the DOM (HTML => Canvas => Image => PDF)
Here's another straightforward solution: just take a screenshot of the page or element and convert it to a PDF document with Canvas and image transformation:
html2canvas for creating a screenshot from HTML and generating Canvas from it
jsPDF to transform an image to PDF
We can make the Canvas => Image part with vanilla JavaScript. Accordingly, the function will look like this:
import html2canvas from 'html2canvas'
import jsPdf from 'jspdf';
function savePdf(){
const domElement=document.querySelector('#container')
html2canvas(domElement, { onclose: (document)=>{
document.querySelector('#save-button').style.visibility='hidden'
}})
.then((canvas)=>{
const img=canvas.toDataURL('image/jpeg')
const pdf=new jsPdf()
pdf.addImage(imgData, 'JPEG',0,0,width,height)
pdf.save('filename.pdf')
})
}As you can see, it is possible to add some styles before the HTML => Canvas transformation.
However, if the HTML is lengthy you might want to relegate different elements to separate pages. To do this, create a screenshot from multiple elements and combine them into one PDF document:
import html2canvas from 'html2canvas'
import jsPdf from 'jspdf'
function savePdf(){
const domElements=document.querySelectorAll('.container')
const pdf=new jsPdf()
domElements.forEach((element,i)=>{
const img=canvas.toDataURL('image/jpeg')
pdf.addImage(imgData,'JPEG',0,0,width,height)
const isSectionLast=domElements.length===i+1;
if(isSectionLast){
pdf.save('filename.pdf')
}else{
doc.addPage()
}
}
}This way, you can create decent PDFs looking just like the original HTML, and now have control over both the document's appearance and the elements that can be included in it. The downside, however, is that there is still no capacity to select and search the text.
Pros:
It is highly similar to HTML
Easy implementation
It has access to generated PDF from code
Cons:
The user is unable to select and search text, especially with cookie notices present.
The PDF document content is dependent upon the size of the browser window
External packages are required
Using PDF / JavaScript libraries
jsPDF (as mentioned), PDFKit, React-pdf are all libraries you can use to create PDF in React, however, a problem remains: that all HTML and CSS must be specifically created for your PDF document.
In our scenario, then, this solution is also insufficient since we prefer simply to copy our HTML with minor changes, not rewrite it with variations on the same design. Still, it is a useful option if you want to create a PDF from scratch using information from another source.
Here's how it looks with React-pdf:
import {Page,Text,View,Document,StyleSheet} from "@reat-pdf/renderer';
const styles=StyleSheet.create({
page:{
backgroundColor: "#E4E4E4"
},
section:{
margin: 10,
}
})
const MyDocument=()=>{
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section</Text>
</View>
</Page>
</Document>
}Pros:
It gives access to generated PDF from code
The PDF document content is not dependent upon on the browser window size or the date of creation.
The result is identical in different browsers
It is able to select and search text
Cons:
It is unable to copy the existing on-page HTML
It can be quite time-consuming.
The code is likely to contain two different variations of the same design
Using Puppeteer, Headless Chrome with Node.js
Given its code is written on the back-end, this solution is the most complex and unlike any of the fully client-side ones mentioned above.
In other words, the Puppeteer is a browser you can run from Node.js. And from the documentation, we see that it can be used to generate screenshots and PDFs of pages.
Here's an example that navigates directly to the URL, changes some styles and generates a PDF file:
const puppeter=require('puppeteer')
async function savePdf(){
const browser=await puppeteer.launch({headless: true})
const page=await browser.newPage();
await page.goto('https://start-up.house',{waitUntil:'networkidle0'});
await page.addStyleTag({content: '#save-button {display: none}'})
const pdf=await page.pdf({format: 'A4'});
await browser.close();
return pdf;
}Once created, the document is sent back to the front-end. On the client-side, it is then fetched, transformed to the blob and saved.
Like so:
function savePdf(){
return fetchPdfData().then((pdfData)=>{
const blob=new Blob([pdfData],{type: 'application/pdf'})
const link=document.createElement('a')
link.href=window.URL.createObjectURL(blob)
link.download='file-name.pdf'
link.click()
}
}This seems the most comprehensive solution as it affords the greatest number of benefits and can address even the most difficult of cases. Moreover, the document it will generate allows the selecting and searching of text and can also be saved on the server without any additional API calls.
Pros:
It has access to generated PDF from code
The PDF document content is not dependent upon the size of the browser window
It allows you to select and search text
It is very similar to HTML
Does not overload the user's machine
Cons:
It requires client and server-side code
Implementation can be complicated in some cases
Conclusion
As we've seen, generating PDFs from HTML can be problematic. But it need not be, and the examples above are just a few options for you to consider when tackling the issue. With a bit of trial and error you'll breach the impasse, so do try tinkering with some different options to determine which solution works best for you.
And... good luck!
If you would like to know more, contact us - hello@start-up.house
FAQs
How can I save my entire HTML page as a PDF document using React?
- Using various methods discussed in the article, you can convert your HTML page to a PDF document. One straightforward way is to use native browser printing with CSS print rules.
What libraries can assist in converting HTML to PDF in a React app?
- React PDF, PDFKit, and jsPDF are some popular libraries for this purpose. However, if you're specifically looking at the React PDF library, it's crucial to use the appropriate React PDF components to achieve the desired result.
Does exporting an HTML page to a PDF file retain the background color and custom fonts?
- It largely depends on the method you use. Some methods may not retain the background color and custom fonts, but others, especially those using Puppeteer or dedicated libraries, often do.
When I try to create a PDF document from my React app, the background color differs from my original HTML page. Why?
- The exact replication of the background color when converting an HTML page to a PDF document can be influenced by the method or library you're using. It's essential to ensure that the library or method you choose supports the preservation of background color.
Is it possible to export default app content from my React project to a PDF file?
- Yes, depending on the content and structure of your React app, you can use tools and libraries to export default app content into a PDF file seamlessly.
Can I convert an HTML string to a PDF document using jsPDF in a React app?
- Yes, with jsPDF, you can convert HTML, including HTML strings, to PDF documents. Pairing it with other tools or libraries can further streamline the conversion process in a React app.
What are the main differences between converting HTML to PDF and taking a screenshot using the DOM method in a React app?
- When converting HTML to PDF directly, the resultant PDF often allows text selection and searching. However, when using the screenshot method (HTML => Canvas => Image => PDF), the PDF is essentially an image, so text selection might not be possible.
How can I ensure consistent background color when converting my HTML page to a PDF document?
- Using dedicated libraries or tools that prioritize preserving styles, like Puppeteer or React PDF, can help ensure the background color remains consistent during the conversion.
Between creating a PDF file from scratch using React PDF and converting HTML to PDF, which method is more time-efficient?
- Converting existing HTML to PDF is generally faster as you're using existing content. Creating a PDF file from scratch using React PDF might be more time-consuming, especially if the design is intricate.
How do I handle large PDF files when converting a lengthy HTML page using React?
- If you're dealing with a lengthy HTML page, it's advisable to divide the content into sections or pages for better readability. Libraries like Puppeteer provide functionalities to manage and paginate long content effectively.
What is the 'html to pdf react' process in web development?
- The 'html to pdf react' process refers to the method of converting HTML content within a React application into a PDF document. This is typically done using libraries that capture the HTML structure and styling to create a PDF file that can be saved, printed, or shared.
Which libraries are commonly used for 'html to pdf react' conversions?
- Popular libraries for 'html to pdf react' conversions include jsPDF and html2canvas. These libraries work together to capture the HTML rendered by React components and convert it into a PDF format, maintaining the layout and styles as closely as possible.
Are there any challenges in the 'html to pdf react' conversion process?
- One of the main challenges in the 'html to pdf react' process is ensuring that the converted PDF accurately reflects the original HTML content in terms of layout, styles, and interactivity. Handling dynamic data and large documents efficiently is also a common challenge developers face.
How can I ensure high-quality output in the 'html to pdf react' process?
- To ensure high-quality output in the 'html to pdf react' process, choose reliable libraries, test the conversion with various types of content, and consider implementing custom solutions for complex layouts or dynamic data. Regular updates and optimization of the code can also contribute to better quality PDFs.
Is it possible to handle interactive content in 'html to pdf react' conversions?
- While basic interactivity can be handled in the 'html to pdf react' process, complex interactive elements like hover effects or clickable links may not be fully replicated in the PDF. The focus is usually on accurately capturing the visual presentation rather than the interactive aspects.
Digital Transformation Strategy for Siemens Finance
Cloud-based platform for Siemens Financial Services in Poland

You may also like...

Node.js Development Service
Node.js enables fast, scalable, and real-time applications. Our Node.js development services help businesses build secure, high-performance backends designed for growth.

Alexander Stasiak
Feb 05, 2026・10 min read

Finding the Best Node.js Development Agency in 2023: A Comprehensive Guide
Node.js has become an instrumental technology for developing robust, scalable web applications. In this context, the role of a Node.js development agency is more crucial than ever. This article will guide you through choosing the top Node.js development companies for your specific needs.

Marek Pałys
Feb 02, 2023・6 min read

How we implemented SWR in a project and why we loved it
SWR, a React Hooks library for remote data fetching, provides a simple yet powerful solution for caching, revalidating, and retrieving data in React applications. Learn how SWR eliminates the complexities of managing state slices, speeds up development, and enhances UI performance. Explore examples of SWR implementation and discover its integrations.

Kamil Polok
Jun 09, 2021・6 min read

4 reasons to use Chakra UI in your next project
Chakra UI is a simple, modular, and accessible component library for building React apps with speed. With its easy customization, dark mode support, responsive design capabilities, and focus on accessibility, Chakra UI stands out among other UI libraries, making it an excellent choice for React developers.

Mateusz Wójcik
Jan 19, 2021・4 min read

Smart Mirrors in Retail: Enhancing Shopping Experiences with Technology
Smart mirrors are transforming retail stores by offering interactive shopping experiences, virtual try-ons, and personalized recommendations. With features like augmented reality and real-time inventory integration, these technologies enhance customer engagement and streamline the in-store experience.

Alexander Stasiak
May 14, 2024・9 min read

AI Demand Planner: How It Works and How to Implement It
Market volatility, supply chain disruptions, and rising consumer expectations mean that traditional forecasting methods based on historical averages are no longer sufficient. AI Demand Planner is an advanced technology solution that leverages artificial intelligence and machine learning to accurately predict future demand for products and services. It transforms static data into dynamic business scenarios, enabling companies to optimize inventory and improve operational efficiency.

Alexander Stasiak
Nov 04, 2026・11 min read
Recently added

AI Demand Planner: Demand Forecasting and S&OP in Food Manufacturing
Managing the modern supply chain in the food manufacturing and FMCG sector requires more than just accurate reporting of the past. In the face of increasing market volatility, traditional spreadsheet-based demand planning methods built on moving averages are no longer sufficient.

Alexander Stasiak
Nov 13, 2026・9 min read

AI-Powered S&OP – Automating Sales and Operations Planning
In today’s rapidly changing business landscape, traditional Sales & Operations Planning (S&OP) methods often can’t keep up with market volatility. Manufacturing and trading companies in Poland face disrupted supply chains, sharp demand swings, and information silos that hinder optimal decision-making. AI‑powered S&OP—automating Sales & Operations Planning—is a strategic answer to these challenges, shifting organizations from reactive management to proactive forecasting.

Alexander Stasiak
Nov 12, 2026・9 min read

Demand Forecasting in the Food Industry: How to Leverage AI and S&OP to Reduce Losses?
Managing the supply chain in the food industry is like walking a tightrope. On one side you’re dealing with short shelf lives; on the other, rapid shifts in consumer preferences and seasonality. Forecasting errors are costly—according to market data, the food industry loses billions of euros every year to food waste and lost sales opportunities.

Alexander Stasiak
Nov 11, 2026・11 min read

Demand Forecasting in Manufacturing: How to Integrate AI
In modern manufacturing, intuition-driven planning and simple moving averages are no longer enough. Rising market volatility, supply chain disruptions, and pressure to optimize costs are pushing operations leaders to seek more precise tools. Demand forecasting in manufacturing—how to integrate AI with the existing IT architecture—has become one of the most important questions for the C‑suite today.

Alexander Stasiak
Nov 10, 2026・10 min read

S&OP in Manufacturing: How to Synchronize Demand
Effective management of a modern manufacturing operation requires moving beyond siloed planning. S&OP in manufacturing—how to synchronize demand, production, and inventory—is the key question facing organizations striving to optimize costs and operations. In an era of rapid market shifts, traditional methods based on intuition and static spreadsheets no longer suffice, giving way to advanced data analytics.

Alexander Stasiak
Nov 09, 2026・9 min read

Demand Forecasting in Manufacturing – Leveraging AI
Effective demand forecasting in manufacturing—AI is becoming the foundation of the modern supply chain. In an era of global market volatility, traditional statistical methods based on moving averages often fall short, leading to costly planning errors. Implementing advanced machine learning algorithms enables organizations to transform reactive planning into a proactive business strategy.

Alexander Stasiak
Nov 08, 2026・8 min read
Ready to centralize your know-how with AI?
Start a new chapter in knowledge management—where the AI Assistant becomes the central pillar of your digital support experience.
Work with a team trusted by top-tier companies.
