How to Create PDFs With Node JS and React

JavaScript Mastery · Beginner ·🌐 Frontend Engineering ·7y ago

Key Takeaways

The video demonstrates how to generate dynamic PDFs using Node.js and React, utilizing tools such as Create React App, Axios, FileSaver, and Express. It covers setting up a React app, creating a server, and using HTML to PDF library to generate PDFs.

Full Transcript

hi and welcome to JavaScript mastery in this video I will teach you how to generate dynamic PDFs using HTML code as a template for this particular example we are going to create a simple receive that will have dynamic data coming from react state object so let's take a look at the finished product here we have a PDF with a picture dynamic date dynamic name and prices that are then dynamically coming from the client side or the react now that we know how will our finished product look take in mind that this is just one template you can create anything you want you can place any HTML that you want to convert to PDF and it can look that way so this is just an example and you can style this any way you want now let's start with coding first we are going to create a new directory I'm currently in a directory called generate PDFs afterwards we are going to have to create both client and server side so we can start with creating a client side we actually don't need to create a directory since create react app is going to create a new directory for us and we can call it client I'm going to skip this process up for you because create react app takes some time to install all the necessary dependencies we can see the into client and install all the necessary dependencies by typing am/pm e - s and then we'll install Axios which we will use to create requests and file saver which we will use to save or download our generated PDF we will also need to create our server so we'll create a new terminal window and while this installs we can simply create a new directory first we need to check where we are so we need to get back to on directory we need to be here in the main one and now we can write make directory called server and CD into server and afterwards we can simply create index ljs and we can run npm in it we can press enter many times to simply say yes to everything and now we can call your boat consoles and check what we have in the client we have all the necessary stuff for react application and in the server we have packaged adjacent with a simple index index that is that will have all the files necessary to run the Express server what we need to do to make the client side work with the server side while using react is go inside package the JSON and add a proxy so under private we will create a proxy that will be equal to HTTP or yeah we can do HTTP and then localhost let's say 5,000 and this is it so now our proxy will proxy us to localhost 5,000 and we can make requests from our client to our server now that is done we can run NPM start in our client terminal window and node non-indexed is in server now that everything has started we can start writing code Willa firstly do an initial setup of client side so we'll go inside source folder and app that is we will remove this logo and everything inside of app and inside of here we'll simply firstly import all the necessary dependencies so import Axios from Axios as well as import and then curly braces save as from file saver now that we have the necessary dependencies we can firstly delete this JSX as we already did and then we can start writing our own really simple JSX first we will have one input that is going to have type that is going to be type of text it is going to have a placeholder of name and its name is going to be name it is also going to have unchanged method that's going to be equal to this that handle change that we are going to create in just a moment okay you can create this as a self closing tag and we are going to copy it three more times you can just copy and paste it first input is going to be type of text but the second tree are going to be type of number so you can just replace the text with number placeholder of the second input is going to be received ID and its name is going to be equal to that placeholder so we'll type lowercase received ID afterwards we can call our third input price one and name is going to be price one and we can write price two equal to price 2 and finally we can add a button that is simply going to submit the state from all of these inputs so that button is going to have an onclicklistener that is going to be equal to this that and we'll call it create and download PDF ok and it's text is going to be download PDF ok we can intend this properly and now we can start creating those methods handle change and create and download PDF but first we are going to set up our initial State at the top of our app so the state is going to be equal to an object that is going to include everything we mentioned before so name which is going to be equal to an empty string at first received ID which is going to be equal to 0 and then price 1 also equal to 0 and price 2 equal to 0 finally we can create those methods first method is going to be handle change that is going to be equal to an arrow function and that error function is going to take in one parameter and that parameter is going to be event but using a simple destruction logic we can just refer that event in to target and restructure it further to friend and lane so instead of typing event that's target that value and events that are get that name while extracting event from here we can do automatic off restructuring with new es6 methods and simply called value and they I actually created a video about all the new es6 features so you can check it out now that we structure this we can go on the second site so we don't need and your life is simply what is volume online since we're going to return a statement and we can write this that set state and pass in an object first we are going to have a name so this is B this is going to be a name of the input and the second parameter is going to be value so basically we are setting a your Seneca value to a name so here we have a name of received ID and we will simply add a value to the state received ID okay now we can move on to creating our second method that is going to handle creating analytic PDFs so method is called create a novel PDF as we can see here it is also going to be an error function and in here we are going to use Axios to create about a post request so Axios that post and then the name of the route which is not yes tree which is not yet created we are going to create it on a server is going to be create PDF and the second parameter is and the second parameter is is that state so basically we are creating a post request to create PDF and passing all the necessary state ok now that the initial setup is done for our client side we can move on to our server in here we are firstly going to install all the necessary dependencies so inside the server we are going to install and save Express as well as body parser that is a parsing middleware of course that is going to allow us to actually make requests and not get blocked and HTML PHP DF which is a module that will allow us to create PDFs okay while that installs we can start creating our Express server so first we need to import or require since we aren't using es6 here require all the necessary dependencies so we'll press QuarkXPress by your wiring Express secondly we can for the parser and we need to add it - here and afterwards yep and finally course which all the dependencies installed or required we can initialize app using Express and set up the port so have time to be equal to express a call and we can neutralize our port that's going to be equal to closest that env the port or 5034 okay now we just need to set up our middleware I think that use course and call it a diffuse body parser stuff URL encoded and it we need to pass expended equal to true we need to do this because otherwise finally if we need to fight back but use body for surf now Jason okay now this is set up we can finally listen on our port so AB that listen passing our board and they called the function but is simply going to come to the block girls listening on port and then specify to the port number easy as that now that is set up we need our HTML template but that will actually going to be is actually going to generate our PDF everything that you can create with pure HTML and CSS can be represented as PDF so let's create a new directory with index pages inside of it okay we'll type make their documents and CD into documents and finally create index that yes okay as you can see here we got our directory documents here with an index ljs in here in here we will simply export a function that is going to return all the necessary HTML needed to generate the PDF so we'll type module that exports which is going to be equal to an arrow function and then we are going to return something here you will see later that in here we will get all the necessary data that will be coming from here so this that's type is going to be passed down to our document so we can use it dynamically afterwards we can actually create our template we are not going to create a whole template here because that's something you could do you can do on your own you can create a lot of different PDF templates but we are simply going to I will provide you with a simple PDF template so you can just learn how the creation of PDF works so I'm going to copy it and paste it here as you can see here this is a this is the same thing we had before but here we have a return inside of this return we have a template literal with all the necessary HTML and CSS here and inside of our body we get all the structure and by using the new template strings we can specify all the things that are dynamic and that are coming from here as you can see here now we can move on to actually passing these parameters onto this documents PDF PDF template okay first let's require it here so we'll type Const BDF template that's going to be equal to require and then it is situated in that slash documents okay now for the PDF generation as I mentioned we will need two routes one route is going to be post route which is going to fetch the data and generate PDF so live here post route PDF generation and fetching of the data and we'll need another get request which is simply going to send the generated PDF to the client okay first we are going to create this post request okay we can simply tap AB that post it requires a request name or route so it's route is going to be equal to create PDF and it requires a callback function which has request and response okay now that is setup we are simply going to call our PDF that we have from here this HTML PDF allows you to actually create videos so we'll call PDF that create and this method as you can see here requires HTML as a string so we are simply going to pass our created PDF template along with request that data because inside of this request that data is where all our dynamic data is so as you can see here inside of create PDF we are sending our this that state which has all the necessary data and we are passing the data inside to our PDF template our create function also requires options which we will leave empty so just empty object okay now we can call another method that PDF provides from HTML PDF that is going to be equal to to file new file basically creates a file for us first first parameter you need to pass the to file is file name so we'll type the result results that PDF and the second parameter is callback function with the error if we have one so we'll create a callback function and the in here we can check check if there is an error so if error will simply going to return promise that reject that we can use in our client and if there is no error through those simply return promise that result so we can call that then inside of our client ok basically that's it for our PDF generation we have our PDF that create where we pass our PDF template in which we pass all the data coming from the client finally we can create our fetch PDF route inside of here we are going to simply have one get request so we'll type app that get the route name is going to be fetch PDF and now it is also going to have request and response as a callback and in here we can simply send our file that was just generated so we'll type dress that send file and it is going to be equal to template string and then double underscore dear name this is going to find our directory and then we can just type result that PDF so we are going to fetch it and then send it down back to our client ok that's basically it now we can move on to our client side and actually generate and down our PDF so in here we for now have just a post request as you can see here that sends the data down to this request the data passes it to the PDF template down to this create which simply creates PDF and puts it to a file called result PDF okay now since we have that done on this we can call sorry since we have promised that resolve we can call that done on this and in here we can simply call our other requests so it's going to be Axios get and it is going to be fetch PDF as we mentioned there okay but one important thing we need to do here is we need to set response type equal to blob now blob is not something that is used really often in JavaScript but it is an important aspect so we first need to cover what a blob is one sentence explanation of what blobs are without any technical terms that I could come up with is blobs are immutable objects that represent raw data so they are often used for representing data that isn't necessarily in a JavaScript format like our PDF they're a blob object represents a chunk of bytes that holds the data of a file blobs allow you to construct file like objects on the client that you can pass to api's that expect URLs instead of requiring the server to provide the files now that you know something more about the blobs we can create one and then actually download it okay we can call another that that since our since our fetch PDF actually returns that file it is going to be situated inside of the response and then we can use that response to create a blob which will simply pass to the I save as a file server to download the generated PDF so we can create a PDF block which is going to be equal to new blob so you can create blobs but by using a blob constructor and then passing an array so it's array inside of which there is there is a response that's data with this data we need also we need to also set the type which is going to be equal to application PDF okay with this setup we are basically good to go we created a PDF blog by passing response the data that is coming from our server and we set the type to application PDF after we have created the blob we can use save as method that we imported from file saver module to download the newly generated PDF save as takes in the newly generated PDF as well as the name of the file as a second parameter so we can call save as pass in our newly generated PDF blob and the name of our generated PDF which can be new PDF that PDF that is basically it okay now that is done we can actually run our client and our server to generate our PDF so our client is currently running on localhost 3000 we can open it and see it right here and our server isn't running yet so make sure you are in server so if you were in documents you need to get back one directory by typing CD dot dot and then you can write node one index that is which will simply run our Express server for us ok I just noticed that this should be request that body and not request the data so sorry for some of you who actually noticed this or mostly all of you who noticed that this is the data that's coming from request that body and this shouldn't be returned this should be response that sense because we aren't returning it we are simply sending it back to our client okay now this is setup we can go back to our page we can clear all the earth this errors here I just know this and we can simply click download PDF as you can see here we got our download here new PDF that PDF if we click it we get our nice-looking PDF file that was completely dynamically generated with the date and received number and all of that so this is really good this is nice and as you can see here if we type some different information like I don't know your name and we type something else and we click download PDF we will get another PDF right here and it is going to have all the new information so your possibilities are basically endless you can dynamically print receives or staff the need to change daily okay so this is basically it's a really simple but powerful way to generate dynamic PDFs and download them right away thank you for watching and if you liked the video subscribe to JavaScript mastery this channel is brand new and I'm planning to post more quality content on here so stay tuned and thank you for watching [Music]

