I'm looking into using the pdf-lib library form manipulating pdf forms. The package is located here: [pdf-lib][1]
Edited the question to just include a code snippet that is at least partially working after getting the right script tag libraries. The snippet seems to run, and it uses a PDF form on a hosted server with CORS enabled.
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 eidted and completed.
The built-in PDF viewers for Chrome and Firefox do something similar in that you can print or download the form, but I'd like to also have the option of submitting the flattened edited form to the backend server as a PDF or base64 pdf with maybe a couple of other params so I would know here to put the data in the database.
If you run the snippet and open it in Full Page view you should be able to see the Print and Download buttons for the built-in PDF Viewers for FF and Chrome, as well as Flatten and Save Buttons that are sort of Placeholders for now.
I'd like to have the Flatten one just sort of collapse the fields so the data remains, but the form fields are no longer there or at least not editable, and the Save would do the same, but also allow submitting the form to the backend server.
This has been posted for awhile, but I just modified the snippet so there is basically a partially working example to work with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<meta name="generator" content="BBEdit 13.5" />
<!-- Adapated from https://github.com/Hopding/pdf-lib/issues/457 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://unpkg.com/pdf-lib@1.16.0/dist/pdf-lib.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@pdf-lib/fontkit/dist/fontkit.umd.min.js"></script>
<script src="https://unpkg.com//downloadjs@1.4.7/download.js"></script>
<style> .modal-dialog {
max-width:100%;
}
#flatten {
position: absolute;
top: 0;
right: 0;
left: 0;
margin: auto;
}
#saveform {
position: absolute;
top: 20px;
right: 0;
left: 0;
margin: auto;
}
</style>
</head>
<body>
<h5>
Use Browser to Print or Download
</h5>
<button class="uibuttonsmallred pdf-lib" id="flatten">Flatten</button>
<button class="uibuttonsmallred pdf-lib" id="saveform">Save</button>
<iframe style="display:none;border:0;margin:5px;padding:5px;" src="" id="pdf"></iframe>
<script nonce="cad403412f88ace1faf5b941e261ca60967120e831f5141bafbef78a1eacdf99">
var pdfDoc;
var pdfBytes;
var formfields;
// $("[src='https://unpkg.com/pdf-lib@1.16.0/dist/pdf-lib.min.js']").on("load", function(e) {
$(function() {
// e.preventDefault();
const { PDFDocument, PDFDocumentWriter, rgb } = PDFLib;
RenderData('https://sscotti.org/MRI_NOChecks.pdf', {"MRN":{"value":"MRN: CM0000002\nOrder: CMACC00000001\nName: Last, First\nDOB: 2001-01-01\nTime: Jul 04, 2021 12:00 PM","type":"text","font":8},"PatientName":{"value":"Last, First","type":"text"},"StudyDescription":{"value":"MRI BRAIN \/ BRAIN STEM - WITHOUT CONTRAST","type":"text","font":8},"PatientHeight":{"value":"","type":"text"},"PatientWeight":{"value":"","type":"text"},"PatientAdditionalHistory":{"value":"test","type":"text"},"PriorSurg":{"value":"None In Record","type":"text","font":8},"Priors":{"value":"","type":"text"},"Pacer":{"value":"1","type":"radio"},"CABG":{"value":"0","type":"radio"},"CNSClips":{"value":"0","type":"radio"},"EyeMetal":{"value":"0","type":"radio"},"Hearing":{"value":"0","type":"radio"},"BodyMetal":{"value":"0","type":"radio"},"BodyDevice":{"value":"0","type":"radio"},"Piercings":{"value":"0","type":"radio"},"Transdermal":{"value":"0","type":"radio"},"Panics":{"value":"0","type":"radio"},"Sedative":{"value":"0","type":"radio"},"NoDriving":{"value":"0","type":"radio"},"Pregnant":{"value":"0","type":"radio"},"BreastFeeding":{"value":"0","type":"radio"},"Allergies":{"value":"None In Record","type":"text"},"MRITech":{"value":"First Last","type":"text"},"ContrastHx":{"value":"0","type":"radio"},"Hypertension":{"value":"0","type":"radio"},"ContrastAllergy":{"value":"0","type":"radio"},"Diabetes":{"value":"0","type":"radio"},"TransplantHx":{"value":"0","type":"radio"},"Age":{"value":"63 yrs","type":"text"},"InjSite":{"value":"","type":"text"},"Dose":{"value":"","type":"text"},"CorrectPatient":{"value":"","type":"text"},"Sex":{"value":"M","type":"text"},"Lot":{"value":"","type":"text"},"CorrectSite":{"value":"","type":"text"},"ExpDate":{"value":"","type":"text"},"CorrectPosition":{"value":"","type":"text"},"PatientSig":{"value":"First Last","type":"text"},"PatientSigDate":{"value":"2021-07-17","type":"text"},"TechSig":{"value":"First Last","type":"text"},"TechSigDate":{"value":"2021-07-17","type":"text"}}, 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJEAAACRCAIAAABMus10AAAABnRSTlMA/wD/AP83WBt9AAAACXBIWXMAAA7EAAAOxAGVKw4bAAACe0lEQVR4nO3dQW6jMABA0clo7n/lzrISCyTLNvDJe9s2adCXFRew+fz8/Pwh5e/dH4BhmvVo1qNZj2Y9mvVo1qNZj2Y9mvVo1qNZj2Y9mvVo1qNZj2Y9mvVo1vNv5sWfz2fV5zh3ftPKzMc4vPNDjuiccdajWY9mPZr1TM1BDhbe3rpvWjH0IR9yRAfGWY9mPZr1aNazcg5yMPStu295zl3ziH1HZJz1aNajWY9mPRvnIPuczwXOf/qCtcjGWY9mPZr1aNaTnIMcDN3TMXNp5iGMsx7NejTr0axn4xzkIZdXFt51+pAJi3HWo1mPZj2a9aycg1y2qOSycxmXHdEQ46xHsx7NejTr+Tzkf/sZLzi1McQ469GsR7MezXo27g8y9PW+cMnJvs1EHnK3q3HWo1mPZj2a9dy2P8i+7/OZKzVDr124EckQ46xHsx7NejTr2XgtZuHNFEP3lS6cGpy/9q4lNsZZj2Y9mvVo1rPyWsxdW5Du+0P7LvrYq/27aNajWY9mPbetzZ05xXD+y0Mzo+KzZoyzHs16NOvRrCe5LmZo/nLushtPFl64Mc56NOvRrEeznvc/N3dmhjJzOsY9qfzSrEezHs16Xvjc3IVvNXOF6PytZhhnPZr1aNajWU/yubkzJyAWngcZemdzkK+mWY9mPZr1vP+ZdfvWxdy1ZZlx1qNZj2Y9mvW8YQ5yMLOx2MI/ZG0uvzTr0axHs57kc3Mv29h9yMLVOueMsx7NejTr0awn+dzcg4XbhRxcdllniHHWo1mPZj2a9ST3B/lyxlmPZj2a9WjWo1mPZj2a9WjWo1mPZj2a9WjWo1mPZj2a9WjWo1mPZj2a9fwH5Y0DFT4sERAAAAAASUVORK5CYII=' );
console.log( "ready!" );
async function RenderData(formurl, fields, QRCode) {
const formPdfBytes = await fetch(formurl, {
headers: {
'Content-Type': 'application/pdf',
'Origin': 'https://stackoverflow.com'
}
})
.then(res => res.arrayBuffer())
const PDFDocument = PDFLib.PDFDocument
// Load a PDFDocument from the existing PDF bytes
pdfDoc = await PDFDocument.load(formPdfBytes)
const url = 'https://pdf-lib.js.org/assets/ubuntu/Ubuntu-R.ttf'
const fontBytes = await fetch(url).then((res) => res.arrayBuffer())
pdfDoc.registerFontkit(fontkit)
const ubuntuFont = await pdfDoc.embedFont(fontBytes);
if (QRCode != '') {
const QRCodeEmbed = await pdfDoc.embedPng(QRCode)
const page = pdfDoc.getPage(0)
page.drawImage(QRCodeEmbed, {
width: 100,
height: 100,
y: 692,
x:280
})
console.log(page.getSize())
}
// Get the form containing all the fields
formfields = pdfDoc.getForm()
// Iterate through the form data and fill based on type.
// formfields.getTextField('QRCode').setText(QRCodeEmbed)
$.each(fields, function(fieldname, fielddata) {
console.log(fieldname);
console.log(fielddata);
switch(fielddata.type) {
case "text":
try {
formfields.getTextField(fieldname).setText(fielddata.value);
if (fielddata.font) {
formfields.getTextField(fieldname).setFontSize(fielddata.font);
}
else {
formfields.getTextField(fieldname).setFontSize(10);
}
}
catch(err) {
console.log(err.message);
}
break;
case "radio":
try {
let button = formfields.getRadioGroup(fieldname);
button.select(fielddata.value);
//console.log("set radio to " + fielddata.value);
}
catch(err) {
console.log(err.message);
}
break;
case "check":
try {
if (fielddata.value == "0") {
formfields.getCheckBox(fieldname).uncheck();
}
else formfields.getCheckBox(fieldname).check();
//console.log("set check to " + fielddata.value);
}
catch(err) {
console.log(err.message);
}
break;
default:
}
});
formfields.updateFieldAppearances(ubuntuFont);
pdfBytes = await pdfDoc.saveAsBase64({ dataUri: true })
document.getElementById('pdf').src = pdfBytes;
}
});
$("#flatten").on("click", function(e) {
async function Flatten() {
pdfDoc = await PDFLib.PDFDocument.load(document.getElementById('pdf').src)
form = pdfDoc.getForm()
form.updateFieldAppearances();
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) {
alert ("Use Print as PDF");
// download(document.getElementById('pdf').src, "pdf-lib_creation_example.pdf", "application/pdf");
});
</script>
</body>
</html>
from Trying to use pdf-lib to fill pdf form fields. Trouble Flattening and Saving Form
No comments:
Post a Comment