Newer
Older
import { PdfData } from "pdfdataextract";
import { config } from "./config";
import { IGetMetaResponse } from "./types";
import { verifyPDF } from "./lib";
import { formatPdfTime } from "./lib/timeUtils";
import { AppError, GeneralError } from "./lib/errors";
import { isPDF } from "./lib/generalUtils";
class PDFparser {
readonly document;
readonly config;
constructor(document: Buffer) {
this.document = document;
this.config = config;
}
getPDFMeta = async (): Promise<IGetMetaResponse> => {
if (!(this.document instanceof Buffer)) {
throw new AppError("Document is not Buffer");
}
if (!isPDF(this.document)) {
throw new AppError("Only pdf file type is supported");
}
try {
const signaturesMeta = await verifyPDF(this.document);
const pdfMeta = await PdfData.extract(this.document, config);
title: pdfMeta.info.Title || "Unknown",
author: pdfMeta.info.Author || "Unknown",
creation_date: formatPdfTime(pdfMeta.info.CreationDate),
mod_date: formatPdfTime(pdfMeta.info.ModDate),
result["expired"] = signaturesMeta.expired;
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];
const x =
typeof coords[index + 1] !== "undefined"
: null;
const y =
typeof typeof coords[index + 1] !== "undefined"
: null;
if (x && y) {
page.drawImage(img, {
x,
y,
width: scaled.width,
height: scaled.height,
});
const link = this.createPageLinkAnnotation(page, url, {
imgXPos: x,
imgYPos: y,
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),
},
})
);