UNPKG

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.6 kB
/*! * For license information please see pdf-form-filler.node.min.js.LICENSE.txt */ (function(a,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("fs")):typeof define=="function"&&define.amd?define(["exports","fs"],c):(a=typeof globalThis<"u"?globalThis:a||self,c(a.PDFFormFiller={},a.fs))})(this,(function(a,c){"use strict";class F{constructor(e){this.map=e,this.res={}}mapDataRecursive(e,t){if(e!=null){if(typeof e!="object"){if(Array.isArray(t)){t.forEach(r=>{this.mapDataRecursive(e,r)});return}typeof t!="object"?this.res[t]=e:this.res[t[e].field]=t[e].value;return}if(Array.isArray(e)){e.forEach((r,s)=>{this.mapDataRecursive(r,Array.isArray(t)?t[s]:t)});return}Object.keys(e).forEach(r=>{this.mapDataRecursive(e[r],t[r])})}}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 r=new F(this.fieldMap).mapData(this.data);return await((e=this.pdfLibraryAdapter)===null||e===void 0?void 0:e.fillForm(this.pdfTemplate,r))}fromCharCode(e){const t=[];for(let s=0;s<e.length;s+=65535){const n=Array.prototype.slice.call(e,s,s+65535);t.push(String.fromCharCode.apply(null,n))}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 r=new Blob([t],{type:"application/pdf"});return e=="blob"?r:e=="bloburl"?URL.createObjectURL(r):t}async save(e="FilledForm.pdf"){const t=await this.getPDFBytes();t&&await this.saveToFile(t,e)}}class y extends m{async saveToFile(e,t){return new Promise((r,s)=>{c.writeFile(t,e,n=>{n?s(n):r()})})}}class D{constructor(e){this.pdfLibrary=e}async fillForm(e,t){const{PDFDocument:r,PDFTextField:s,PDFCheckBox:n,PDFRadioGroup:f,PDFDropdown:h}=this.pdfLibrary,d=await r.load(e);return d.getForm().getFields().forEach(i=>{const g=i.getName(),u=t[g];u!=null&&(i instanceof s?i.setText(u):i instanceof n?u?i.check():i.uncheck():(i instanceof f||i instanceof h)&&i.select(u.toString()))}),await d.save()}}class b{constructor(e){this.pdfLibrary=e}async fillForm(e,t){const s=await this.pdfLibrary.getDocument(e).promise,n=s.numPages;for(let f=1;f<=n;f++)(await(await s.getPage(f)).getAnnotations()).forEach(o=>{if(o.fieldType==null)return;const p=t[o.fieldName];if(p){if(o.radioButton&&o.buttonValue!=p)return;s.annotationStorage.setValue(o.id,{value:p})}});return await s.saveDocument()}}a.PDFFormFiller=y,a.PDFJSAdapter=b,a.PDFLibAdapter=D}));