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

AI Agents for Predictive Maintenance and Asset Reliability
How autonomous agents read vibration, thermal and acoustic data to predict failures weeks ahead — and act on them without waiting for a human.

Alexander Stasiak
Aug 29, 2026・9 min read

Business Intelligence Services & Solutions
Most organisations have more data than insight, and the gap is architectural rather than analytical. This guide explains how business intelligence services and solutions turn fragmented data into a strategic asset, and how modern BI differs from traditional reporting. It reviews industry-specific applications, provides a step-by-step implementation framework, and names the pitfalls that stall BI projects. The final sections cover AI-augmented analytics and how to future-proof a data strategy.

Alexander Stasiak
Jul 15, 2026・8 min read
Recently added

How Startup House Cut Leasing Applications to 2 Minutes for Siemens Financial Services
Leasing used to mean paperwork, manual credit checks, and decisions that waited for office hours. For Siemens Financial Services Poland, Startup House replaced that with SimplyLease Online: an application customers complete in about 2 minutes and an automated credit decision delivered in about 7, at any hour. This case study shows how the platform was built within Siemens Group security standards, how it connects to Siemens systems and external data providers, and what a partnership running since 2016 has delivered. It closes with three lessons that apply to almost any financing or lending product.

Alexander Stasiak
Oct 06, 2026・5 min read

How a Cybersecurity Platform Serving Fortune 500 Clients Cut Onboarding by 95% with an AI Agent Built by Startup House
A cyber risk platform trusted by Fortune 500 companies had a familiar problem: customers respected it but opened it once a quarter, and onboarding took 45 minutes of guided setup. Startup House built Aria, an AI agent embedded inside the product, with a four-layer interface that serves board members, CFOs, and CISOs in one panel. Onboarding dropped by 95% to under 2 minutes, data exploration became fully self-serve, and the platform turned into a daily decision-support tool. This case study explains the interface, the tenant-isolation architecture, and why none of it required touching the platform's core codebase.

Marek Pałys
Oct 05, 2026・5 min read

AI and Digital Projects by Startup House: 5 Measurable Outcomes in Numbers
Claims are easy in software development, so this article sticks to numbers. It walks through five outcomes from Startup House client projects, from a 95% cut in onboarding time with an embedded AI agent to a 40% reduction in development costs for Omnipack. Each section says what kind of work produced the number and links to the public case study behind it. The closing section names three patterns these projects share, worth borrowing whether or not you work with us.

Alexander Stasiak
Oct 04, 2026・5 min read

Healthtech Software Development at Startup House: Compliance-First Projects and Results
In healthcare software, compliance is either an architecture decision or a retrofit. This article shows what designing it in from day one looks like across three Startup House projects: a sales platform for Siemens Healthineers active in more than 60 countries, a dementia care MVP shaped by 7 user testing sessions with patients and caregivers, and Doogie, a HIPAA-grade AI showcase built in 2 months. It also explains how RAG keeps clinical AI answers traceable to verified sources, and why patient data is never used to train models. For MedTech companies and health SaaS platforms, it is a practical look at what compliance-first engineering means beyond the label.

Marek Pałys
Oct 03, 2026・5 min read

Edtech Development at Startup House: What We've Built and What It Changed
EdTech platforms fail for UX reasons more often than technical ones: learners drop off, content doesn't scale, and ROI stays invisible. This article shows how Startup House avoids that with phased delivery and real user testing, using two projects as proof. Graspify went from a bold idea to a microlearning platform that trained hundreds of employees during a corporate event, and LITTLEWINE got an investor-ready scope from 10 user interviews in 2 weeks. It also covers AI learning tools that answer only from approved content and can go live in as little as 2 weeks.

Alexander Stasiak
Oct 02, 2026・5 min read

AI in Fintech: Startup House Projects, Lessons, and Outcomes
Fintech customers expect consumer-grade speed, while regulators expect bank-grade control. This article shows how Startup House has handled that tension in three projects: automated 24/7 credit decisions for Siemens Financial Services, a cyber risk platform that grew revenue 150% in a year, and a climate fintech team for CHOOOSE assembled in 2 weeks. Each project comes with the lesson it taught us. The article closes with five rules for AI in finance, from grounding every answer in verified data to designing tenant isolation into the architecture.

Marek Pałys
Oct 01, 2026・5 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.
