forked from Hopding/pdf-lib
-
Notifications
You must be signed in to change notification settings - Fork 2
/
test9.ts
62 lines (53 loc) · 1.77 KB
/
test9.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import fontkit from '@pdf-lib/fontkit';
import { Assets } from '..';
import { ParseSpeeds, PDFDocument, rgb } from '../../..';
export default async (assets: Assets) => {
const { pdfs, fonts, images } = assets;
const pdfDoc = await PDFDocument.load(pdfs.with_comments, {
parseSpeed: ParseSpeeds.Fastest,
});
pdfDoc.registerFontkit(fontkit);
const ubuntuFont = await pdfDoc.embedFont(fonts.ttf.ubuntu_r, {
subset: true,
});
const smallMarioImage = await pdfDoc.embedPng(images.png.small_mario);
const smallMarioDims = smallMarioImage.scale(0.15);
const pages = pdfDoc.getPages();
const lines = [
'This is an image of Mario running.',
'This image and text was drawn on',
'top of an existing PDF using pdf-lib!',
];
const fontSize = 24;
const solarizedWhite = rgb(253 / 255, 246 / 255, 227 / 255);
const solarizedGray = rgb(101 / 255, 123 / 255, 131 / 255);
const textWidth = ubuntuFont.widthOfTextAtSize(lines[2], fontSize);
pages.forEach((page) => {
const { width, height } = page.getSize();
const centerX = width / 2;
const centerY = height / 2 - 250;
page.drawImage(smallMarioImage, {
...smallMarioDims,
x: centerX - smallMarioDims.width / 2,
y: centerY + 15,
});
const boxHeight = (fontSize + 5) * lines.length;
page.drawRectangle({
x: centerX - textWidth / 2 - 5,
y: centerY - 15 - boxHeight + fontSize + 3,
width: textWidth + 10,
height: boxHeight,
color: solarizedWhite,
borderColor: solarizedGray,
borderWidth: 3,
});
page.setFont(ubuntuFont);
page.setFontColor(solarizedGray);
page.drawText(lines.join('\n'), {
x: centerX - textWidth / 2,
y: centerY - 15,
});
});
const pdfBytes = await pdfDoc.save();
return pdfBytes;
};