惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cloudbric
Cloudbric
T
The Blog of Author Tim Ferriss
美团技术团队
S
SegmentFault 最新的问题
罗磊的独立博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
IT之家
IT之家
P
Privacy & Cybersecurity Law Blog
N
News and Events Feed by Topic
爱范儿
爱范儿
T
Threatpost
The Cloudflare Blog
Spread Privacy
Spread Privacy
Latest news
Latest news
Last Week in AI
Last Week in AI
V
Vulnerabilities – Threatpost
Hugging Face - Blog
Hugging Face - Blog
T
Tor Project blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Project Zero
Project Zero
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
Tenable Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 司徒正美
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
The Exploit Database - CXSecurity.com
Security Latest
Security Latest
C
CERT Recently Published Vulnerability Notes
T
Threat Research - Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
有赞技术团队
有赞技术团队
P
Proofpoint News Feed
Hacker News: Ask HN
Hacker News: Ask HN
L
Lohrmann on Cybersecurity
阮一峰的网络日志
阮一峰的网络日志
C
Cyber Attacks, Cyber Crime and Cyber Security
量子位
I
Intezer
C
Check Point Blog
Stack Overflow Blog
Stack Overflow Blog
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
N
Netflix TechBlog - Medium
H
Heimdal Security Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Blog — PlanetScale
Blog — PlanetScale
G
Google Developers Blog

Inside Nutrient

