Trying to use pdf-lib to fill pdf form fields. Trouble Flattening and Saving Form

2.8k Views Asked by At

I'm looking into using the pdf-lib library form manipulating pdf forms. The package is located here: https://github.com/Hopding/pdf-lib

Edited the question yet again (it has been here for months and no takers on 2 bounties for 100) to just include a code snippet that is at least partially working after getting the right script tag libraries.

The issue I am having is that I want to be able to Flatten and Save the form after any online editing after the pre-populated form is edited and completed.

Here is a bit of a sample from what I have posted as an issue on Github in the pdf-lib repo here https://github.com/Hopding/pdf-lib/issues/965

$("#flatten").on("click", function(e) {

async function Flatten() {

 pdfDoc = await PDFLib.PDFDocument.load(document.getElementById('pdf').src)
 form = pdfDoc.getForm()
 form.updateFieldAppearances();
  checkboxes.forEach(function (item, index) {
    checkBox = form.getCheckBox(item);
    checkBox.defaultUpdateAppearances()
  });
 form.flatten()
 pdfBytes = await pdfDoc.saveAsBase64({ dataUri: true })
 document.getElementById('pdf').src = pdfBytes
}

Flatten();
});
    
    
$("#pdf").on("load", function(e) {
  autoResize($(this));
});
    
function autoResize(iframe) {
    
  // iframe.height($(iframe).contents().find('html').height());
  iframe.height("1650px");
  iframe.width("1275px");
  iframe.show();
}
    
        
$("#saveform").on("click", function(e) {
    download(document.getElementById('pdf').src, SaveAs+'.pdf', "application/pdf");
});

$("#sendform").on("click", function(e) {
    alert(document.getElementById('pdf').src);
    //download(document.getElementById('pdf').src, SaveAs+'.pdf', "application/pdf");
});

There is an archive.zip attached to the GitHub issue post. If you are interested, I suggest you put the two files there on a server to see what the issue is. It is setup to just work if you put the test.html file and the PDF on a webserver in the same directory (root of server) and then just open it up in a browser. If you type something into a field and then try to Flatten you'll be asked to stay on page or leave. That is what I want to try to fix.

0

There are 0 best solutions below