Create PDF Forms in Node.js
PDF Generator for SurveyJS allows you to generate interactive PDF forms on a Node.js server. This tutorial describes how to configure PDF form creation in a Node.js application.
- Install the
survey-pdf
npm package - Configure Export Properties
- Populate the PDF Form with Data
- Export the PDF Form
Install the survey-pdf
npm package
PDF Generator for SurveyJS is built upon the jsPDF library and is distributed as a survey-pdf
npm package. Run the following command to install the package and its dependencies, including jsPDF:
npm install survey-pdf --save
If your survey contains HTML or Signature Pad questions, install the jsdom
package to create a simulated web environment in a Node.js application. Create a JSDOM instance and reference the window
and document
objects from the JSDOM instance in a global scope:
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const SurveyPDF = require("survey-pdf");
const { window } = new JSDOM(`...`);
global.window = window;
global.document = window.document;
Configure Export Properties
Export properties allow you to customize the page format, orientation, margins, font, and other parameters. Refer to the IDocOptions
interface for a full list of properties. The following code changes the fontSize
property:
const pdfDocOptions = {
fontSize: 12
};
Pass the object with export properties as a second parameter to the SurveyPDF
constructor. The first parameter should be a survey JSON schema:
// ...
const surveyJson = { ... };
const surveyPdf = new SurveyPDF.SurveyPDF(surveyJson, pdfDocOptions);
Populate the PDF Form with Data
Specify the data
property of a SurveyPDF
instance to define question answers. If a survey contains default values, and you wish to preserve them, call the mergeData(newObj)
method instead.
surveyPdf.data = {
// ...
// An object with question answers
// ...
};
// ----- or -----
surveyPdf.mergeData({
// ...
// An object with question answers
// ...
});
For more information on how to programmatically define question answers, refer to the following help topic: Populate Form Fields.
Export the PDF Form
To save a PDF document with the exported survey, call the save(fileName)
method on the SurveyPDF
instance. If you omit the fileName
parameter, the document uses the default name ("survey_result.pdf"
).
surveyPdf.save("My PDF Form.pdf");