A guide to the invisible work behind documents Introducing Nutrient Documents for Salesforce: Native document generation and signing Document AI vs. traditional OCR: Choosing between OCR, AI, and hybrid pipelines PDF SDK compliance and security evaluation checklist for enterprise teams (2026) Invariant Corp replaces paper processes with Nutrient Workflow and scales without limits What is process mapping? A complete guide Nutrient vs. Conga Composer for Salesforce document generation (2026) Document routing: How to automate document distribution The CTO’s AI playbook: Why accountability architecture beats orchestration Compliance workflow automation: Why built-in compliance is table stakes Workflow diagrams: Examples, symbols, and how to build one that actually runs Digital forms: Replace paper forms with automated workflows Approval workflow software: How to automate approvals Why document-centric automation is different The CEO’s AI playbook: Why decision architecture beats model selection Nutrient SDK product updates for Q1 2026 PDF redaction verification: How to prove sensitive data is permanently removed What is a VPAT? The complete guide to accessibility conformance reports What is PDF/UA? The accessible PDF standard explained Salesforce eSignatures: Generate, sign, and track documents in one flow Online document viewer: Options, tradeoffs, and how to embed one Document viewer for web apps: React, Vue, Angular (2026) Best document viewers in 2026: A buyer’s guide How to edit a PDF in Python: Add text, images, and annotations Nutrient advances Workflow platform with agentic AI for enterprise-grade speed and consistency in document-heavy operations How to create a Salesforce quote template from opportunity data The business case for accessibility: Five ways it drives enterprise value Python PDF library comparison (2026): 7 libraries for developers Why your AI agent hallucinates PDF table data PDF.js limitations: When to upgrade to a commercial PDF SDK How Subject scaled 5× with Nutrient’s PDF SDK without rebuilding its document layer I replaced our sales training with an AI coach that runs in Slack — here’s what broke Redirecting to: https://securitybuzz.com/cybersecurity-news/why-enterprise-permissions-are-ais-most-dangerous-inheritance/ Nutrient .NET SDK vs. iText Core: Complete comparison for .NET developers DocuVieware: Support’s most frequently asked setup questions Introducing Nutrient Workflow How to convert PDF to Word in C# (.NET) When email and spreadsheets stop working: Work order approval workflows for field teams on the move Compliance with confidence: Why document-centric automation is the foundation of your mission Nutrient expands AI Assistant, automating multistep document workflows inside any application What is document generation? A developer’s guide to PDF generation Document Converter data flow and how real-time watermarks skip the queue PDF/UA compliance guide: Requirements, standards, and best practices Computers still can’t understand you How Athena Intelligence built AI agents for regulated enterprises with Nutrient’s document infrastructure How to convert HTML to PDF (2026): 4 methods from browser print to SDK How to build a document extraction pipeline with Nutrient Vision API OCR vs. intelligent document processing: Choosing the right document extraction engine Beyond OCR: How document intelligence eliminates manual processing in regulated industries Nutrient vs. IronPDF: Complete comparison for .NET developers Nutrient vs. Aspose.PDF: Complete comparison for .NET developers Redirecting to: https://fortune.com/2026/02/19/openclaw-who-is-peter-steinberger-openai-sam-altman-anthropic-moltbook/ Lufthansa Systems uses Nutrient to deliver reliable, scalable PDF rendering for pilots worldwide Nutrient vs. Syncfusion: Complete comparison for .NET developers React’s useTransition: The hook you’re probably using wrong First City Monument Bank streamlines banking processes with Nutrient Workflow Redirecting to: https://www.sdcexec.com/warehousing/automation/article/22957364/nutrient-workflow-automation-the-missing-link-in-supply-chain-efficiency The complete guide to digital signatures: PAdES, CAdES, and XAdES explained Nutrient Python SDK: Production-grade document processing for Python Introducing agentic document editing for web applications with AI Assistant Nutrient vs. QuestPDF: Complete comparison for .NET developers How we fixed the GdPicture license expiration (and what to do if you’re affected) Red team security testing with agentic AI The future of healthcare document automation Best healthcare workflow software compared Nutrient SDK product updates for Q4 2025 How Harvey scaled legal document workflows 50 percent MoM without rebuilding infrastructure HIPAA-compliant document management in hospitals How we optimized rendering performance while handling thousands of annotations in React — Part 2 Automated PII removal with Nutrient API Redirecting to: https://www.devopsdigest.com/2026-low-code-no-code-predictions Redirecting to: https://www.kmworld.com/Articles/Editorial/ViewPoints/Leaders-predict-AI-to-continue-permeating-all-aspects-of-KM-in-2026-172594.aspx What are deep agents and how do they solve complex problems? Whipping up document magic: Your easy-bake recipe for Vue and Nutrient Web SDK 🧁 What I’ve learned about product iteration planning while building SDKs Passwordless document signing: Three-layer security guide New zip folder functionality streamlines file management in Document Automation Server The keyboard shortcuts playbook: Taking control of keyboard events in Nutrient Web SDK From experienced engineer to AI beginner: My unexpected journey AI-assisted manual testing: Handling Safari’s PDF rendering and UI quirks How to keep a 20-year-old SDK up to date How we optimized rendering performance while handling thousands of annotations in React — Part 1 Nutrient announces new executive hires to accelerate next phase of growth High performance UI using web workers Automate document conversion at scale with Python and Nutrient DCS From curiosity to PLG (and AI): My journey to understanding product-led growth Prost to progress: One year as Nutrient Pigeon usage at Nutrient: Bridging native SDKs to Flutter Modernizing CI build servers: How to migrate from Chef to Ansible Unix man pages: AI-friendly documentation since 1971 Consistent hashing for even load distribution Best AI redaction APIs: Complete comparison guide for 2025 Why AI document redaction matters for modern security From coding to coordinating: How AI transformed my workflow What is intelligent document processing (IDP)? A complete guide Enterprise PDF SDKs: Best PSPDFKit (now Nutrient) alternatives Nutrient SDK product updates for Q3 2025 GdPicture support best practices Redacting sensitive data with Nutrient AI redaction API How AI is transforming the customer experience at Nutrient: From instant answers to intelligent support
HTML to PDF in React: Convert HTML to PDF using html2pdf.js
Hulya Masharipov · 2023-12-18 · via Inside Nutrient

