2023-02-20 18:14:52 +01:00
|
|
|
import fontkit from "@pdf-lib/fontkit";
|
|
|
|
|
import * as fs from "fs";
|
2023-04-04 22:02:32 +00:00
|
|
|
import { PDFDocument, StandardFonts, rgb } from "pdf-lib";
|
2023-02-18 14:37:26 +01:00
|
|
|
|
|
|
|
|
export async function insertTextInPDF(
|
|
|
|
|
pdfAsBase64: string,
|
|
|
|
|
text: string,
|
|
|
|
|
positionX: number,
|
|
|
|
|
positionY: number,
|
2023-02-28 19:36:21 +01:00
|
|
|
page: number = 0,
|
|
|
|
|
useHandwritingFont = true
|
2023-02-18 14:37:26 +01:00
|
|
|
): Promise<string> {
|
2023-02-20 18:14:52 +01:00
|
|
|
const fontBytes = fs.readFileSync("public/fonts/Qwigley-Regular.ttf");
|
|
|
|
|
|
2023-04-06 23:16:20 +10:00
|
|
|
const pdfDoc = await PDFDocument.load(pdfAsBase64);
|
2023-02-18 14:37:26 +01:00
|
|
|
|
2023-02-20 18:14:52 +01:00
|
|
|
pdfDoc.registerFontkit(fontkit);
|
2023-04-06 23:16:20 +10:00
|
|
|
|
|
|
|
|
const font = await pdfDoc.embedFont(useHandwritingFont ? fontBytes : StandardFonts.Helvetica);
|
2023-02-18 14:37:26 +01:00
|
|
|
|
|
|
|
|
const pages = pdfDoc.getPages();
|
2023-02-20 14:49:17 +01:00
|
|
|
const pdfPage = pages[page];
|
2023-04-06 23:16:20 +10:00
|
|
|
|
2023-02-28 19:36:21 +01:00
|
|
|
const textSize = useHandwritingFont ? 50 : 15;
|
2023-04-06 23:16:20 +10:00
|
|
|
const textWidth = font.widthOfTextAtSize(text, textSize);
|
|
|
|
|
const textHeight = font.heightAtSize(textSize);
|
2023-03-07 16:21:57 +01:00
|
|
|
const fieldSize = { width: 192, height: 64 };
|
2023-04-06 23:16:20 +10:00
|
|
|
|
|
|
|
|
// Because pdf-lib use a bottom-left coordinate system, we need to invert the y position
|
|
|
|
|
// we then center the text in the middle by adding half the height of the text
|
|
|
|
|
// plus the height of the field and divide the result by 2
|
|
|
|
|
const invertedYPosition =
|
|
|
|
|
pdfPage.getHeight() - positionY - (fieldSize.height + textHeight / 2) / 2;
|
|
|
|
|
|
|
|
|
|
// We center the text by adding the width of the field, subtracting the width of the text
|
|
|
|
|
// and dividing the result by 2
|
|
|
|
|
const centeredXPosition = positionX + (fieldSize.width - textWidth) / 2;
|
2023-02-20 14:49:17 +01:00
|
|
|
|
|
|
|
|
pdfPage.drawText(text, {
|
2023-04-06 23:16:20 +10:00
|
|
|
x: centeredXPosition,
|
2023-03-07 16:21:57 +01:00
|
|
|
y: invertedYPosition,
|
2023-02-20 18:14:52 +01:00
|
|
|
size: textSize,
|
2023-02-18 14:37:26 +01:00
|
|
|
color: rgb(0, 0, 0),
|
2023-04-06 23:16:20 +10:00
|
|
|
font,
|
2023-02-18 14:37:26 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const pdfAsUint8Array = await pdfDoc.save();
|
|
|
|
|
return Buffer.from(pdfAsUint8Array).toString("base64");
|
|
|
|
|
}
|