Skip to content

Commit 7b33ae3

Browse files
committed
fix: added horizontal stretch (tz) for text overlay to match size
1 parent 09c3f51 commit 7b33ae3

1 file changed

Lines changed: 31 additions & 9 deletions

File tree

src/ocr-api/src/services/pdf.service.ts

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,18 @@
11
import { HttpException, Injectable, Logger } from '@nestjs/common';
22
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';
416
import * as fontkit from '@pdf-lib/fontkit';
517
import { Block } from '@aws-sdk/client-textract';
618
import { CfgService } from './cfg.service';
@@ -33,14 +45,24 @@ export class PdfService {
3345
} = b;
3446
const x = box.Left * width;
3547
const y = (1 - box.Top) * height - box.Height * height;
36-
page.drawText(word, {
48+
const size = box.Height * height;
49+
page.drawText('', {
3750
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+
);
4466
if (this.cfg.drawBoundingBox)
4567
page.drawRectangle({
4668
width: box.Width * width,
@@ -131,7 +153,7 @@ export class PdfService {
131153
}
132154

133155
async pdfToImageToPdf(buffer: Buffer): Promise<Buffer> {
134-
const images = await pdfToPng(buffer, {
156+
const images = await pdfToPng(buffer as any, {
135157
viewportScale: this.cfg.pngQuality,
136158
});
137159
const oldPdf = await PDFDocument.load(buffer);

0 commit comments

Comments
 (0)