Skip to content

sc-pdf

*This document is a user guide for the sc-pdf component release version 7.2.2

go-to-typical-definition

 

1. Purpose

The new sc-pdf component can be used to generate formatted pdf documents for printing, audit or other purposes. The component uses javascipt library PDFMAKE.

pdfs can be fully customised with:

  • styling
  • tables and columns
  • headers and footers
  • images
  • etc.

It allows data to be taken from template definitions and formatted in a suitable way that meets the needs of the customer. The resulting pdf can then be viewed live, downloaded or printed, and can now be uploaded and saved on the formbird server via a variety of means.

The component requires a valid PDFMAKE object which specifies the format for the output PDF. See PDFMAKE for documentation and correct practice.

 

2. Definition

sc-pdf is defined by a set of name/value pair fields consisting of:

  • Required system fields
  • Required customizable fields
  • Optional customizable fields

Note:

  1. Default values for fields described in the tables below are shown in bold text.

2.1. Required System Fields

Field Valid Values Description
componentName sc-pdf The component name.

Example:
"componentName": "sc-pdf"

2.2. Required Customisable Fields

Field Valid Values Description
name Any value written in camel case Defines the name of the sc-pdf field in the document and database.

Example: "name": "testScPdf"

2.3. Optional Customisable Fields

Field Valid Values Description
buttonLabel Any value Changes the action button label to provide more information.

Example:
"buttonLabel": "Open in new tab"
buttonType value Default Value.
buttonType Download Sets the action button to Download. Clicking the button downloads the pdf.

Example: "buttonType": "Download"
Open Sets the action button to Open. Clicking the button opens the pdf in a new tab.

Example: "buttonType": "Open"
Print Sets the action button to Print. Clicking the button opens the pdf in a new tab and opens browser print dialog menu.

Example: "buttonType": "Print"
none Default Value.
Removes the action button from the component display.
disableSave true Clicking the action button or changing the pdf value (through the rulesets) does not trigger the Save icon to flash.
Exiting the form without saving changes to the sc-pdf field value does not trigger a warning message to display.
In the Angular version of the sc-pdf component, clicking the Save icon will not save the sc-pdf field value to the document.
In the AngularJS version of the sc-pdf component, clicking the Save icon will save the sc-pdf field value to the document.

Example: "disableSave": true
false Default Value.
Changing the sc-pdf field value (i.e. entering or editing a value) or clicking action button does trigger the Save icon to flash.
Exiting the form without saving changes to the sc-pdf field value does trigger a warning message to display.
In both the Angular and AngularJS versions of the sc-pdf component, clicking the Save icon will save the sc-pdf field value to the document.
docDefName String Defaults to 'pdfDef'
When using rulesets to dynamically assign the pdf definition, this field is used to fetch the definition from the document via an assignable variable. This variable must contain a valid pdfDefintion object as per PDFMAKE documentation. docDefName takes preference over pdfDefintion in assigning the pdf object creation/display.
Do not make this the component name. It must be another name entirely that is unique on the template
See tutorials for further information

Example:
"docDefName": "pdfDef"
enabled false No updates can be made to the sc-pdf, all buttons are hidden, except those in full width for print and download. Only a preview can be loaded from a paired sc-uploader component specified by 'scUploaderName'. It will fetch either a pdf file from the uploader with the specified 'pdfFileName' or the component 'name'. If there is no corresponding file no preview will be shown.
In this mode, it is best to ensure the sc-uploader component is disabled as well to prevent saved PDF deletions.

Example: "enabled": false
true Default Value.
PDF's can be generated and buttons are functional.
fullWidth true The sc-pdf preview displays the full width of the form. Recommended displaying the sc-pdf component in full width.

Example: "fullWidth": true
false Default value.
The sc-pdf does not display the full width of the form.
label Any value Defines the name of the sc-pdf field on the form i.e. the field label.

Example: "label": "Test sc-pdf"
Defaults to no label is displayed.
openInSameWindow true When using buttonType: "Open" or "Print", it will open/Print the pdf from the initial same tab.

Example: "openInSameWindow": true
false Default value.
The pdf will open/print in a new tab/window.
pdfDefinition valid pdfmake object Pdf definition used by the component. See PDFMAKE documentation for more information.
Example:
"pdfDefinition": "{ content: 'Example test document' }"

