Newer
Older
// import verifyPDF from "@ninja-labs/verify-pdf";
import { PDFName, PDFPage, PDFString, PDFDocument } from "pdf-lib";
import { PdfData } from "pdfdataextract";
import { config } from "./config";
import { IgetMetaResponse } from "./types";
import { verifyPDF } from "./lib";
import { formatPdfTime } from "./lib/timeUtils";
class PDFparser {
readonly document;
readonly config;
constructor(document: Buffer) {
this.document = document;
this.config = config;
}
getPDFMeta = async (): Promise<IgetMetaResponse> => {
try {
const pdfMeta = await PdfData.extract(this.document, config);
const signaturesMeta = await verifyPDF(this.document);
expired: signaturesMeta.expired,
pages: pdfMeta.pages,
title: pdfMeta.info.Title || "Unknown",
author: pdfMeta.info.Author || "Unknown",
creation_date: formatPdfTime(pdfMeta.info.CreationDate),
mod_date: formatPdfTime(pdfMeta.info.ModDate),
if (signaturesMeta.signatures.length !== 0) {
result["signatures"] = signaturesMeta.signatures;
}
return result;
} catch (error) {
console.error(error);
throw new Error("Could not get pdf metadata");
}
};
const pdfDoc = await PDFDocument.load(this.document);
const img = await pdfDoc.embedPng(imgBytes);
for (let index = 0; index < pages.length; index++) {
const page = pages[index];
page.drawImage(img, {
x: page.getWidth() / 2 - scaled.width / 2,
y: page.getHeight() / 2 - scaled.height / 2,
width: scaled.width,
height: scaled.height,
});
const link = this.createPageLinkAnnotation(page, url, {
imgXPos: page.getWidth() / 2 - scaled.width / 2,
imgYPos: page.getHeight() / 2 - scaled.height / 2,
imgWidth: scaled.width,
imagHeight: scaled.height,
});
page.node.set(PDFName.of("Annots"), pdfDoc.context.obj([link]));
}
const pdfBytes = await pdfDoc.save();
return pdfBytes;
};
private createPageLinkAnnotation = (
page: PDFPage,
uri: string,
{ imgXPos, imgYPos, imgWidth, imagHeight }
) =>
page.doc.context.register(
page.doc.context.obj({
Type: "Annot",
Subtype: "Link",
Rect: [imgXPos, imgYPos, imgXPos + imgWidth, imgYPos + imagHeight],
A: {
Type: "Action",
S: "URI",
URI: PDFString.of(uri),
},
})
);