foliojs / pdfkit

A JavaScript PDF generation library for Node and the browser

Home Page:http://pdfkit.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

invisible text layer

lbr991 opened this issue · comments

commented

I'm trying to take a non-searchable pdf and convert it to searchable pdf by superimposing an invisible text layer.
I need the invisible text bboxes to align exactly with the original bboxes (extracted by Textract).
I also don't want to specify a font and font_size because then the bboxes wouldn't align perfectly.

Is this possible with pdfkit?

const PDFDocument = require('pdfkit');
const fs = require('fs');

const originalText = 'This text will be searchable';
const invisibleText = 'This text will be invisible';

const doc = new PDFDocument();

const outputPath = 'output.pdf';

// Set the position where you want to add the text
const x = 100;
const y = 100;

// Get the bounding box of the original text without specifying fontSize and font
const originalBBox = doc.widthOfString(originalText);

doc.text(originalText, x, y);

doc.opacity(0.0); // Set opacity (0.0: completely invisible, 1.0: fully visible)
doc.text(invisibleText, x + originalBBox.width, y);

// Save the file
doc.pipe(fs.createWriteStream(outputPath));
doc.end();

console.log('PDF created:', outputPath);

With this updated code, the invisible text will be positioned exactly to the right of the visible text, maintaining the same alignment without specifying the font size and font family.

You try it.