forked from Hopding/pdf-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test5.js
60 lines (44 loc) · 1.73 KB
/
test5.js
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
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
import { fetchAsset, writePdf } from './assets';
export default async () => {
const [inputPdfBytes, minionsBananaAlphaBytes] = await Promise.all([
fetchAsset('pdfs/with_large_page_count.pdf'),
fetchAsset('images/minions_banana_alpha.png'),
]);
const pdfDoc = await PDFDocument.load(inputPdfBytes);
const timesRomanFont = await pdfDoc.embedFont(
StandardFonts.TimesRomanBoldItalic,
);
const minionsBananaImage = await pdfDoc.embedPng(minionsBananaAlphaBytes);
const minionsBananaDims = minionsBananaImage.scale(0.5);
const pages = pdfDoc.getPages();
pages.forEach((page) => {
const { width, height } = page.getSize();
page.drawImage(minionsBananaImage, {
...minionsBananaDims,
x: width / 2 - minionsBananaDims.width / 2,
y: height / 2 - minionsBananaDims.height / 2,
});
});
// Interleave new pages between all existing ones
pages.forEach((_, idx) => {
const newPage = pdfDoc.insertPage(2 * idx + 1, [500, 150]);
const fontSize = 24;
const { width, height } = newPage.getSize();
newPage.setFont(timesRomanFont);
newPage.setFontSize(fontSize);
const text = 'This page was interleaved by pdf-lib!';
const textWidth = timesRomanFont.widthOfTextAtSize(text, fontSize);
const textHeight = timesRomanFont.heightAtSize(fontSize);
newPage.drawText(text, {
x: width / 2 - textWidth / 2,
y: height / 2 - textHeight / 2,
color: rgb(0.7, 0.4, 0.9),
});
});
const base64Pdf = await pdfDoc.saveAsBase64({ dataUri: true });
return { base64Pdf };
// const pdfBytes = await pdfDoc.save();
// const path = await writePdf(pdfBytes);
// return { base64Pdf: `file://${path}` };
};