backend: fix PDFService.ts
This commit is contained in:
1 parent
db7446f19a
commit
954a54df68
1 file changed
+8
-25
@@ -198,33 +198,16 @@ export class PdfService {
|
|||||||
page.drawPage(timbradoEmbed, { x: 0, y: 0, width: page.getWidth(), height: page.getHeight() });
|
page.drawPage(timbradoEmbed, { x: 0, y: 0, width: page.getWidth(), height: page.getHeight() });
|
||||||
}
|
}
|
||||||
// Após mesclar o timbrado
|
// Após mesclar o timbrado
|
||||||
const pageCountBefore = pdfDoc.getPageCount();
|
let pageCountBefore = pdfDoc.getPageCount();
|
||||||
if (pageCountBefore > 1) {
|
// Remove páginas em branco no final do PDF
|
||||||
// Heurística aprimorada: remove a última página apenas se estiver realmente vazia (sem texto, imagens ou gráficos)
|
while (pageCountBefore > 1) {
|
||||||
const lastPage = pdfDoc.getPage(pageCountBefore - 1);
|
const lastPage = pdfDoc.getPage(pageCountBefore - 1);
|
||||||
let isBlank = true;
|
// Verifica se a página está realmente vazia (sem texto, imagens ou gráficos)
|
||||||
// Verifica se há texto
|
const operators = lastPage.getOperators ? lastPage.getOperators() : [];
|
||||||
const annotations = lastPage.node.Annots;
|
const isBlank = !operators || operators.length === 0;
|
||||||
if (annotations && annotations.length > 0) {
|
if (!isBlank) break;
|
||||||
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);
|
pdfDoc.removePage(pageCountBefore - 1);
|
||||||
}
|
pageCountBefore = pdfDoc.getPageCount();
|
||||||
}
|
}
|
||||||
const mergedPdf = await pdfDoc.save();
|
const mergedPdf = await pdfDoc.save();
|
||||||
return Buffer.from(mergedPdf);
|
return Buffer.from(mergedPdf);
|
||||||
|
|||||||
Reference in new issue
Block a user