survey-pdf
Version:
Renders JSON-driven SurveyJS forms and their responses as PDF documents in the browser or Node.js: fillable interactive PDF forms (AcroForm) or static printouts.
6 lines (4 loc) • 2.72 kB
JavaScript
/*!
* For license information please see pdf-form-filler.min.js.LICENSE.txt
*/
(function(s,o){typeof exports=="object"&&typeof module<"u"?o(exports):typeof define=="function"&&define.amd?define(["exports"],o):(s=typeof globalThis<"u"?globalThis:s||self,o(s.PDFFormFiller={}))})(this,(function(s){"use strict";class o{constructor(e){this.map=e,this.res={}}mapDataRecursive(e,t){if(e!=null){if(typeof e!="object"){if(Array.isArray(t)){t.forEach(i=>{this.mapDataRecursive(e,i)});return}typeof t!="object"?this.res[t]=e:this.res[t[e].field]=t[e].value;return}if(Array.isArray(e)){e.forEach((i,r)=>{this.mapDataRecursive(i,Array.isArray(t)?t[r]:t)});return}Object.keys(e).forEach(i=>{this.mapDataRecursive(e[i],t[i])})}}mapData(e){return this.res={},this.mapDataRecursive(e,this.map),this.res}}class m{constructor(e){e&&(this.data=e.data,this.fieldMap=e.fieldMap,this.pdfTemplate=e.pdfTemplate,this.pdfLibraryAdapter=e.pdfLibraryAdapter)}async getPDFBytes(){var e;const i=new o(this.fieldMap).mapData(this.data);return await((e=this.pdfLibraryAdapter)===null||e===void 0?void 0:e.fillForm(this.pdfTemplate,i))}fromCharCode(e){const t=[];for(let r=0;r<e.length;r+=65535){const c=Array.prototype.slice.call(e,r,r+65535);t.push(String.fromCharCode.apply(null,c))}return t.join("")}async raw(e){const t=await this.getPDFBytes();if(!e||!t)return t;if(e=="dataurlstring")return"data:application/pdf;base64,"+btoa(this.fromCharCode(t));const i=new Blob([t],{type:"application/pdf"});return e=="blob"?i:e=="bloburl"?URL.createObjectURL(i):t}async save(e="FilledForm.pdf"){const t=await this.getPDFBytes();t&&await this.saveToFile(t,e)}}class F extends m{async saveToFile(e,t){const i=new Blob([e],{type:"application/pdf"}),r=document.createElement("a");r.href=URL.createObjectURL(i),r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(r.href)}}class b{constructor(e){this.pdfLibrary=e}async fillForm(e,t){const{PDFDocument:i,PDFTextField:r,PDFCheckBox:c,PDFRadioGroup:f,PDFDropdown:h}=this.pdfLibrary,p=await i.load(e);return p.getForm().getFields().forEach(a=>{const D=a.getName(),l=t[D];l!=null&&(a instanceof r?a.setText(l):a instanceof c?l?a.check():a.uncheck():(a instanceof f||a instanceof h)&&a.select(l.toString()))}),await p.save()}}class y{constructor(e){this.pdfLibrary=e}async fillForm(e,t){const r=await this.pdfLibrary.getDocument(e).promise,c=r.numPages;for(let f=1;f<=c;f++)(await(await r.getPage(f)).getAnnotations()).forEach(n=>{if(n.fieldType==null)return;const d=t[n.fieldName];if(d){if(n.radioButton&&n.buttonValue!=d)return;r.annotationStorage.setValue(n.id,{value:d})}});return await r.saveDocument()}}s.PDFFormFiller=F,s.PDFJSAdapter=y,s.PDFLibAdapter=b}));