|
1 | 1 | import { HttpException, Injectable, Logger } from '@nestjs/common'; |
2 | 2 | import { readFileSync } from 'fs'; |
3 | | -import { PDFDocument, rgb } from 'pdf-lib'; |
| 3 | +import { |
| 4 | + beginText, |
| 5 | + endText, |
| 6 | + PDFDocument, |
| 7 | + PDFOperator, |
| 8 | + popGraphicsState, |
| 9 | + pushGraphicsState, |
| 10 | + rgb, |
| 11 | + setFontAndSize, |
| 12 | + setTextMatrix, |
| 13 | + setTextRenderingMode, |
| 14 | + showText, |
| 15 | +} from 'pdf-lib'; |
4 | 16 | import * as fontkit from '@pdf-lib/fontkit'; |
5 | 17 | import { Block } from '@aws-sdk/client-textract'; |
6 | 18 | import { CfgService } from './cfg.service'; |
@@ -33,14 +45,24 @@ export class PdfService { |
33 | 45 | } = b; |
34 | 46 | const x = box.Left * width; |
35 | 47 | const y = (1 - box.Top) * height - box.Height * height; |
36 | | - page.drawText(word, { |
| 48 | + const size = box.Height * height; |
| 49 | + page.drawText('', { |
37 | 50 | x, |
38 | | - y, |
39 | | - size: box.Height * height, |
40 | | - font, |
41 | | - color: rgb(0, 0, 0), |
42 | | - opacity: 0, |
43 | | - }); |
| 51 | + }); // Ensure content stream exists |
| 52 | + const defaultWidth = font.widthOfTextAtSize(word || '', size); |
| 53 | + const scale = (box.Width * width) / defaultWidth; |
| 54 | + const { newFontKey } = (page as any).setOrEmbedFont(font); // Accessing private method |
| 55 | + page.pushOperators( |
| 56 | + pushGraphicsState(), |
| 57 | + beginText(), |
| 58 | + setTextRenderingMode(3), |
| 59 | + setFontAndSize(newFontKey, size), |
| 60 | + PDFOperator.of('Tz' as any, [(scale * 100).toFixed(2).toString()]), |
| 61 | + setTextMatrix(1, 0, 0, 1, x, y), |
| 62 | + showText(font.encodeText(word || '')), |
| 63 | + endText(), |
| 64 | + popGraphicsState(), |
| 65 | + ); |
44 | 66 | if (this.cfg.drawBoundingBox) |
45 | 67 | page.drawRectangle({ |
46 | 68 | width: box.Width * width, |
@@ -131,7 +153,7 @@ export class PdfService { |
131 | 153 | } |
132 | 154 |
|
133 | 155 | async pdfToImageToPdf(buffer: Buffer): Promise<Buffer> { |
134 | | - const images = await pdfToPng(buffer, { |
| 156 | + const images = await pdfToPng(buffer as any, { |
135 | 157 | viewportScale: this.cfg.pngQuality, |
136 | 158 | }); |
137 | 159 | const oldPdf = await PDFDocument.load(buffer); |
|
0 commit comments