Link Annotation inside pdfkit and node-signpdf
Software Used:
- Nodejs
- pdfkit 1.23
- node-signpdf 1.2.3
- node-forge 0.7.6
Wanted:
I want to create a pdf that has a link inside it and sign that pdf with password
Question:
How to do it … ?
Answer:
We will create 2 files:
- helpers.js
- index.js used
helpers.js
Create a file named it helpers.js and insert this code below:
const PDFDocument = require('pdfkit');
module.exports = {
createPdf(params) {
return new Promise((resolve) => {
const pdf = new PDFDocument({
autoFirstPage: true,
size: 'A4',
layout: 'portrait',
bufferPages: true,
});
pdf.info.CreationDate = '';
pdf.text(params.title,75,90)
pdf.text('Copyright © 2020',{continued:true}).fillColor('blue')
pdf.text('Fahmi Basya',{link: 'https://a2fahmi.com'})
const pdfChunks = [];
pdf.on('data', (data) => {
pdfChunks.push(data);
});
pdf.on('end', () => {
resolve(Buffer.concat(pdfChunks));
});
pdf.end();
})
}
}
Explain:
- pdf.text(params.title,75,90) used for create text in x-coordinate=75 and y-coordinate = 90
- pdf.text(‘Fahmi Basya’,{link: ‘http://a2fahmi.com’}) used for create a ‘Fahmi Basya’ text and linked to ‘http://a2fahmi.com’
index.js
const {SignPdf} = require('node-signpdf');
const fs = require('fs');
const {plainAddPlaceholder} = require ('node-signpdf/dist/helpers');
const {createPdf} = require('./helpers');
const signPdf = new SignPdf();
async function signPdfWithPassphrase(passphrase) {
const p12Buffer = fs.readFileSync(`${__dirname}/resources/withpass.p12`);
let data={title:'Learning Creating PDF with nodejs and pdfkit'}
let pdfBuffer = await createPdf(data);
pdfBuffer = plainAddPlaceholder({
pdfBuffer,
reason: 'I have reviewed it.',
signatureLength: 1612,
});
const signedPdfBuffer = signPdf.sign(
pdfBuffer,
p12Buffer,
{passphrase}
);
const outputPath = `${__dirname}/output/pdfkit-sample-signed-with-passphrase.pdf`;
fs.writeFileSync(outputPath, signedPdfBuffer);
console.log('Pdf signed and saved to:', outputPath);
}
Running the Code
Just call this code:
signPdfWithPassphrase('your password')
Thanks for reading