|
1 |
| -import fontkit from '@pdf-lib/fontkit'; |
2 | 1 | import fs from 'fs';
|
3 |
| -import { PDFDocument, rgb } from 'src/index'; |
| 2 | +import { PDFDocument } from 'src/index'; |
4 | 3 |
|
5 | 4 | (async () => {
|
6 |
| - // This should be a Uint8Array. |
| 5 | + // These should be a Uint8Arrays. |
7 | 6 | // This data can be obtained in a number of different ways.
|
8 | 7 | // If your running in a Node environment, you could use fs.readFile().
|
9 | 8 | // In the browser, you could make a fetch() call and use res.arrayBuffer().
|
10 |
| - const fontBytes = fs.readFileSync('assets/fonts/ubuntu/Ubuntu-R.ttf'); |
| 9 | + const jpgImageBytes = fs.readFileSync('assets/images/cat_riding_unicorn.jpg'); |
| 10 | + const pngImageBytes = fs.readFileSync( |
| 11 | + 'assets/images/minions_banana_alpha.png', |
| 12 | + ); |
11 | 13 |
|
12 | 14 | const pdfDoc = await PDFDocument.create();
|
13 | 15 |
|
14 |
| - pdfDoc.registerFontkit(fontkit); |
| 16 | + const jpgImage = await pdfDoc.embedJpg(jpgImageBytes); |
| 17 | + const pngImage = await pdfDoc.embedPng(pngImageBytes); |
15 | 18 |
|
16 |
| - const customFont = await pdfDoc.embedFont(fontBytes); |
| 19 | + const jpgDims = jpgImage.scale(0.25); |
| 20 | + const pngDims = pngImage.scale(0.5); |
17 | 21 |
|
18 | 22 | const page = pdfDoc.addPage();
|
19 | 23 |
|
20 |
| - const text = 'This is text in an embedded font!'; |
21 |
| - const textSize = 35; |
22 |
| - const textWidth = customFont.widthOfTextAtSize(text, textSize); |
23 |
| - const textHeight = customFont.heightAtSize(textSize); |
24 |
| - |
25 |
| - // Draw text on page |
26 |
| - page.drawText(text, { |
27 |
| - x: 40, |
28 |
| - y: 450, |
29 |
| - size: textSize, |
30 |
| - font: customFont, |
31 |
| - color: rgb(0, 0.53, 0.71), |
| 24 | + page.drawImage(jpgImage, { |
| 25 | + x: page.getWidth() / 2 - jpgDims.width / 2, |
| 26 | + y: page.getHeight() / 2 - jpgDims.height / 2, |
| 27 | + width: jpgDims.width, |
| 28 | + height: jpgDims.height, |
32 | 29 | });
|
33 | 30 |
|
34 |
| - // Draw a box around the text |
35 |
| - page.drawRectangle({ |
36 |
| - x: 40, |
37 |
| - y: 450, |
38 |
| - width: textWidth, |
39 |
| - height: textHeight, |
40 |
| - borderColor: rgb(1, 0, 0), |
41 |
| - borderWidth: 1.5, |
| 31 | + page.drawImage(pngImage, { |
| 32 | + x: page.getWidth() / 2 - pngDims.width / 2 + 75, |
| 33 | + y: page.getHeight() / 2 - pngDims.height, |
| 34 | + width: pngDims.width, |
| 35 | + height: pngDims.height, |
42 | 36 | });
|
43 | 37 |
|
44 | 38 | const pdfBytes = await pdfDoc.save();
|
|
0 commit comments