backend: fix PDFService.ts
This commit is contained in:
1 parent
8f6b708d51
commit
0fef046d38
1 file changed
+18
-17
@@ -199,26 +199,27 @@ export class PdfService {
|
|||||||
}
|
}
|
||||||
// Após mesclar o timbrado
|
// Após mesclar o timbrado
|
||||||
let pageCountBefore = pdfDoc.getPageCount();
|
let pageCountBefore = pdfDoc.getPageCount();
|
||||||
// Remove páginas em branco no final do PDF (heurística baseada no tamanho do conteúdo)
|
// Remove apenas a ÚLTIMA página se ela estiver realmente vazia (sem conteúdo)
|
||||||
while (pageCountBefore > 1) {
|
if (pageCountBefore > 1) {
|
||||||
const lastPage = pdfDoc.getPage(pageCountBefore - 1);
|
const lastPage = pdfDoc.getPage(pageCountBefore - 1);
|
||||||
const contentStreams = (lastPage as any).node.Contents();
|
const contentStreams = (lastPage as any).node.Contents?.();
|
||||||
// Se não houver conteúdo, é uma página em branco
|
let isBlank = false;
|
||||||
if (!contentStreams || contentStreams.length === 0) {
|
|
||||||
pdfDoc.removePage(pageCountBefore - 1);
|
if (!contentStreams) {
|
||||||
pageCountBefore = pdfDoc.getPageCount();
|
isBlank = true;
|
||||||
continue;
|
} else if (Array.isArray(contentStreams)) {
|
||||||
|
// Se todos os streams são vazios ou muito pequenos
|
||||||
|
isBlank = contentStreams.every(
|
||||||
|
(stream: any) =>
|
||||||
|
!stream.contents ||
|
||||||
|
(typeof stream.contents.length === 'number' && stream.contents.length < 5)
|
||||||
|
);
|
||||||
|
} else if (contentStreams.contents && typeof contentStreams.contents.length === 'number') {
|
||||||
|
isBlank = contentStreams.contents.length < 5;
|
||||||
}
|
}
|
||||||
// Soma o tamanho dos streams de conteúdo
|
|
||||||
const totalLength = contentStreams
|
if (isBlank) {
|
||||||
.map((stream: any) => stream.contents.length)
|
|
||||||
.reduce((acc: number, len: number) => acc + len, 0);
|
|
||||||
// Se o conteúdo for muito pequeno (< 30 bytes), considera em branco
|
|
||||||
if (totalLength < 30) {
|
|
||||||
pdfDoc.removePage(pageCountBefore - 1);
|
pdfDoc.removePage(pageCountBefore - 1);
|
||||||
pageCountBefore = pdfDoc.getPageCount();
|
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const mergedPdf = await pdfDoc.save();
|
const mergedPdf = await pdfDoc.save();
|
||||||
|
|||||||
Reference in new issue
Block a user