使用 pdf-lib 在 NodeJS 中检测 PDF 中的空白页

Detect blank page in PDF in NodeJS using pdf-lib

提问人:Axel Carré 提问时间:7/10/2023 最后编辑:Axel Carré 更新时间:7/12/2023 访问量:236

问:

我花了一天时间试图在我的 NodeJS 服务器上找到一种方法来检测生成的 pdf 的最后一页何时为空白(将其删除)。我似乎找不到一种方法。一路上我尝试使用许多其他人,但没有成功。目前,我正在运行以下函数:pdf-lib

const docx_buffers_to_pdf_buffer = async (docx_buffers) => {
    const combined_pdf_buffer = await PDFDocument.create()
    for(const docx_buffer of docx_buffers){
        const pdf_buffer = await PDFDocument.load(await libre_convert(docx_buffer, "pdf", undefined))
        const pages = await combined_pdf_buffer.copyPages(pdf_buffer, pdf_buffer.getPageIndices())
        const n = Math.max(1, pages.length - 1)
        for(let page_index = 0; page_index < n; page_index++){
            combined_pdf_buffer.addPage(pages[page_index])
        }
        if(pages.length > 1){
            let temp_pdf_buffer = await PDFDocument.create()
            const temp_page = (await temp_pdf_buffer.copyPages(pdf_buffer, [pages.length - 1]))[0]
            temp_pdf_buffer.addPage(temp_page)
            temp_pdf_buffer = await temp_pdf_buffer.save()
            if(await page_is_not_empty(temp_pdf_buffer)){
                combined_pdf_buffer.addPage(pages[pages.length - 1])
            }
        }
    }
    return await combined_pdf_buffer.save()
}

逻辑工作正常,pdf文档已正确生成,但我不知道如何编写函数,现在它只是返回true以包含最后一页。page_is_not_empty

我的想法是将最后一页转换为图像并手动检查它是否为空,如果不是,则返回 true,以便不将该页面包含在最终文档中。

我的想法快用完了,我不知道检查空白页会这么难,或者我错过了关键点......

我什至试图深入研究,但没有成功,或者(最后一个包含一个空数组,无论页面是否真的是空的,这让我感到非常困惑)。page.nodeevenpage.getContentStream().operators

更奇怪的是,该文档似乎不是最新的,因为我能够使用,而那里甚至没有引用此功能......getContentStream()

node.js 是空 的 pdf-lib.js

评论


答: 暂无答案