Original Description

In this video, you’ll learn how to generate dynamic PDFs using Node.js and React. The PDFs will be generated from an HTML file, so anything you can build with HTML and CSS can be converted into a fully dynamic PDF. 💬 Some of my favorite tools: Hostinger: https://jsm.dev/hostinger + Use coupon JAVASCRIPTMASTERY Junie AI: https://jsm.dev/junie WebStorm: https://jsm.dev/webstorm Explore my Pro Content: ⭐ Join JS Mastery Pro: https://jsmastery.com 💎 Become Top 1% Next.js Developer: https://jsm.dev/nextjs 👨‍🔬 Master Next.js Testing: https://jsm.dev/testing 📗 GSAP Animations Course: https://jsm.dev/gsap 📕 Three.js 3D Course: https://jsm.dev/threejs 📙 JavaScript Course: https://jsm.dev/javascript 🚀 Launch Your SaaS: https://jsm.dev/saas Many Pro Courses launching soon! Join the waitlists to get notified! 🔥🔥 👉 React Native Course Waitlist: https://jsm.dev/native 👉 Backend Course Waitlist: https://jsm.dev/backend 👉 React Course Waitlist: https://jsm.dev/react 👉 Tailwind Course Waitlist: https://jsm.dev/tailwind 👉 AI Development Course Waitlist: https://jsm.dev/ai ⚠ Links not working? → If you're in Nigeria, you'll have to use a VPN due to regional restrictions. ⚠ Something mentioned in the video isn’t listed here or a link is broken: → contact support@jsmastery.pro 📚 Resources: — Repository: https://github.com/adrianhajdin/tutorial_pdf_generation HTML Template: https://gist.github.com/adrianhajdin/ca4b094f65d244edba20a83db8d1da30 — Rate us on TrustPilot: https://jsm.dev/trustpilot https://discord.com/invite/n6EdbFJ https://twitter.com/jsmasterypro https://instagram.com/javascriptmastery https://linkedin.com/company/javascriptmastery Business Inquiries: contact@jsmastery.pro
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from JavaScript Mastery · JavaScript Mastery · 6 of 60

