Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save documentprocessing/3d1580980ef05e239725048e6232b3e3 to your computer and use it in GitHub Desktop.

Select an option

Save documentprocessing/3d1580980ef05e239725048e6232b3e3 to your computer and use it in GitHub Desktop.
Create PDF & Add Content to PDF, Modify PDF Document and Create PDF Forms in JavaScript using pdf-lib Library. Check https://products.documentprocessing.com/editor/javascript/pdf-lib/ for more details.
// Import required objects and functions from pdf-lib library
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
// Import fs module from Node.js standard library
import fs from 'fs/promises';
// Asynchronously create a PDF document
async function createPdf() {
// Create a new PDF document
const pdfDoc = await PDFDocument.create();
// Embed the Times Roman font
const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman);
// Add a new page to the PDF document
const page = pdfDoc.addPage();
const { width, height } = page.getSize();
const fontSize = 30;
// Draw text on the page
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),
});
// Save the PDF document to a byte array
const pdfBytes = await pdfDoc.save();
// Write the byte array to an 'output.pdf' file
await fs.writeFile('output.pdf', pdfBytes);
console.log(`PDF saved`);
}
// Call the createPdf function to generate and save the PDF
createPdf();
// Import PDFDocument object from pdf-lib library
import { PDFDocument } from 'pdf-lib';
// Import fs module from Node.js standard library
import fs from 'fs/promises';
async function createForm() {
// Create a new PDF document
const pdfDoc = await PDFDocument.create();
// Add a page with dimensions 550x750
const page = pdfDoc.addPage([550, 750]);
// Access the form in the PDF document
const form = pdfDoc.getForm();
// Add text to the page
page.drawText('Enter your favorite superhero:', { x: 50, y: 700, size: 20 });
// Create and add a text field for the favorite superhero
const superheroField = form.createTextField('favorite.superhero');
superheroField.setText('One Punch Man');
superheroField.addToPage(page, { x: 55, y: 640 });
// Add more text and create a radio group for favorite rockets
page.drawText('Select your favorite rocket:', { x: 50, y: 600, size: 20 });
page.drawText('Falcon Heavy', { x: 120, y: 560, size: 18 });
// Create and add a radio group for favorite rockets
const rocketField = form.createRadioGroup('favorite.rocket');
rocketField.addOptionToPage('Falcon Heavy', page, { x: 55, y: 540 });
rocketField.addOptionToPage('Saturn IV', page, { x: 55, y: 480 });
rocketField.select('Saturn IV');
// Create and add checkboxes for favorite gundams
const exiaField = form.createCheckBox('gundam.exia');
const kyriosField = form.createCheckBox('gundam.kyrios');
// Check specific checkboxes
exiaField.check();
dynamesField.check();
// Create and add a dropdown for favorite planets
const planetsField = form.createDropdown('favorite.planet');
planetsField.addOptions(['Venus', 'Earth', 'Mars', 'Pluto']);
planetsField.select('Pluto');
planetsField.addToPage(page, { x: 55, y: 220 });
// Create and add an option list for favorite persons
const personField = form.createOptionList('favorite.person');
personField.addOptions([
'Julius Caesar',
'Ada Lovelace',
'Cleopatra',
'Aaron Burr',
'Mark Antony',
]);
personField.select('Ada Lovelace');
personField.addToPage(page, { x: 55, y: 70 });
// Add a note about Pluto
page.drawText(`* Pluto should be a planet too!`, { x: 15, y: 15, size: 15 });
// Save the PDF document
const pdfBytes = await pdfDoc.save();
// Write the PDF to a file
await fs.writeFile("form.pdf", pdfBytes);
}
// Call the createForm function to create the form and save it as 'form.pdf'
createForm()
.then(() => {
console.log('Form Created');
})
.catch((error) => {
console.error('Error in creating form', error);
});
// Import required objects and functions from pdf-lib library
import { degrees, PDFDocument, rgb, StandardFonts } from 'pdf-lib';
// Asynchronously modify a PDF document
async function modifyPdf() {
// Load the input PDF from a local file
const filePath = 'documentprocessing.pdf'; file name
const existingPdfBytes = await fs.readFile(filePath);
// Load PDF document from the binary data and embed Helvetica font into it asynchronously
const pdfDoc = await PDFDocument.load(existingPdfBytes);
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
// Get all pages of the PDF document
const pages = pdfDoc.getPages();
// Get first page of the PDF
const firstPage = pages[0];
// Get the height & width of the first page of the PDF
const { width, height } = firstPage.getSize();
// Add diagonal red text to the first page
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),
});
// Save changes to the PDF document as binary data
const modifiedPdfBytes = await pdfDoc.save();
// Save the modified PDF in binary form to a file
await fs.writeFile("modified-pdf.pdf", modifiedPdfBytes);
}
// Call the modifyPdf function to modify and save the PDF
modifyPdf()
.then(() => {
console.log('PDF modification complete');
})
.catch((error) => {
console.error('Error modifying PDF:', error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment