【问题标题】:Issue while flattening PDF using PDF-lib in JavaScript在 JavaScript 中使用 PDF-lib 展平 PDF 时出现问题
【发布时间】:2021-01-03 03:41:10
【问题描述】:

我使用 PDF-lib (https://www.npmjs.com/package/pdf-lib) 成功创建了一个可填写的表单。

但是我在展平它时遇到了以下错误。

未处理的拒绝(错误):找不到元素 mahesh_Signature_0 的未定义页面

这里 mahesh_Signature_0 是一个文本字段名称。

这是我将其展平的简单代码。

const formPdfBytes = await fetch(file).then(res => res.arrayBuffer())
const pdfDoc = await PDFDocument.load(formPdfBytes)
const form = pdfDoc.getForm()
form.flatten()

我该如何解决这个问题?在 JavaScript 中扁平化 PDF 注释的任何替代解决方案?

【问题讨论】:

    标签: javascript pdf.js pdf-annotations


    【解决方案1】:
    const someVar = await form.save();
    then download, view from the array
    
    My guess from snippet of code seen.
    
    import { PDFDocument } from 'pdf-lib'
    
    // This should be a Uint8Array or ArrayBuffer
    // This data can be obtained in a number of different ways
    // If your running in a Node environment, you could use fs.readFile()
    // In the browser, you could make a fetch() call and use res.arrayBuffer()
    const formPdfBytes = ...
    
    // Load a PDF with form fields
    const pdfDoc = await PDFDocument.load(formPdfBytes)
    
    // Get the form containing all the fields
    const form = pdfDoc.getForm()
    
    // Fill the form's fields
    form.getTextField('Text1').setText('Some Text');
    
    form.getRadioGroup('Group2').select('Choice1');
    form.getRadioGroup('Group3').select('Choice3');
    form.getRadioGroup('Group4').select('Choice1');
    
    form.getCheckBox('Check Box3').check();
    form.getCheckBox('Check Box4').uncheck();
    
    form.getDropdown('Dropdown7').select('Infinity');
    
    form.getOptionList('List Box6').select('Honda');
    
    // Flatten the form's fields
    form.flatten();
    
    // Serialize the PDFDocument to bytes (a Uint8Array)
    const pdfBytes = await pdfDoc.save()
    

    【讨论】:

    • 您不应该只是复制粘贴代码,还应该回答为什么您提出的解决方案能够解决问题中暴露的问题。
    • 如果 getform 没有定义怎么办?
    猜你喜欢
    • 2019-03-19
    • 2010-12-05
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多