1 Learn Async/Await in This Real World Project
Learn Async/Await in This Real World Project
JavaScript Mastery
2 JavaScript Exercise | Learn JavaScript with Exercism | #0 Setup
JavaScript Exercise | Learn JavaScript with Exercism | #0 Setup
JavaScript Mastery
3 JavaScript ES6 for Beginners
JavaScript ES6 for Beginners
JavaScript Mastery
4 ES7 and ES8 New Features
ES7 and ES8 New Features
JavaScript Mastery
5 Learn JSON in a Real World React App
Learn JSON in a Real World React App
JavaScript Mastery
How to Create PDFs With Node JS and React
How to Create PDFs With Node JS and React
JavaScript Mastery
7 Must Have Visual Studio Code Extensions
Must Have Visual Studio Code Extensions
JavaScript Mastery
8 Top 10 JavaScript Array Methods
Top 10 JavaScript Array Methods
JavaScript Mastery
9 JavaScript Map and Set Explained
JavaScript Map and Set Explained
JavaScript Mastery
10 Git Commands Tutorial for Beginners
Git Commands Tutorial for Beginners
JavaScript Mastery
11 Build and Deploy a YouTube Clone Application Using React
Build and Deploy a YouTube Clone Application Using React
JavaScript Mastery
12 React Hooks - Most Used Features
React Hooks - Most Used Features
JavaScript Mastery
13 JavaScript Best Practices and Coding Conventions - Write Clean Code
JavaScript Best Practices and Coding Conventions - Write Clean Code
JavaScript Mastery
14 Build and Deploy a Realtime Chat Application - Socket.io, Node.js, and React.js
Build and Deploy a Realtime Chat Application - Socket.io, Node.js, and React.js
JavaScript Mastery
15 How to Create and Deploy a Portfolio Site in less than 30 Minutes
How to Create and Deploy a Portfolio Site in less than 30 Minutes
JavaScript Mastery
16 SEO for Developers | 2020 SEO Tutorial
SEO for Developers | 2020 SEO Tutorial
JavaScript Mastery
17 Web Development Roadmap 2020 [Learning Path] - Start Coding at Home!
Web Development Roadmap 2020 [Learning Path] - Start Coding at Home!
JavaScript Mastery
18 Random Quote Generator - React Fetch API Data | Build and Deploy a Real Advice App Project
Random Quote Generator - React Fetch API Data | Build and Deploy a Real Advice App Project
JavaScript Mastery
19 Build a COVID-19 Tracker Application - React JS Project (Hooks, Material UI, Charts js)
Build a COVID-19 Tracker Application - React JS Project (Hooks, Material UI, Charts js)
JavaScript Mastery
20 JavaScript ES2020 - The Most Requested Feature Explained in 10 Minutes
JavaScript ES2020 - The Most Requested Feature Explained in 10 Minutes
JavaScript Mastery
21 Modern React Event Handling Using Hooks
Modern React Event Handling Using Hooks
JavaScript Mastery
22 Deno JS - Intro +  Real Life Example
Deno JS - Intro + Real Life Example
JavaScript Mastery
23 Build and Deploy a React PWA - Why Progressive Web Apps are the Future of the Web
Build and Deploy a React PWA - Why Progressive Web Apps are the Future of the Web
JavaScript Mastery
24 Build a REST API with Node JS and Express | CRUD API Tutorial
Build a REST API with Node JS and Express | CRUD API Tutorial
JavaScript Mastery
25 Build and Deploy an ARTIFICIAL INTELLIGENCE React App | Alan AI, JavaScript
Build and Deploy an ARTIFICIAL INTELLIGENCE React App | Alan AI, JavaScript
JavaScript Mastery
26 Master Async JavaScript using Async/Await | Quokka JS
Master Async JavaScript using Async/Await | Quokka JS
JavaScript Mastery
27 Spaced Repetition in Programming | mem.dev
Spaced Repetition in Programming | mem.dev
JavaScript Mastery
28 Stop Copy & Pasting Code | mem.dev
Stop Copy & Pasting Code | mem.dev
JavaScript Mastery
29 GitHub Profile README | Create an Amazing Profile Readme | Setup + Templates
GitHub Profile README | Create an Amazing Profile Readme | Setup + Templates
JavaScript Mastery
30 NEW GitHub CLI 1.0 is here! | GitHub CLI Tutorial - Demo & Commands
NEW GitHub CLI 1.0 is here! | GitHub CLI Tutorial - Demo & Commands
JavaScript Mastery
31 React Custom Hooks | Learn Custom Hooks & Build a Project
React Custom Hooks | Learn Custom Hooks & Build a Project
JavaScript Mastery
32 Learn how to deploy an NPM Package
Learn how to deploy an NPM Package
JavaScript Mastery
33 JavaScript Algorithms for Beginners
JavaScript Algorithms for Beginners
JavaScript Mastery
34 Level UP your GitHub Game - Get Hired Quickly
Level UP your GitHub Game - Get Hired Quickly
JavaScript Mastery
35 The Best Way to Host & Deploy a React Application
The Best Way to Host & Deploy a React Application
JavaScript Mastery
36 Full Stack MERN Project - Build and Deploy an App | React + Redux, Node, Express, MongoDB [Part 1/2]
Full Stack MERN Project - Build and Deploy an App | React + Redux, Node, Express, MongoDB [Part 1/2]
JavaScript Mastery
37 Full Stack MERN Project - Build and Deploy an App | React + Redux, Node, Express, MongoDB [Part 2/2]
Full Stack MERN Project - Build and Deploy an App | React + Redux, Node, Express, MongoDB [Part 2/2]
JavaScript Mastery
38 ECommerce Web Shop - Build & Deploy an Amazing App | React.js, Commerce.js, Stripe
ECommerce Web Shop - Build & Deploy an Amazing App | React.js, Commerce.js, Stripe
JavaScript Mastery
39 JavaScript Crash Course 2021 - Master JavaScript in One Video!
JavaScript Crash Course 2021 - Master JavaScript in One Video!
JavaScript Mastery
40 MERN Auth - Login with Email (JWT) + Google OAuth Authentication | React, Node, Express, MongoDB
MERN Auth - Login with Email (JWT) + Google OAuth Authentication | React, Node, Express, MongoDB
JavaScript Mastery
41 Chat Application using React JS - Build and Deploy a Chat App in 1 Hour (Microsoft Teams)
Chat Application using React JS - Build and Deploy a Chat App in 1 Hour (Microsoft Teams)
JavaScript Mastery
42 MUST USE Websites & Tools for Web Developers
MUST USE Websites & Tools for Web Developers
JavaScript Mastery
43 Learn Material UI in One Hour - React Material UI Project Tutorial [2022]
Learn Material UI in One Hour - React Material UI Project Tutorial [2022]
JavaScript Mastery
44 Shopify ECommerce Store with React & Next JS | BuilderIO
Shopify ECommerce Store with React & Next JS | BuilderIO
JavaScript Mastery
45 React Video Chat App | WebRTC Video Chat Zoom Clone | Tabnine
React Video Chat App | WebRTC Video Chat Zoom Clone | Tabnine
JavaScript Mastery
46 TypeScript Crash Course 2021
TypeScript Crash Course 2021
JavaScript Mastery
47 Build and Deploy a Premium Next JS React Website | Landing Page, Business Website, Portfolio
Build and Deploy a Premium Next JS React Website | Landing Page, Business Website, Portfolio
JavaScript Mastery
48 Full Stack MERN Project - Pagination & Search | React + Redux, Node, Express, MongoDB
Full Stack MERN Project - Pagination & Search | React + Redux, Node, Express, MongoDB
JavaScript Mastery
49 Build a BETTER Facebook Messenger Chat Application | React JS, Firebase, Chat Engine
Build a BETTER Facebook Messenger Chat Application | React JS, Firebase, Chat Engine
JavaScript Mastery
50 Build and Deploy THE PERFECT Portfolio Website | Create a Portfolio from Scratch
Build and Deploy THE PERFECT Portfolio Website | Create a Portfolio from Scratch
JavaScript Mastery
51 Full Stack MERN Project - Implement MERN Comments | React + Redux, Node, Express, MongoDB
Full Stack MERN Project - Implement MERN Comments | React + Redux, Node, Express, MongoDB
JavaScript Mastery
52 Turn an API into a Startup?! Build & Sell an API with JavaScript
Turn an API into a Startup?! Build & Sell an API with JavaScript
JavaScript Mastery
53 Exclusive First Look at GitHub Copilot - All you need to know
Exclusive First Look at GitHub Copilot - All you need to know
JavaScript Mastery
54 Build and Deploy a Google Maps Travel Companion Application | React.js
Build and Deploy a Google Maps Travel Companion Application | React.js
JavaScript Mastery
55 Build and Deploy a Full Stack Realtime Chat Messaging App with Authentication & SMS Notifications
Build and Deploy a Full Stack Realtime Chat Messaging App with Authentication & SMS Notifications
JavaScript Mastery
56 Build and Deploy a React Cryptocurrency App and Master Redux Toolkit in One Video
Build and Deploy a React Cryptocurrency App and Master Redux Toolkit in One Video
JavaScript Mastery
57 Build and Deploy a Group Video Chat Application with Messaging, Polls & More
Build and Deploy a Group Video Chat Application with Messaging, Polls & More
JavaScript Mastery
58 Build and Deploy Google Search 2.0 with React & Tailwind CSS (simple!)
Build and Deploy Google Search 2.0 with React & Tailwind CSS (simple!)
JavaScript Mastery
59 Top 10 Web Development Chrome Extensions You Simply Need to Try!
Top 10 Web Development Chrome Extensions You Simply Need to Try!
JavaScript Mastery
60 Build and Deploy THE BEST Modern Blog App with React | GraphQL, NextJS, Tailwind CSS
Build and Deploy THE BEST Modern Blog App with React | GraphQL, NextJS, Tailwind CSS
JavaScript Mastery