Dynamic Assignment: Can be set programmatically using rulesets:
javascript<br />ntf.scope.setComponentProps('pdfReportCompDef', 'sc-pdf', {<br /> 'pdfDefinition': val<br />});<br />
pdfFileName Any Value Defines the name of the downloaded/printed pdf.
This string now is also able to process handlebars and can be used to dynamically fetch other values from the document.
It is worth noting that these fields must exist on the document when the pdf is generated.
Example:
"pdfFileName": "examplePdfName {{document.exampleId}}"
Defaults to component Name.
preview false Hides the preview window, leaving just print button.

Example:
"preview": false
true Default value.
Displays the pdf preview window
previewHeight String Sets the height of the preview window. Can be specified in pixels (px) or percentage (%).

Example: "previewHeight": "300px" or "previewHeight": "80%"
Defaults to calculated height based on content.
previewWidth String Sets the width of the preview window. Can be specified in pixels (px) or percentage (%).

Example: "previewWidth": "500px" or "previewWidth": "100%"
Defaults to "100%".
scUploaderName any sc-uploader component name Specifies what uploader to save the generated PDF. Only required for uploadType 'scUploader'. A sc-uploader component is needed on the document definition for this functionality to work.
The name of the uploaded pdf file should be specified with 'pdfFileName' however defaults to the sc-pdf component 'name'

Example:
"scUploaderName": "testScUploader"
uploadDefault true This will upload the default pdf definition to the server. Use this functionality when you have a basic pdf that needs to be generated and then utilized elsewhere like email.
false Default value.
The default pdf definition will not be uploaded to the server.
uploadType none Default value.
Sets component to display only mode which means that the component will only display a pdf. It will display a pdf from the document or render one from a valid pdf definition. This mode disables uploads when a pdf definition (via docDefName) or pdfDefinition is defined.
Note: valid pdfs can be assigned to the document using ntf.document[name] from a ruleset and this will be displayed by the component.
onGen This upload type generates the pdf when it is created. Note that the pdfDefinition does not allow for pdf uploading as it is displayed when the component is instantiated. Eg. when the docDefName is assigned to in the rulesets.
This upload type now makes use of pending operation and will always ensure the generated pdf is uploaded.
Example:
"uploadType": "onGen"
preSave PDF will be uploaded to the server on the pre-save event. Ie just before the document is saved. This ensures that the document is saved with the PDF on a successful save event. Issues arise here if the onFieldState ruleset assigning the pdf does so after the save tick has been clicked. For stability please use onGen or server side rendering using pdf functions ruleset includes.
scUploader This upload type requires scUploaderName and this uses the uploader component to upload the PDF to the server. The PDF is available through the saved sc-uploader object. This type allows for visual representation of saved pdf's in the uploader field, however requires the upload to be completed before the user saves or exits the page.
server Server-side PDF generation using pdfFunctions ruleset includes. Requires server-side ruleset configuration.
useGenerateButton true Turns off automatic generation of PDF when the assigned pdfDefinition is changed. Generate PDF button must be clicked to generate a PDF from the pdfDefinition. Works best in cases where users want control when to generate PDF's.

