backend: fix PDFService.ts
This commit is contained in:
1 parent
db7446f19a
commit
8f6b708d51
4 files changed
+178
-953
No files matched your search
@@ -198,32 +198,27 @@ 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 (heurística baseada no tamanho do conteúdo)
|
||||
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) {
|
||||
const contentStreams = (lastPage as any).node.Contents();
|
||||
// Se não houver conteúdo, é uma página em branco
|
||||
if (!contentStreams || contentStreams.length === 0) {
|
||||
pdfDoc.removePage(pageCountBefore - 1);
|
||||
pageCountBefore = pdfDoc.getPageCount();
|
||||
continue;
|
||||
}
|
||||
// Soma o tamanho dos streams de conteúdo
|
||||
const totalLength = contentStreams
|
||||
.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);
|
||||
pageCountBefore = pdfDoc.getPageCount();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
const mergedPdf = await pdfDoc.save();
|
||||
|
||||
Reference in new issue
Block a user