PDF-lib.js is a JavaScript library that enables developers to create, modify and manipulate PDF documents in the browser or server-side using Node.js. It provides a range of features such as creating new PDF documents, adding text, images, and shapes, and modifying existing PDF documents.
The library is built on top of PDF.js, a popular open-source PDF viewer, and is designed to be easy to use and flexible. It provides a simple API for creating and modifying PDF documents, allowing developers to customize and automate the process of PDF generation.
Some of the key features of PDF-lib.js include:
➡️ Creating new PDF documents from scratch or merging existing ones
➡️ Adding text, images, and shapes to PDF documents
➡️ Modifying existing PDF documents by changing text, images, and other content
➡️ Encrypting and decrypting PDF documents
➡️ Adding digital signatures to PDF documents
➡️ Extracting data from PDF documents
PDF-lib.js is compatible with most modern browsers and supports both client-side and server-side PDF document manipulation. It is also available as an npm package for easy installation and integration with Node.js projects.
Overall, PDF-lib.js is a powerful and flexible library that simplifies working with PDF documents in JavaScript.
To create a PDF document in React using PDF-lib.js, you need to follow these steps:
1. Install the library:
npm install pdf-lib
2. Import the necessary classes from the library:
import { PDFDocument, StandardFonts } from 'pdf-lib';
3. Define a function that will create the PDF document:
async function createPdf() { const pdfDoc = await PDFDocument.create() const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman) const page = pdfDoc.addPage() const { width, height } = page.getSize() const fontSize = 30 page.drawText('Creating PDFs in JavaScript is awesome!', { x: 50, y: height - 4 * fontSize, size: fontSize, font: timesRomanFont, color: rgb(0, 0.53, 0.71), }) const pdfBytes = await pdfDoc.save() // Create a Blob object from the Uint8Array const pdfBlob = new Blob([pdfBytes], { type: 'application/pdf' }); // Download the PDF file saveAs(pdfBlob, 'example.pdf'); }
4. Call the createpdf function to generate the PDF document:
<button onClick={createPdf}>Create PDF</button>
Related read: Creating PDFs with ReactJS: A Step-by-Step Guide
import { degrees, PDFDocument, rgb, StandardFonts } from 'pdf-lib'; async function modifyPdf() { const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf' const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer()) const pdfDoc = await PDFDocument.load(existingPdfBytes) const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica) const pages = pdfDoc.getPages() const firstPage = pages[0] const { width, height } = firstPage.getSize() firstPage.drawText('This text was added with JavaScript!', { x: 5, y: height / 2 + 300, size: 50, font: helveticaFont, color: rgb(0.95, 0.1, 0.1), rotate: degrees(-45), }) const pdfBytes = await pdfDoc.save() }
Here is an example of how you can fill in a PDF form using PDF-lib.js in React.
import { PDFDocument } from 'pdf-lib'; async function fillPdfForm() { // Fetch the PDF file as a Uint8Array const response = await fetch('/path/to/example.pdf'); const pdfBytes = await response.arrayBuffer(); // Load the PDF document const pdfDoc = await PDFDocument.load(pdfBytes); // Get the PDF form const form = pdfDoc.getForm(); // Fill in the form fields form.getTextField('First Name').setText('John'); form.getTextField('Last Name').setText('Doe'); form.getCheckBox('Agree').check(); form.getRadioGroup('Gender').select('Male'); // Save the PDF document const pdfBytesFilled = await pdfDoc.save(); // Download the filled PDF document const blob = new Blob([pdfBytesFilled], { type: 'application/pdf' }); const url = URL.createObjectURL(blob); window.open(url); }
This code snippet loads a PDF file, gets its form, and fills in the text fields, checkboxes, and radio buttons using the setText, check, and select methods. Finally, it saves the filled PDF document and downloads it. You can customize this code snippet to fit your specific use case.
Flattening a PDF is the process of removing the form fields and annotations from the document and converting them into simple graphics. When a PDF document is flattened, the fields and annotations become part of the page content and can no longer be edited or interacted with.
Flattening a PDF is useful when you want to preserve the document’s appearance and prevent changes to the content. For example, if you are distributing a form or document that should not be altered by the recipient, you can flatten the PDF to ensure that the fields and annotations cannot be modified.
However, flattening a PDF also means that the form fields and annotations will no longer be accessible or editable, which may be a disadvantage if you need to modify the document in the future.
It’s important to note that flattening a PDF is a permanent change and cannot be undone. Before flattening a PDF, you should make sure that you have saved a copy of the original document in case you need to make changes later.
import { PDFDocument } from 'pdf-lib'; async function flattenPdf() { // Fetch the PDF file as a Uint8Array const response = await fetch('example.pdf'); const pdfBytes = await response.arrayBuffer(); // Load the PDF document const pdfDoc = await PDFDocument.load(pdfBytes); // Flatten the PDF document pdfDoc.flatten(); // Serialize the flattened PDF document to a Uint8Array const pdfBytesFlattened = await pdfDoc.save(); // Create a Blob object from the Uint8Array const pdfBlob = new Blob([pdfBytesFlattened], { type: 'application/pdf' }); // Download the flattened PDF file saveAs(pdfBlob, 'flattened.pdf'); }
In conclusion, PDF-lib.js is a powerful library that unlocks a multitude of possibilities for working with PDF documents. Whether you need to create new PDFs by adding text and images, incorporate new pages into existing PDFs, or modify PDFs by adding, modifying, or removing elements like text, images, and annotations, PDF-lib.js makes the process effortless.
Furthermore, PDF forms can be easily filled out by setting field values. And when the need arises, PDF-lib.js allows you to flatten PDF documents, preserving their appearance and preventing further changes by removing form fields and annotations. With its flexibility and functionality, PDF-lib.js proves to be a valuable tool for PDF manipulation.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork