How to Modify PDF File and Add Watermark Text in Deno Using PDF-LIB Library Full Tutorial With Example

How to Modify PDF File and Add Watermark Text in Deno Using PDF-LIB Library Full Tutorial With Example

 

Welcome folks today in this tutorial we will be modifying pdf file and adding watermark text using pdf-lib. The full source code of the example is given below.

 

 

Requirements

 

 

You should have Deno installed on your system

 

 

Get Started

 

 

In order to get started you need to create a app.ts file and copy paste the following code

 

 

app.ts

 

 

 

// To run this script with Deno:
//   deno run --allow-write --allow-net https://gist.githubusercontent.com/Hopding/2d25620f0fac5cf141123129cbf0a3d8/raw/pdf-lib-deno-modify-script.ts

import { PDFDocument, rgb, degrees } from 'https://cdn.skypack.dev/pdf-lib@^1.11.1?dts';

// Fetch an existing PDF file
const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf';
const existingPdfBytes = await fetch(url).then((res) => res.arrayBuffer());

// Load an existing PDFDocument
const pdfDoc = await PDFDocument.load(existingPdfBytes);

// Draw some text on the first page of the PDFDocument
const page = pdfDoc.getPage(0);
page.drawText('This text was added with Deno!', {
  x: 40,
  y: page.getHeight() / 2 + 250,
  size: 50,
  color: rgb(0.95, 0.1, 0.1),
  rotate: degrees(-45),
});

// Save the PDFDocument and write it to a file
const pdfBytes = await pdfDoc.save();
await Deno.writeFile('modify.pdf', pdfBytes);

// Done! 💥
console.log('PDF file written to modify.pdf');

 

See also  Build a Bubble Shooter Game in Browser Using Vanilla Javascript Full Project For Beginners

 

 

 

Now if you execute this deno script by executing this following command which is shown below

 

deno run --allow-write --allow-net app.ts

 

In this command there are two flags out there

 

--allow-write This flag is required to create new files inside the system

 

--allow-net` This flag is required for deno scripts to have internet access

 

 

Now if you execute this after this you will have modified.pdf created in the root directory

 

 

 

 

If you open this modified.pdf file you will see the following thing

 

 

 

 

 

 

Leave a Reply