Example:
"useGenerateButton": true`
false Default value.
Document is watched for changes and PDF will be updated on changes. This works with rulesets where assigning of the variable from docDefName is performed once, before the component is disabled.
visible false The sc-pdf component is not visible on the form.

Example:
"visible": false
true Default Value.
The sc-pdf component is visible on the form.

 

3. PDF Definition Formats

The pdfDefinition property can accept either a string or an object format:

3.1. String Format

When pdfDefinition is provided as a string, it can be:

  • A JSON string: '{"content": ["Hello World"]}'
  • A JavaScript object string: '{content: "Hello World"}'
  • A function string: 'function(context) { return {content: "Hello World"}; }'

3.2. Object Format

When pdfDefinition is provided as an object, it should be a valid PDFMake definition object:

{
    content: ['Hello World'],
    styles: {
        header: { fontSize: 18, bold: true }
    }
}

3.3. Document Storage Considerations

Important: When saving PDF definitions to the document (via docDefName or pdfDef fields), the following applies:

  • Object format is recommended for runtime.

  • String format should be used for document storage to avoid Elasticsearch mapping issues with large objects

  • Large objects should be avoided in document storage due to Elasticsearch limitations

Example of proper document storage:

// Convert object to string before saving
const pdfObject = { content: ['Hello World'] };
ntf.document.pdfDef = JSON.stringify(pdfObject);

 

4. Typical Definition

Below is a typical sc-pdf definition, defined with its required fields plus any optional field whose value is typically other than its default value.

{
  "componentName": "sc-pdf",
    "pdfDefinition": "{content:'Example test document.'}",
    "name": "report1Pdf",
}

One or more of the optional fields shown below can be included in the above definition should a value other than their default value be required.

    "fullWidth": true,
    "pdfFileName": "examplePdfFileName",
    "previewWidth": "500px",
    "previewHeight": "300px",
    "buttonType": "Print",
    "buttonLabel": "Print in new tab",
    "openInSameWindow": false,
    "docDefName": "pdfString",
    "uploadDefault": false,
    "uploadType": "onGen",
    "scUploaderName": "testScUploaderName",
    "useGenerateButton": true

 

5. Examples

Example 1

sc-pdf defined with the typically needed fields. This will autogenerate a basic PDF with the text Example test document.

{
  "componentName": "sc-pdf",
    "pdfDefinition": "{content:'Example test document.'}",
    "name": "typicalDefnScPdf"
}

 

Example 2

This example will generate a larger preview window with the text 'Example document' and a Print action button with the label 'Print in a New Tab'. As we have defined docDefName, we can assign from the ruleset a generated PDF Object that will override the default pdf definition here. This workflow works best when working with images, or information from a template that requires a rulset to be used.

{
        "componentName": "sc-pdf",
        "fullWidth": true,
        "buttonType": "Print",
        "buttonLabel": "Print in New Tab",
        "pdfDefinition": "{ content: 'Example document text' }",
        "name": "typicalDefnScPdf",
        "docDefName": "pdfDef"
}

Example 3

This example will generate a basic PDF only when the Generate PDF button is clicked, and it will upload and save the PDF URL to the document.

{
        "componentName": "sc-pdf",
        "fullWidth": true,
        "pdfDefinition": "{ content: 'Example document' }",
        "name": "typicalDefnScPdf",
        "pdfFileName": "exampleTestPdfName",
        "uploadType": "onGen",
        "uploadDefault": true,
        "useGenerateButton": true
}

An example output is...

"typicalDefnScPdf": [{
  "fileName": "exampleTestPdfName.pdf",
  "fileNo": "418a9760-6f97-11ed-b85e-fdf3cd548c0e",
  "createdDate": "2022-11-29T03:38:14.869Z",
  "basePath": "20240301",
  "fileType": "PDF"
 }]

 

Example 4

This example will generate a basic PDF only when the Generate PDF button is clicked, and it will save this PDF to the defined sc-uploader. Once we are happy with our generated pdf, to avoid saving more PDFs to the uploader, we should set the component to enabled:false.

{
        "componentName": "sc-pdf",
        "fullWidth": true,
        "pdfDefinition": "{ content: 'Example document' }",
        "name": "typicalDefnScPdf",
        "scUploaderName": "exampleScUploader",
        "uploadType": "scUploader",
        "useGenerateButton": true,
        "enabled":true
},
{
        "componentName": "sc-uploader",
        "fullWidth": true,
        "name": "exampleScUploader"
}

 

Example 5

Here we will incorporate sc-pdf with sc-signature for sign on glass functionality using the rulesets. When the Generate PDF button is clicked, and it will grab the signature from the other component . Note docDefName defaults to pdfDef

Document:

{
        "componentName": "sc-signature",
        "name": "auditorSignature",
        "label": "Auditor's Signature",
        "saveAsImage": true
},
{
        "componentName": "sc-pdf",
        "fullWidth": true,
        "name": "report2Pdf",
        "pdfFileName": "ExampleTestPDF1"
}

Ruleset:

ruleOnfieldChangedPDFUpdate : { // handles PDF updates
    ruleCondition : function(ntf) {
        return ( (ntf.document.status === 'Completed') )
    },
    ruleAction : function(ntf, cb) {
      var ft3 = ntf.scope;
      const imgNames = {};

      console.log("Saving Signature to pdf"); // signature must be saved already
      const signatureURL = window.location.origin + "/" + ntf.document.auditorSignature[0];

      let dateStr = ft3.moment(ntf.document.signedDate).format('DD/MM/YYYY HH:mm a');

      // create data for pdfValue
      let val = createData();

      ntf.document.pdfDef = val; // assign pdf to default docDefName
      ft3.showField('report2Pdf', true);

      function createData() {
          // creating PDF Definition
          let data = {
            info: {
              title: 'audit'+"1234",
              author: "some name",
            },
            content: [
              {
                text: 'Formbird PDF with Rulesets',
                style: 'header',
              },
              'This document has an id = ' + context.documentId,
              'This document has a template id = ' + context.template.documentId,
              { text: "This is a test" },
              {image: "testSignature", fit: [100, 100] }
              ],
            styles: {
              header: {
                fontSize: 24,
                bold: true
                }
            },
          images: [
                "testSignature": signatureURL;
          ]};
          // convert data to String
          //  dataStr +=  JSON.stringify(data); // use this line for production
          let dataStr =  JSON.stringify(data, null, "\t"); // for debugging purposes (easy to read)
          return dataStr
        }
}}

 

Example 6

Below is one of our PDF Editor Templates that help with visualising the pdf as you create it.

example-pdf-editor f  

Example 7

This example demonstrates how to dynamically set the pdfDefinition using rulesets. This is useful when you need to generate PDF content based on form data or other dynamic conditions.

Ruleset Example:

ruleOnFieldChangedDynamicPDF : {
    ruleCondition : function(ntf) {
        return (ntf.document.status === 'Completed');
    },
    ruleAction : function(ntf, cb) {
        // Create dynamic PDF content based on document data
        const dynamicContent = {
            content: [
                { text: 'Dynamic PDF Report', style: 'header' },
                'Document ID: ' + ntf.document.documentId,
                'Status: ' + ntf.document.status,
                'Generated: ' + new Date().toISOString(),
                {
                    text: 'This PDF was generated dynamically using setComponentProps',
                    style: 'subheader'
                }
            ],
            styles: {
                header: { fontSize: 18, bold: true },
                subheader: { fontSize: 12, italics: true }
            }
        };

        // Set the pdfDefinition dynamically
        ntf.scope.setComponentProps('dynamicPdfComp', 'sc-pdf', {
            'pdfDefinition': JSON.stringify(dynamicContent)
        });
    }
}

Component Definition:

{
    "componentName": "sc-pdf",
    "name": "dynamicPdfComp",
    "fullWidth": true,
    "buttonType": "Download",
    "pdfFileName": "dynamic-report"
}

 

6. Server-Side PDF Functions

The sc-pdf component includes server-side PDF generation functions available through the pdfFunctions ruleset include. These functions allow for server-side PDF generation which is more reliable for complex documents.

6.1. Available Server Functions

Function Description Usage
createPdfServer(ntf, pdfData, fileName) Generates and saves a PDF on the server using the parsed PDF definition data object. Must be called only from server-side rulesets. const result = await pdfFunctions.createPdfServer(ntf, pdfData, fileName);
verifyPdf(pdfDefStr) Validates and parses PDF definition strings. Used internally by createPdfServer. Internal function

6.2. Server-Side Usage Example

// Server-side ruleset example
ruleOnFieldChangedPDFGeneration : {
    ruleCondition : function(ntf) {
        return (ntf.document.status === 'Completed');
    },
    ruleAction : function(ntf, cb) {
        const pdfData = {
            info: {
                title: 'Server Generated PDF',
                author: "Formbird System"
            },
            content: [
                { text: 'This PDF was generated server-side', style: 'header' },
                'Document ID: ' + ntf.document.documentId,
                'Generated on: ' + new Date().toISOString()
            ],
            styles: {
                header: { fontSize: 18, bold: true }
            }
        };

        const result = await pdfFunctions.createPdfServer(ntf, pdfData, 'server-generated.pdf');
        if (result) {
            ntf.document.reportPdf = [result];
        }
    }
}

Note: Server-side functions require the pdfFunctions ruleset include to be available in your template configuration.

 

7. Client Pre-Save Processing

The sc-pdf component includes a client pre-save processor that handles PDF uploads during the document save process. This function is automatically executed when a document is saved and the sc-pdf component has uploadType: "preSave".

7.1. Pre-Save Function Overview

The pre-save processor performs the following operations:

  1. Document Cleanup: Removes the docDefName field from the document if a PDF value exists
  2. Upload Detection: Checks if a PDF is awaiting save (note: 'Awaiting Save')
  3. File Upload: Uploads the PDF file to the server if conditions are met
  4. Document Update: Updates the document with the uploaded file information

7.2. Pre-Save Conditions

The pre-save processor will only execute when:

  • Upload Type: uploadType is set to "preSave"
  • PDF Object: A PDF file object is available in field.pdf
  • Update Flag: The PDF is marked as 'Awaiting Save'
  • Valid Field: The field name and document are valid

7.3. Pre-Save Behavior

  1. Automatic Cleanup: Removes docDefName field from document after PDF generation
  2. File Upload: Uploads PDF to server using FileProviderService
  3. Document Update: Updates document with file metadata (fileName, fileNo, createdDate, fileType)
  4. Error Handling: Provides user feedback for upload failures

 

8. Additional Information

More information: For more information on features, valid pdf definition values, table formatting and more see PDFMAKE website.