backend: fix PDFService.ts

This commit is contained in:
Rodrigo B. de Sousa Martins committed 2025-06-11 11:40:02 -03:00
1 parent db7446f19a
commit 954a54df68
1 file changed
+9 -26
+9 -26
View File
@@ -198,33 +198,16 @@ export class PdfService {
page.drawPage(timbradoEmbed, { x: 0, y: 0, width: page.getWidth(), height: page.getHeight() });
}
// Após mesclar o timbrado
const pageCountBefore = pdfDoc.getPageCount();
if (pageCountBefore > 1) {
// Heurística aprimorada: remove a última página apenas se estiver realmente vazia (sem texto, imagens ou gráficos)
let pageCountBefore = pdfDoc.getPageCount();
// Remove páginas em branco no final do PDF
while (pageCountBefore > 1) {
const lastPage = pdfDoc.getPage(pageCountBefore - 1);
let isBlank = true;
// Verifica se há texto
const annotations = lastPage.node.Annots;
if (annotations && annotations.length > 0) {
isBlank = false;
}
// Verifica se há objetos gráficos (imagens, paths, etc.)
if (isBlank && typeof lastPage.node?.Resources === 'function') {
const resourcesDict = lastPage.node.Resources();
if (resourcesDict && typeof resourcesDict === 'object') {
// Corrige: usa PDFName para acessar o XObject
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { PDFName } = require('pdf-lib');
const xObject = resourcesDict.get(PDFName.of('XObject'));
if (xObject && typeof xObject === 'object' && Object.keys(xObject).length > 0) {
isBlank = false;
}
}
}
// Só remove se realmente não houver nada
if (isBlank) {
pdfDoc.removePage(pageCountBefore - 1);
}
// Verifica se a página está realmente vazia (sem texto, imagens ou gráficos)
const operators = lastPage.getOperators ? lastPage.getOperators() : [];
const isBlank = !operators || operators.length === 0;
if (!isBlank) break;
pdfDoc.removePage(pageCountBefore - 1);
pageCountBefore = pdfDoc.getPageCount();
}
const mergedPdf = await pdfDoc.save();
return Buffer.from(mergedPdf);