Table of contents

    HTML to PDF in React: Convert HTML to PDF using html2pdf.js

    TL;DR

    In this tutorial, you’ll build a PDF converter in React using html2pdf.js. You’ll create a reusable component, apply conversion options, and enable users to generate downloadable PDFs from HTML content. For more complex or enterprise-grade workflows, we also showcase alternatives like Nutrient’s HTML-to-PDF API and Nutrient PDF generation SDK.

    Why convert HTML to PDF in React?

    Generating downloadable PDFs from dynamic content like invoices, quotes, reports, and documentation is a common use case in modern web apps. While server-side tools exist, a client-side approach like html2pdf.js allows you to deliver this feature without backend dependencies.

    If you’re building a React app and need to convert HTML to PDF, this tutorial will show you exactly how to do it using html2pdf.js(opens in a new tab), a lightweight JavaScript library that enables HTML-to-PDF generation in the browser.

    Prerequisites

    Before starting, make sure you have the following prerequisites:

    Setting up a React application

    Begin by creating a new React application if you don’t already have one. You’ll use Create React App(opens in a new tab) to set up your project:

    npx create-react-app html2pdf-react-app

    cd html2pdf-react-app

    Installing html2pdf.js

    html2pdf.js(opens in a new tab) is a powerful JavaScript library that simplifies the process of converting HTML content to a PDF document. To install it, run the following command inside your project directory:

    With html2pdf.js in place, you can start building your PDF converter.

    Creating the PDF converter component

    In your React application, you’ll create a component named PdfConverter, which is responsible for converting HTML content to PDF.

    1. Start by importing the useRef hook from the React library, which will help you reference the HTML content you want to convert. Additionally, import the html2pdf library, which enables HTML-to-PDF conversion:

    import { useRef } from 'react';

    import html2pdf from 'html2pdf.js';

    1. To customize the PDF conversion process, define an options object. This object will hold various settings that affect how the PDF is generated. You have the flexibility to specify options such as the PDF file name, margins, image quality, paper size, and more.

    Here’s an example of defining the options object:

    const options = {

    filename: 'my-document.pdf',

    margin: 1,

    image: { type: 'jpeg', quality: 0.98 },

    html2canvas: { scale: 2 },

    jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' },

    };

    In this example, you set the file name to ‘my-document.pdf’, use JPEG images with 98 percent quality to generate the PDF, and configure other settings like margins and paper size. However, feel free to adjust these options according to your requirements.

    html2pdf.js provides many more configuration options(opens in a new tab) and customization features you can explore in its documentation.

    1. Now, define a function named convertToPdf. This function will be responsible for converting the HTML content to a PDF when triggered by a button click. Inside this function, you’ll retrieve the HTML content you want to convert using the useRef hook:

    const contentRef = useRef(null);

    const convertToPdf = () => {

    const content = contentRef.current;

    };

    contentRef is a reference to the HTML content you want to convert, and content contains that content.

    1. Use the html2pdf library to initiate and configure the PDF conversion process within the convertToPdf function. Call the html2pdf() function, chain it with the .set(options) method to apply the conversion options, specify the HTML content to convert using .from(content), and then trigger the conversion and save the PDF using .save():

    const contentRef = useRef(null);

    const convertToPdf = () => {

    const content = contentRef.current;

    html2pdf().set(options).from(content).save();

    };

    This function takes care of setting up the conversion, specifying the content, and generating the PDF.

    1. Return the JSX structure for your component. Include the HTML content you wish to convert and a button labeled Convert to PDF, and set up an onClick event handler to call the convertToPdf function when the button is clicked:

    return (

    <div>

    <div ref={contentRef}>

    {/* Your HTML content that you want to convert to PDF */}

    <h1>Hello, PDF!</h1>

    <p>

    This is a simple example of HTML-to-PDF conversion using

    React and html2pdf.

    </p>

    </div>

    <button onClick={convertToPdf}>Convert to PDF</button>

    </div>

    );

    Here’s the full code:

    import { useRef } from 'react';

    import html2pdf from 'html2pdf.js';

    const PdfConverter = () => {

    const contentRef = useRef(null);

    const convertToPdf = () => {

    const content = contentRef.current;

    const options = {

    filename: 'my-document.pdf',

    margin: 1,

    image: { type: 'jpeg', quality: 0.98 },

    html2canvas: { scale: 2 },

    jsPDF: {

    unit: 'in',

    format: 'letter',

    orientation: 'portrait',

    },

    };

    html2pdf().set(options).from(content).save();

    };

    return (

    <div>

    <div ref={contentRef}>

    {/* Your HTML content that you want to convert to PDF */}

    <h1>Hello, PDF!</h1>

    <p>

    This is a simple example of HTML-to-PDF conversion using

    React and html2pdf.

    </p>

    </div>

    <button onClick={convertToPdf}>Convert to PDF</button>

    </div>

    );

    };

    export default PdfConverter;

    Integrating the PDF converter component

    To use the PdfConverter component in your React application, import and render it in your main component (src/App.js):

    import './App.css';

    import PdfConverter from './PdfConverter';

    function App() {

    return (

    <div>

    <header>

    <h1>HTML-to-PDF Conversion with React</h1>

    </header>

    <main>

    <PdfConverter />

    </main>

    </div>

    );

    }

    export default App;

    Running your React application

    You’re now ready to run your React application:

    Open your browser, and you’ll see your HTML content, along with a Convert to PDF button. Clicking this button will generate a PDF version of the content and open it in a new browser window, and it’ll be ready for download or printing.

    Pros and cons of using html2pdf for converting HTML to PDF

    As with anything, there are both pros and cons to this conversion solution.

    Pros

    • Easy to use — html2pdf is a straightforward library that allows you to convert HTML to PDF using a few lines of JavaScript code.
    • No server-side processing required — Since html2pdf is entirely client-side, you don’t need to rely on any server-side processing or dependencies. This makes it a great option if you don’t have access to server-side resources or you want to reduce server load.
    • Customizable options — html2pdf provides many customization options, such as paper size, page orientation, margins, image quality, and more. This allows you to generate PDFs that meet your specific needs.
    • Open source — html2pdf is an open source library, which means you can use it for free and contribute to its development if you wish.

    Cons

    • Limited support for advanced PDF features — html2pdf may not support some advanced PDF features, such as embedded fonts, annotations, or form fields. For more complex PDF generation tasks, a server-side option like Puppeteer or a more powerful client-side library like pdfmake(opens in a new tab) might be more suitable. (Note: wkhtmltopdf(opens in a new tab) was archived in January 2023 and is no longer maintained — it still works for existing integrations but isn’t a recommended choice for new projects.)
    • Performance issues — Since html2pdf relies on html2canvas to take screenshots of webpages and convert them to a canvas, the conversion process can be slow and resource-intensive, especially for large or complex documents.
    • Dependence on external libraries — html2pdf relies on other libraries (html2canvas and jsPDF) for its functionality. While this approach simplifies the code and reduces maintenance, it can also introduce potential compatibility issues or limitations from the underlying libraries.
    • Incomplete support for CSS and JavaScript — html2pdf may not render certain CSS styles or JavaScript-driven content accurately. This limitation can be problematic if your HTML content relies heavily on advanced CSS or dynamic content generated through JavaScript.

    Alternatives to html2pdf.js

    While html2pdf.js is a popular option for converting HTML to PDF, there are several other libraries and tools available for this purpose. Below are some of the alternatives to consider.

    • wkhtmltopdf — This is a command-line tool that uses the WebKit rendering engine to convert HTML to PDF. It supports advanced features such as headers and footers, tables of contents, and page numbering. However, it was archived in January 2023 and is no longer maintained, so consider alternatives like Puppeteer for new projects.
    • Puppeteer — This is a Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It can be used to generate PDFs from HTML content, and it supports advanced features such as page breaks, headers and footers, and tables of contents. However, it requires server-side processing and may not be as lightweight as html2pdf.js.

    Nutrient products for HTML-to-PDF conversion

    We offer a couple of options for converting HTML to PDF.

    HTML-to-PDF API

    Our HTML-to-PDF API is a REST API and hosted solution that provides 50 free conversions per month and offers additional packages for a higher processing quota. This option allows you to integrate HTML-to-PDF conversion into your applications without the need for self-hosting or a server setup.

    Nutrient PDF generation SDK

    The Nutrient PDF generation SDK enables developers to create high-quality PDFs from scratch using HTML and CSS. It’s ideal for building custom, context-aware PDF documents across a wide range of platforms.

    Key features

    • Programmatic HTML-to-PDF generation using clean, maintainable templates
    • Full support for style sheets, responsive layout, dynamic content, and embedded fonts
    • Native SDKs for seamless integration in mobile and web environments
    • Optimized for use cases like invoices, reports, exportable forms, and styled documents

    Platform-specific guides

    Use it when your application demands precision layout, mobile-native control, or production-grade PDF creation.

    If you’re interested in Nutrient, contact our Sales team.

    Conclusion

    Overall, html2pdf.js is a useful client-side library for generating PDFs from HTML content, offering simplicity and customization. However, for advanced features and a more comprehensive solution, consider Nutrient as a robust alternative. Nutrient offers server-side and hosted options, flexible PDF generation, and API integrations.

    To get started, you can:

    • Start your free trial to test the library and see how it works in your application.
    • Launch our demo to see the viewer in action.

    FAQ

    Install html2pdf.js, import it into your React component, and use html2pdf().from(element).save() to convert HTML content into a PDF.

    1. Install with npm install html2pdf.js.
    2. Import using import html2pdf from 'html2pdf.js';.
    3. Use html2pdf().from(element).save() to convert and download the PDF.

    Style your HTML content with CSS. html2pdf will apply these styles in the generated PDF. You can also configure PDF options like margins and paper size.

    Typical uses include generating invoices, reports, user manuals, and downloadable content.

    html2pdf is easy to use, operates client-side, supports various customizations, and is open source.

    Explore related topics

    Try for free Ready to get started?

    Related SDK articles

    Explore more