### Run test examples
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/readme.md
Command to start a local HTTP server for running examples, accessible at http://localhost:7777/.
```bash
npm start
```
--------------------------------
### Run local examples with npm run serve
Source: https://github.com/surveyjs/survey-pdf/blob/master/README.md
Serve the package directory at http://localhost:7777/. The examples load bundles from build, so run npm run build:all first; npm start only rebuilds the main bundle, leaving form-filler examples without build/pdf-form-filler.js.
```sh
npm run serve
```
--------------------------------
### Install and import pdf-lib
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/fill-pdf-form-with-web-form-responses.md
Install the pdf-lib npm package and import the entire module for modular applications.
```sh
npm install pdf-lib
```
```js
import * as PDFLib from "pdf-lib";
```
--------------------------------
### Install and import PDF.js
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/fill-pdf-form-with-web-form-responses.md
Install the pdfjs-dist npm package, import the module, and set the worker source for modular applications.
```sh
npm install pdfjs-dist
```
```js
import * as pdfjsLib from "pdfjs-dist";
if (!pdfjsLib.GlobalWorkerOptions.workerSrc) {
pdfjsLib.GlobalWorkerOptions.workerSrc = "https://unpkg.com/pdfjs-dist@5.1.91/build/pdf.worker.min.mjs";
}
```
--------------------------------
### Install survey-pdf with npm
Source: https://github.com/surveyjs/survey-pdf/blob/master/README.md
Installs the survey-pdf package, which also runs in Node.js for server-side PDF generation.
```sh
npm install survey-pdf
```
--------------------------------
### Install dependencies with npm install
Source: https://github.com/surveyjs/survey-pdf/blob/master/README.md
Install project dependencies. The survey-pdf package depends on survey-core; the dependencies entry in package.json points to a local survey-library checkout, so build survey-core first or replace that entry with a published version before running this command.
```sh
npm install
```
--------------------------------
### Switch to Compact layout in modular application
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/pdf-appearance-customization.md
Imports the Compact and Spacious layouts and applies the currently selected layout with the applyLayout method. This example shows applying the Compact layout.
```javascript
// Modular applications
import { Compact, Spacious } from "survey-pdf/layouts";
// ...
surveyPdf.applyLayout(Compact);
surveyPdf.save();
```
--------------------------------
### Initialize PDFFormFiller
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/ipdfformfilleroptions.md
Pass the configuration object to the PDFFormFiller constructor. The example shows both standard and modular import usage.
```js
const form = new PDFFormFiller.PDFFormFiller(pdfFormFillerOptions);
// In modular applications:
import { PDFFormFiller } from "survey-pdf/pdf-form-filler";
const form = new PDFFormFiller(pdfFormFillerOptions);
```
--------------------------------
### Full React PDF Export Implementation
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/get-started-react.md
A complete example showing the survey model definition, PDF export logic using Monochrome Light theme, and the React component integration.
```js
// components/Survey.tsx
'use client'
import 'survey-core/survey-core.css';
import { Model } from 'survey-core';
import { Survey } from 'survey-react-ui';
import { IDocOptions, SurveyPDF } from 'survey-pdf';
import { MonochromeLight } from "survey-core/themes";
const surveyJson = {
"title": "NPS Survey Question",
"description": "NPS (net promoter score) is a metric used to evaluate customer loyalty and business growth opportunities. To measure NPS, respondents should rate on a scale of 0 to 10 how likely they would recommend your product or service to a friend or colleague.",
"pages": [
{
"name": "page1",
"elements": [
{
"type": "rating",
"name": "nps-score",
"title": "On a scale from 0 to 10, how likely are you to recommend us to a friend or colleague?",
"rateMin": 0,
"rateMax": 10
},
{
"type": "comment",
"name": "disappointing-experience",
"title": "If your score is 0 to 5, how did we disappoint you and what can we do to improve?",
"maxLength": 300
},
{
"type": "comment",
"name": "improvements-required",
"title": "If your score is 6 or higher, what can we do to improve your experience?",
"maxLength": 300
},
{
"type": "checkbox",
"name": "promoter-features",
"title": "If your score is 9 or 10, which features do you value most?",
"description": "Select up to three features, if applicable.",
"choices": [
{
"value": "performance",
"text": "Performance"
},
{
"value": "stability",
"text": "Stability"
},
{
"value": "ui",
"text": "User interface"
},
{
"value": "complete-functionality",
"text": "Complete functionality"
},
{
"value": "learning-materials",
"text": "Learning materials"
},
{
"value": "support",
"text": "Support quality"
}
],
"showOtherItem": true,
"otherText": "Other",
"colCount": 2,
"maxSelectedChoices": 3
}
]
},
{
"name": "page2",
"elements": [
{
"type": "boolean",
"name": "rebuy",
"title": "Would you buy our product again?"
}
]
},
{
"name": "page3",
"elements": [
{
"type": "boolean",
"name": "testimonial",
"title": "Would you be willing to provide a short testimonial?"
},
{
"type": "text",
"name": "email",
"title": "If yes, enter your email address",
"inputType": "email"
}
]
}
],
"questionsOnPageMode": "singlePage",
"headerView": "advanced"
};
const pdfDocOptions: IDocOptions = { };
const savePdf = (surveyData: any) => {
const surveyPdf = new SurveyPDF(surveyJson, pdfDocOptions);
surveyPdf.data = surveyData;
surveyPdf.applyTheme(MonochromeLight);
surveyPdf.save();
};
export default function SurveyComponent() {
const survey = new Model(surveyJson);
survey.addNavigationItem({
id: "pdf-export",
title: "Save as PDF",
action: () => savePdf(survey.data)
});
return (
);
}
```
```js
// survey/page.tsx
import dynamic from 'next/dynamic';
const SurveyComponent = dynamic(() => import("@/components/Survey"), {
ssr: false
});
export default function Survey() {
return (
);
}
```
--------------------------------
### Configure JSDOM for Node.js
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/get-started-nodejs.md
If your survey includes HTML or Signature Pad questions, install jsdom and configure the global window and document objects as shown.
```js
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const SurveyPDF = require("survey-pdf");
const { window } = new JSDOM(`...`);
global.window = window;
global.document = window.document;
```
--------------------------------
### save()
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/surveypdf.md
An asynchronous method that starts to download the generated PDF file in the web browser.
```APIDOC
## save()
### Description
An asynchronous method that starts to download the generated PDF file in the web browser.
### Method
save()
### Parameters
- **fileName** (string) - Optional - A file name with the ".pdf" extension. Default value: "survey_result.pdf".
### Return Value
Promise
```
--------------------------------
### Configure PDFFormFiller with pdfLibraryAdapter, pdfTemplate, data, and fieldMap
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/fill-pdf-form-with-web-form-responses.md
Create a PDFFormFiller instance with a configuration object. The example shows both PDFLibAdapter and PDFJSAdapter options, but only one should be used at a time. The pdfTemplate is a Base64 data URL, data contains survey answers, and fieldMap maps survey fields to PDF form field IDs.
```js
// ...
const pdfTemplate = "data:application/pdf;base64,...";
const data = {
"employer": "ABC Technologies",
"position": "Software Developer",
"name": "Doe, Jane Marie",
// ...
}
const fieldMap = {
"employer": "Employer",
"position": "Position",
"name": "Candidate Name",
// ...
}
const form = new PDFFormFiller({
pdfLibraryAdapter: new PDFLibAdapter(PDFLib), // For pdf-lib
pdfLibraryAdapter: new PDFJSAdapter(pdfjsLib), // For PDF.js
pdfTemplate: pdfTemplate,
data: data,
fieldMap: fieldMap
});
```
--------------------------------
### raw()
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/surveypdf.md
An asynchronous method that allows you to get PDF content in different formats.
```APIDOC
## raw()
### Description
An asynchronous method that allows you to get PDF content in different formats.
### Method
raw()
### Return Value
Promise | Promise | Promise | Promise | Promise
```
--------------------------------
### Import PDFFormFiller from survey-pdf/pdf-form-filler
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/fill-pdf-form-with-web-form-responses.md
Import the PDFFormFiller class from the survey-pdf/pdf-form-filler module after installing the package.
```js
import { PDFFormFiller } from "survey-pdf/pdf-form-filler";
```
--------------------------------
### Full Vue 3 PDF Export Implementation
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/get-started-vue.md
A complete example showing how to define a survey model, configure a PDF export action using the Monochrome Light theme, and render the survey in a Vue 3 component.
```html
```
--------------------------------
### Padding property examples
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/icontainerstyle.md
Shows the different ways to specify the padding property: a single number for uniform padding, or arrays for individual sides (top/bottom, left/right, etc.).
```javascript
// all four sides
padding: 12,
// top and bottom | left and right
padding: [12, 24],
// top | left and right | bottom
padding: [12, 6, 24],
// top | right | bottom | left
padding: [12, 12, 24, 24]
```
--------------------------------
### Add a Base64-encoded logo to a PDF form
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/add-header-and-footer-to-pdf-form.md
This example demonstrates how to configure the logo and its position within the survey JSON schema and initialize the SurveyPDF instance.
```js
const surveyJson = {
"logo": "data:image/png;base64,...",
"logoPosition": "right"
};
const pdfDocOptions = { ... };
const surveyPdf = new SurveyPDF.SurveyPDF(surveyJson, pdfDocOptions);
// In modular applications:
import { SurveyPDF } from "survey-pdf";
const surveyPdf = new SurveyPDF(surveyJson, pdfDocOptions);
```
--------------------------------
### Configure Global Matrix Rendering as List
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/customize-survey-question-rendering-in-pdf-form.md
Set the matrixRenderAs property to 'list' in the pdfDocOptions object to force all matrix questions to render as lists. The example includes both standard and modular import usage.
```js
const pdfDocOptions = {
matrixRenderAs: "list"
};
const surveyPdf = new SurveyPDF.SurveyPDF(surveyJson, pdfDocOptions);
// In modular applications:
import { SurveyPDF } from "survey-pdf";
const surveyPdf = new SurveyPDF(surveyJson, pdfDocOptions);
```
--------------------------------
### Export Survey to PDF in Angular
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/get-started-angular.md
A complete example showing the HTML template and TypeScript component logic required to add a 'Save as PDF' button to an Angular survey component.
```html
```
```js
// app.component.ts
import { Component, OnInit } from '@angular/core';
import { Model } from "survey-core";
import { SurveyPDF, IDocOptions } from "survey-pdf";
import { MonochromeLight } from "survey-core/themes";
const surveyJson = {
"title": "NPS Survey Question",
"description": "NPS (net promoter score) is a metric used to evaluate customer loyalty and business growth opportunities. To measure NPS, respondents should rate on a scale of 0 to 10 how likely they would recommend your product or service to a friend or colleague.",
"pages": [
{
"name": "page1",
"elements": [
{
"type": "rating",
"name": "nps-score",
"title": "On a scale from 0 to 10, how likely are you to recommend us to a friend or colleague?",
"rateMin": 0,
"rateMax": 10
},
{
"type": "comment",
"name": "disappointing-experience",
"title": "If your score is 0 to 5, how did we disappoint you and what can we do to improve?",
"maxLength": 300
},
{
"type": "comment",
"name": "improvements-required",
"title": "If your score is 6 or higher, what can we do to improve your experience?",
"maxLength": 300
},
{
"type": "checkbox",
"name": "promoter-features",
"title": "If your score is 9 or 10, which features do you value most?",
"description": "Select up to three features, if applicable.",
"choices": [
{
"value": "performance",
"text": "Performance"
},
{
"value": "stability",
"text": "Stability"
},
{
"value": "ui",
"text": "User interface"
},
{
"value": "complete-functionality",
"text": "Complete functionality"
},
{
"value": "learning-materials",
"text": "Learning materials"
},
{
"value": "support",
"text": "Support quality"
}
],
"showOtherItem": true,
"otherText": "Other",
"colCount": 2,
"maxSelectedChoices": 3
}
]
},
{
"name": "page2",
"elements": [
{
"type": "boolean",
"name": "rebuy",
"title": "Would you buy our product again?"
}
]
},
{
"name": "page3",
"elements": [
{
"type": "boolean",
"name": "testimonial",
"title": "Would you be willing to provide a short testimonial?"
},
{
"type": "text",
"name": "email",
"title": "If yes, enter your email address",
"inputType": "email"
}
]
}
],
"questionsOnPageMode": "singlePage",
"headerView": "advanced"
};
const pdfDocOptions: IDocOptions = { };
const savePdf = function (surveyData: any) {
const surveyPdf = new SurveyPDF(surveyJson, pdfDocOptions);
surveyPdf.data = surveyData;
surveyPdf.applyTheme(MonochromeLight);
surveyPdf.save();
};
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Export Survey to PDF - SurveyJS for Angular';
surveyModel: Model;
ngOnInit() {
const survey = new Model(surveyJson);
survey.addNavigationItem({
id: "pdf-export",
title: "Save as PDF",
action: () => savePdf(survey.data)
});
this.surveyModel = survey;
}
}
```
--------------------------------
### Build the library with npm run build:all
Source: https://github.com/surveyjs/survey-pdf/blob/master/README.md
Build the library. Output goes to the build directory. npm run build:all also builds the embeddable fonts bundle, the interactive-forms (pdf-form-filler) bundle, and the layout presets. Use npm run watch:dev while developing.
```sh
npm run build:all
```
--------------------------------
### Test commands (vitest, coverage, watch, snapshot update, single file, single test)
Source: https://github.com/surveyjs/survey-pdf/blob/master/CLAUDE.md
Run the test suite with coverage, watch mode, update snapshots, run a specific test file, or run a test by name. PDF output is verified by snapshotting computed layout (brick rectangles/text) rather than pixel-diffing.
```bash
npm run test # vitest run --coverage
npm run test:watch # vitest --no-isolate
npm run test:update-snapshots # regenerate snapshots (vitest --mode update-snapshots)
npx vitest run tests/.test.ts
npx vitest run -t "test name"
```
--------------------------------
### PDFFormFillerBase.raw()
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/pdfformfillerbase.md
An asynchronous method that allows you to get PDF content in different formats. You can specify the output type as 'blob', 'bloburl', or 'dataurlstring', or omit the parameter to get raw PDF content as a string.
```APIDOC
## PDFFormFillerBase.raw()
### Description
An asynchronous method that allows you to get PDF content in different formats.
### Method
raw()
### Parameters
- `type` ("blob" | "bloburl" | "dataurlstring") - Optional - One of "blob", "bloburl", "dataurlstring". Do not specify this parameter if you want to get raw PDF content as a string value.
### Return Value
`unknown` - The PDF content in the requested format.
```
--------------------------------
### Build the library
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/readme.md
Command to build the library for production. Built scripts and stylesheets are located in the packages/survey-pdf directory.
```bash
npm run build_prod
```
--------------------------------
### Run unit tests
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/readme.md
Command to execute the project's unit tests.
```bash
npm test
```
--------------------------------
### Configure borderWidth
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/iborderstyle.md
Demonstrates how to set the border width in points using a single value or an array to specify widths for individual sides.
```js
// all four sides
borderWidth: 2,
// top and bottom | left and right
borderWidth: [2, 1],
// top | left and right | bottom
borderWidth: [2, 1, 4],
// top | right | bottom | left
borderWidth: [2, 1, 4, 3]
```
--------------------------------
### Lint command (npm run lint)
Source: https://github.com/surveyjs/survey-pdf/blob/master/CLAUDE.md
Run ESLint on the src directory with the --quiet flag. The husky pre-push hook runs lint, build, and test via pre-push-check.
```bash
npm run lint # eslint ./src --quiet
```
--------------------------------
### Add Page Numbers to Footer
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/add-header-and-footer-to-pdf-form.md
This example demonstrates how to add page numbers to the footer, positioned in the bottom right corner with 12-millimeter margins.
```js
surveyPdf.onRenderFooter.add((_, canvas) => {
canvas.drawText({
text: "Page " + canvas.pageNumber + " of " + canvas.pageCount,
horizontalAlign: "right",
verticalAlign: "bottom",
margins: {
right: 12,
bot: 12
}
});
});
```
--------------------------------
### PDFFormFillerBase.save()
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/pdfformfillerbase.md
An asynchronous method that starts to download the filled PDF form in the web browser. You can optionally specify a file name for the downloaded PDF.
```APIDOC
## PDFFormFillerBase.save()
### Description
An asynchronous method that starts to download the filled PDF form in the web browser.
### Method
save()
### Parameters
- `fileName` (string) - Optional - A file name with the ".pdf" extension. Default value: "FilledForm.pdf".
### Return Value
`any` - The result of the download operation.
```
--------------------------------
### Build commands (npm run build, build:fonts, build:forms, build:all, watch:dev)
Source: https://github.com/surveyjs/survey-pdf/blob/master/CLAUDE.md
Build the main bundle with rollup, the embeddable fonts bundle, the interactive-forms bundle, or all three. Use watch:dev for rollup watch mode. The fonts.ts file is built separately and excluded from coverage.
```bash
npm run build # main bundle (rollup), emits minified + non-source files
npm run build:fonts # the embeddable fonts bundle (rollup.fonts.config.mjs)
npm run build:forms # the interactive-forms bundle (rollup.forms.config.mjs)
npm run build:all # build + build:fonts + build:forms
npm run watch:dev # rollup -w
```
--------------------------------
### Register a Custom Renderer for a PDF Brick
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/export-custom-components.md
Configure a custom renderer by extending the FlatQuestion class and implementing generateFlatsContent to return an array of custom PDF bricks, then register it with FlatRepository.
```js
import { FlatRepository, FlatQuestion } from "survey-pdf";
/* Custom PDF brick configuration goes here */
class FlatCustomColor extends FlatQuestion {
async generateFlatsContent(point) {
const rect = { ...point };
rect.yBot = point.yTop + 20;
rect.xRight = point.xLeft + 100;
return [new CustomPdfBrick(this.question, this.controller, rect)];
}
}
FlatRepository.register("color-picker", FlatCustomColor);
```
--------------------------------
### Draw Base64 Image in Footer
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/add-header-and-footer-to-pdf-form.md
Use the drawImage method to render a Base64-encoded image. This example scales the image to occupy half of the drawing area's dimensions.
```js
surveyPdf.onRenderFooter.add((_, canvas) => {
canvas.drawImage({
base64: "data:image/png;base64,...",
width: (canvas.rect.yBot - canvas.rect.yTop) * 0.5,
height: (canvas.rect.yBot - canvas.rect.yTop) * 0.5
});
});
```
--------------------------------
### Switch to Compact layout in classic script application
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/pdf-appearance-customization.md
Loads the layout index script and applies the Compact layout via the DocLayout.Compact object in a classic script application.
```html
```
--------------------------------
### Run unit tests with npm and Vitest
Source: https://github.com/surveyjs/survey-pdf/blob/master/README.md
Run unit tests using Vitest in a jsdom environment. PDF output is verified by snapshotting the computed layout. The commands cover the whole suite, watch mode, snapshot regeneration, a single file, and tests matching a substring.
```sh
npm run test # whole suite
npm run test:watch # watch mode
npm run test:update-snapshots # regenerate snapshots
npx vitest run tests/flat_checkbox.test.ts # a single file
npx vitest run -t "test name" # tests matching a substring
```
--------------------------------
### Set htmlRenderAs option in SurveyPDF constructor
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/customize-survey-question-rendering-in-pdf-form.md
Configure the PDF generator to render HTML questions as images, standard text, or automatically. The 'auto' mode is the default. This example shows both the script-tag and modular import usage.
```javascript
const pdfDocOptions = {
htmlRenderAs: "image" // or "standard" | "auto"
};
const surveyPdf = new SurveyPDF.SurveyPDF(surveyJson, pdfDocOptions);
// In modular applications:
import { SurveyPDF } from "survey-pdf";
const surveyPdf = new SurveyPDF(surveyJson, pdfDocOptions);
```
--------------------------------
### Configure borderColor
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/iborderstyle.md
Demonstrates how to set the border color using a single value or an array to specify colors for individual sides.
```js
// all four sides
borderColor: "#ff0000",
// top and bottom | left and right
borderColor: ["#ff0000", "#0000ff"],
// top | left and right | bottom
borderColor: ["#ff0000", "#008000", "#0000ff"],
// top | right | bottom | left
borderColor: ["#ff0000", "#008000", "#0000ff", "#FFA500"]
```
--------------------------------
### Customize choice item styles with onGetItemStyle
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/pdf-appearance-customization.md
Use the onGetItemStyle event to set the font and border colors of choice items based on their value. The example modifies the style for the 'colors' question, setting choiceText.fontColor, input.fontColor, and input.borderColor to the item's value.
```javascript
import { SurveyPDF } from "survey-pdf";
const surveyJson = {
"pages": [
{
"name": "page1",
"elements": [
{
"type": "radiogroup",
"name": "colors",
"title": "Select a color",
"choices": [
{ "value": "red", "text": "Red" },
{ "value": "green", "text": "Green" },
{ "value": "blue", "text": "Blue" }
]
}
]
}
]
};
const pdfDocOptions = { /* PDF document settings */ };
const surveyPdf = new SurveyPDF(surveyJson, pdfDocOptions);
surveyPdf.data = { /* Survey data */ }
surveyPdf.onGetItemStyle.add((_, options) => {
if (options.question.name === "colors") {
options.style.choiceText.fontColor = options.item.value;
options.style.input.fontColor = options.item.value;
options.style.input.borderColor = options.item.value;
}
});
surveyPdf.save();
```
--------------------------------
### Apply Spacious layout in classic script application
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/pdf-appearance-customization.md
Loads the Spacious layout script and applies it via the DocLayout.Spacious object in a classic script application.
```html
```
--------------------------------
### Apply Type-Wide Styles with applyStyle
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/pdf-appearance-customization.md
Use this snippet to apply type-wide styles to all elements of a given type. The example increases the gap between header and content for all Radio Button Group questions and assigns different title colors to surveys, pages, and panels. The `applyStyle` method is called on a `SurveyPDF` instance before saving.
```js
import { SurveyPDF } from "survey-pdf";
const surveyJson = { /* Survey JSON schema */ };
const pdfDocOptions = { /* PDF document settings */ };
const surveyPdf = new SurveyPDF(surveyJson, pdfDocOptions);
surveyPdf.data = { /* Survey data to populate the document with */ }
surveyPdf.applyStyle({
radiogroup: {
spacing: { choiceGap: 10 }
},
survey: {
title: { fontColor: "#1F3A5F" }
},
page: {
title: { fontColor: "#3F5F8A" }
},
panel: {
title: { fontColor: "#6F86A6" }
}
});
surveyPdf.save();
```
--------------------------------
### Configure borderRadius
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/iborderstyle.md
Demonstrates how to set the border radius in points using a single value or an array to specify radii for individual corners.
```js
// all four corners
borderRadius: 15,
// top-left and bottom-right | top-right and bottom-left
borderRadius: [15, 50],
// top-left | top-right and bottom-left | bottom-right
borderRadius: [15, 50, 30],
// top-left | top-right | bottom-right | bottom-left
borderRadius: [15, 50, 30, 5]
```
--------------------------------
### Clone the survey-pdf repository
Source: https://github.com/surveyjs/survey-pdf/blob/master/README.md
Clone the survey-pdf repository and navigate into the project directory.
```sh
git clone https://github.com/surveyjs/survey-pdf.git
cd survey-pdf
```
--------------------------------
### Configure Survey and PDF Export
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/get-started-html-css-javascript.md
Defines the survey structure, initializes the model, and sets up a navigation item to trigger the PDF export process using SurveyPDF.
```javascript
const surveyJson = {
"title": "NPS Survey Question",
"description": "NPS (net promoter score) is a metric used to evaluate customer loyalty and business growth opportunities. To measure NPS, respondents should rate on a scale of 0 to 10 how likely they would recommend your product or service to a friend or colleague.",
"pages": [
{
"name": "page1",
"elements": [
{
"type": "rating",
"name": "nps-score",
"title": "On a scale from 0 to 10, how likely are you to recommend us to a friend or colleague?",
"rateMin": 0,
"rateMax": 10
},
{
"type": "comment",
"name": "disappointing-experience",
"title": "If your score is 0 to 5, how did we disappoint you and what can we do to improve?",
"maxLength": 300
},
{
"type": "comment",
"name": "improvements-required",
"title": "If your score is 6 or higher, what can we do to improve your experience?",
"maxLength": 300
},
{
"type": "checkbox",
"name": "promoter-features",
"title": "If your score is 9 or 10, which features do you value most?",
"description": "Select up to three features, if applicable.",
"choices": [
{
"value": "performance",
"text": "Performance"
},
{
"value": "stability",
"text": "Stability"
},
{
"value": "ui",
"text": "User interface"
},
{
"value": "complete-functionality",
"text": "Complete functionality"
},
{
"value": "learning-materials",
"text": "Learning materials"
},
{
"value": "support",
"text": "Support quality"
}
],
"showOtherItem": true,
"otherText": "Other",
"colCount": 2,
"maxSelectedChoices": 3
}
]
},
{
"name": "page2",
"elements": [
{
"type": "boolean",
"name": "rebuy",
"title": "Would you buy our product again?"
}
]
},
{
"name": "page3",
"elements": [
{
"type": "boolean",
"name": "testimonial",
"title": "Would you be willing to provide a short testimonial?"
},
{
"type": "text",
"name": "email",
"title": "If yes, enter your email address",
"inputType": "email"
}
]
}
],
"questionsOnPageMode": "singlePage",
"headerView": "advanced"
};
const survey = new Survey.Model(surveyJson);
const pdfDocOptions = { };
const savePdf = function (surveyData) {
const surveyPdf = new SurveyPDF.SurveyPDF(surveyJson, pdfDocOptions);
surveyPdf.data = surveyData;
surveyPdf.applyTheme(SurveyTheme.MonochromeLight);
surveyPdf.save();
};
survey.addNavigationItem({
id: "pdf-export",
title: "Save as PDF",
action: () => savePdf(survey.data)
});
document.addEventListener("DOMContentLoaded", function() {
survey.render(document.getElementById("surveyContainer"));
});
```
--------------------------------
### Enable applyImageFit for Image Questions
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/customize-survey-question-rendering-in-pdf-form.md
Set the applyImageFit option to true to respect the imageFit property in exported PDFs. Note that this may reduce image quality due to conversion processes.
```js
const options = {
applyImageFit: true
};
const surveyPdf = new SurveyPDF.SurveyPDF(surveyJson, pdfDocOptions);
// In modular applications:
import { SurveyPDF } from "survey-pdf";
const surveyPdf = new SurveyPDF(surveyJson, pdfDocOptions);
```
--------------------------------
### SurveyPDF Constructor
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/idocoptions.md
Creates a SurveyPDF instance with survey JSON and PDF document options.
```APIDOC
## SurveyPDF Constructor
### Description
Creates a SurveyPDF instance with survey JSON and PDF document options.
### Method
Constructor
### Endpoint
`new SurveyPDF(surveyJson, pdfDocOptions)`
### Parameters
- **surveyJson** (object) - Required - Survey JSON schema.
- **pdfDocOptions** (IDocOptions) - Required - PDF document configuration.
### Request Example
```js
const surveyPdf = new SurveyPDF.SurveyPDF(surveyJson, pdfDocOptions);
// In modular applications:
import { SurveyPDF } from "survey-pdf";
const surveyPdf = new SurveyPDF(surveyJson, pdfDocOptions);
```
### Response
No response. The constructor returns a SurveyPDF instance.
```
--------------------------------
### applyTheme()
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/surveypdf.md
Applies a UI theme to the exported PDF document. The theme defines color- and shadow-related CSS variables.
```APIDOC
## applyTheme()
### Description
Applies a UI theme to the exported PDF document. A theme defines color- and shadow-related CSS variables. To configure spacing, sizing, typography, and other non-color variables, use the applyLayout method.
### Method
applyTheme()
### Parameters
- **theme** (ITheme) - Required - An ITheme object with theme settings.
- **baseTheme** (ITheme) - Optional - An optional ITheme object used as the base theme. When specified, it is deep-merged with theme, and the merged result is applied.
### Availability
Available since: v3.0.0
```
--------------------------------
### Apply Spacious layout preset with surveyPdf.applyLayout()
Source: https://github.com/surveyjs/survey-pdf/blob/master/README.md
Imports the Spacious layout preset from survey-pdf/layouts and applies it to a SurveyPDF instance. Use this to switch from the default Compact layout to the Spacious preset, which is optimized for readability. The applyLayout() method is part of the PDF appearance customization API.
```javascript
import { Spacious } from "survey-pdf/layouts";
surveyPdf.applyLayout(Spacious);
```
--------------------------------
### IQuestionStyle Interface
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/iquestionstyle.md
Defines the visual style applied to question UI elements in an exported PDF document. This interface includes properties for styling comment areas, labels, containers, descriptions, headers, inputs, numbers, required marks, spacing, and titles.
```APIDOC
## IQuestionStyle Interface
### Description
Defines the visual style applied to question UI elements in an exported PDF document.
### Properties
#### comment
- **Type**: IInputStyle
- Specifies the visual style applied to the question comment. Applies only to questions that include a comment area.
- Available since: v3.0.0
#### commentLabel
- **Type**: ITextStyle
- Specifies the visual style applied to the text above the question's comment area. Applies only to questions that include a comment area.
- Available since: v3.0.0
#### commentReadOnly
- **Type**: IInputStyle
- Specifies the visual style applied to the question comment in read-only mode. Applies only to questions that include a comment area.
- Available since: v3.0.0
#### container
- **Type**: IContainerStyle
- Specifies the visual style applied to the container in which the question is rendered.
- Available since: v3.0.0
#### description
- **Type**: ITextStyle
- Specifies the visual style applied to the question description.
- Available since: v3.0.0
#### header
- **Type**: IContainerStyle
- Specifies the visual style applied to the question header.
- Available since: v3.0.0
#### inlineHeaderWidthPercentage
- **Type**: number
- Specifies the width percentage allocated to the question header. Applies only to questions with titleLocation set to "left".
- Possible values: from 0 to 1 (for example, 0.25)
- Available since: v3.0.0
#### input
- **Type**: IInputStyle
- Specifies the visual style applied to the question input.
- Available since: v3.0.0
#### minWidth
- **Type**: number
- Specifies the minimum width of the container in which the question is rendered, in points.
- Available since: v3.0.0
#### number
- **Type**: ITextStyle
- Specifies the visual style applied to the question number.
- Available since: v3.0.0
#### requiredMark
- **Type**: ITextStyle
- Specifies the visual style applied to the required mark.
- Available since: v3.0.0
#### spacing
- **Type**: IQuestionSpacing
- Specifies spacing values applied to question UI elements.
- Available since: v3.0.0
#### title
- **Type**: ITextStyle
- Specifies the visual style applied to the question title.
- Available since: v3.0.0
```
--------------------------------
### Implement a Custom PDF Brick
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/export-custom-components.md
Create a custom PDF brick by extending the PdfBrick class and implementing the renderInteractive method to define custom drawing logic using jsPDF APIs.
```js
import { PdfBrick } from "survey-pdf";
class CustomPdfBrick extends PdfBrick {
async renderInteractive() {
const doc = this.controller.doc;
let oldFillColor = doc.getFillColor();
doc.setFillColor(this.question.value || "black");
doc.rect(this.xLeft, this.yTop, this.width, this.height, "F");
doc.setFillColor(oldFillColor);
}
}
```
--------------------------------
### Applying a Theme to the PDF Form
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/get-started-nodejs.md
Import a theme from survey-core/themes and apply it to the SurveyPDF instance using the applyTheme method.
```js
import { MonochromeLight } from "survey-core/themes";
const surveyPdf = new SurveyPDF({ /* ... */ });
surveyPdf.applyTheme(MonochromeLight);
```
--------------------------------
### Debug PDF Bricks with onRenderQuestion
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/customize-survey-question-rendering-in-pdf-form.md
Use the debugger within the onRenderQuestion event handler to inspect the options.bricks array and understand the structure of rendered questions.
```js
const surveyPdf = new SurveyPDF.SurveyPDF(surveyJson, pdfDocOptions);
surveyPdf.onRenderQuestion.add((_, options) => {
debugger;
});
// In modular applications:
import { SurveyPDF } from "survey-pdf";
const surveyPdf = new SurveyPDF(surveyJson, pdfDocOptions);
surveyPdf.onRenderQuestion.add((_, options) => {
debugger;
});
```
--------------------------------
### onRenderQuestion
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/surveypdf.md
Event handler for customizing question rendering.
```APIDOC
## `onRenderQuestion`
### Description
An event that is raised when SurveyJS PDF Generator renders a survey question. Handle this event to customize question rendering.
### Parameters
- `sender`: `SurveyPDF` - A `SurveyPDF` instance that raised the event.
- `options.question`: `Question` - A survey question that is being rendered.
- `options.point`: `IPoint` - An object with coordinates of the top-left corner of the element being rendered. This object contains the following properties: `{ xLeft: number, yTop: number }`.
- `options.bricks`: `PdfBrick[]` - An array of bricks used to render the element.
- `options.controller`: `DocController` - An object that provides access to main PDF document properties (font, margins, page width and height) and allows you to modify them.
- `options.repository`: `FlatRepository` - A repository with classes that render elements to PDF. Use its `create` method if you need to create a new instance of a rendering class.
```
--------------------------------
### Apply Monochrome Light Theme to SurveyPDF
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/pdf-appearance-customization.md
Apply the Monochrome Light theme to a SurveyPDF instance. For modular applications, import the theme from 'survey-core/themes' and call applyTheme. For classic script applications, include the monochrome-light.min.js script and use SurveyTheme.MonochromeLight.
```js
import { MonochromeLight } from "survey-core/themes";
const surveyPdf = new SurveyPDF({ /* ... */ });
surveyPdf.applyTheme(MonochromeLight);
```
```html
```
--------------------------------
### ISelectBaseSpacing Interface
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/api-reference/iselectbasespacing.md
Defines spacing values for select-based question types in PDF export. Available since v3.0.0.
```APIDOC
## ISelectBaseSpacing Interface
### Description
Defines spacing values applied to UI elements within Checkboxes, Radio Button Group, Image Picker, Ranking, and Rating Scale questions in an exported PDF document. Available since v3.0.0.
### Inheritance
ISpacingBase -> IQuestionSpacing -> ISelectBaseSpacing
### Properties
#### choiceColumnGap
- **Type**: number
- Specifies the horizontal gap between choice columns, in points. Applies when choice options are arranged in two or more columns.
- Available since: v3.0.0
#### choiceGap
- **Type**: number
- Specifies the vertical gap between choice options, in points.
- Available since: v3.0.0
#### choiceTextGap
- **Type**: number
- Specifies the horizontal gap between the selection input (checkbox or radio button) and the choice text, in points.
- Available since: v3.0.0
```
--------------------------------
### Use a Predefined Renderer for Custom Questions
Source: https://github.com/surveyjs/survey-pdf/blob/master/docs/export-custom-components.md
Register a custom question type to use the renderer of an existing question type, such as Text Input, by extending the corresponding model and using FlatRepository.
```js
import { FlatRepository } from "survey-pdf";
import { QuestionTextModel } from "survey-core";
const CUSTOM_TYPE = "color-picker";
export class QuestionColorPickerModel extends QuestionTextModel {
getType() {
return CUSTOM_TYPE;
}
//...
}
FlatRepository.register(
CUSTOM_TYPE,
FlatRepository.getRenderer("text")
);
```