This video teaches how to generate dynamic PDFs using Node.js and React, covering topics such as setting up a React app, creating a server, and using HTML to PDF library to generate PDFs. By following this tutorial, viewers can learn how to create dynamic PDFs with data from a server response.

Key Takeaways
  1. Create a new directory for the client side
  2. Create a new directory for the server side
  3. Install dependencies using npm
  4. Set up a proxy in the client's package.json
  5. Delete existing JSX in the app component
  6. Create a PDF template using HTML to PDF library
  7. Pass data to PDF template using create function
  8. Fetch PDF route sends generated PDF to client
  9. Use Axios to fetch PDF from server
  10. Set response type to blob to download PDF
💡 The video demonstrates how to use the HTML to PDF library to generate PDFs dynamically with data from a server response, and how to use Axios to fetch the generated PDF from the server.

Related Reads

📰
Debugging React: From Taking a Deep Breath to Finding the Root Cause
Learn to debug React applications by taking a systematic approach to identify and fix issues
Dev.to · surajrkhonde
📰
Next.js vs Remix vs SvelteKit: Which Framework Should You Learn?
Learn how to choose between Next.js, Remix, and SvelteKit for your next project and why it matters for your career as a developer
Dev.to · Etrit Neziri
📰
Had my Frontend Developer interview with Capgemini (Application Developer) today, and I wanted to…
Prepare for a frontend developer interview with Capgemini by reviewing JavaScript fundamentals and practicing common interview questions
Medium · JavaScript
📰
10 Frontend Developer Tools to Boost Productivity in 2026
Boost frontend productivity with 10 essential tools for modern web app development
Medium · Programming
Up next
The masks we wear | Zora Krstić | TEDxLuxembourgCity
TEDx Talks
Watch →