The PDFGenerationAPI provides support for PDF conversion and handling PDF fields.

This API is part of the ServiceNow PDF Generation Utilities plugin (com.snc.apppdfgenerator) and is provided within the sn_pdfgeneratorutils namespace. The plugin is activated by default.

Use the glide.pdf.url.whitelist property to add an extra layer of validation to ensure whether any external URL introduced should be included in the generated PDF. If the system property glide.pdf.url.whitelisting.enabled is set to true, the PDF does not process URL content unless it is listed in the Value field of the com.snc.pdf.whitelisted_urls system property. These properties are listed in the System Properties [sys_properties] table. For more information, see Available system properties.

The methods in this class enable the following tasks:
Note: These methods can also be used for documents created by non-catalog items.

PDFGenerationAPI – PDFGenerationAPI()

Instantiates a new PDFGenerationAPI object.

Table 1. Parameters
Name Type Description
None

Example

The following example shows how to create a PDFGenerationAPI object.

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;

PDFGenerationAPI – convertToPDF(String html, String targetTable, String targetTableSysId, String pdfName, String fontFamilySysId, Object documentConfiguration)

Converts an HTML string to a PDF document.

This method creates a PDF using the page size A4 – 595 × 842 points. Content will be truncated if it exceeds this size.

To generate a PDF with additional settings, such as page size, orientation, and page numbers, use convertToPDFWithHeaderFooter().

Example

The following example shows how to convert HTML to a PDF and attach it to a record in the Incident [incident] table.

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;

//  (Option) get HTML from the description field of an incident record
var gr = new GlideRecord("incident");
var html;

if (gr.get("<tableSysId>")) {
 html = gr.description.toString();
}

var result = v.convertToPDF(html, "incident", "<target_sys_id>", "myPDF");
gs.info(JSON.stringify(result));

Output:

{"attachment_id":"<sys_id>","message":"Conversion is successful.","request_id":"<change_sys_id>","status":"success"}

PDFGenerationAPI – convertToPDFAsync(String html, String targetTable, String targetTableSysId, String pdfName, String fontFamilySysId, Object documentConfiguration)

Stages a job that converts an HTML string to a PDF document asynchronously. Asynchronous processing enables you to work in the instance while the PDF conversion is in progress. This is especially helpful for larger PDF exports.

This API creates a PDF using the page size A4 – 595 × 842 points. Content will be truncated if it exceeds this size.

To generate a PDF with additional settings, such as page size, orientation, and page numbers, use convertToPDFWithHeaderFooterAsync().

Table 5. Returns
Type Description
Object Object indicating whether the PDF conversion is in progress. You can review the conversion status in the PDF Generation Status [sys_pdf_generation_status] table.
{
  "message": "String",
  "request_id": "String"
}
<Object>.message Message confirming success or error.
Possible values:
  • HTML to PDF Conversion is in progress. – Request to convert HTML to a PDF document is successful.
  • Exception while reading Source document contents. PDF header not found. – Input attachment provided is not a valid PDF. Provide the correct attachment sys_id.
  • Given target record [<tableName> - <targetTableSysId>] does not exist. – Target table sys_id is not in the table provided. Make sure you include the correct table name for the record.
  • No Form associated with pdf to fill. attachmentSysId: <sys_id>
  • No editable fields exist with specified names. Please check and try again. field names: <field names>
  • Request cannot proceed as the attachment with sys_id [{0}] did not pass security scan – The PDF did not pass the antivirus scan.
  • Request cannot proceed as the attachment with sys_id [{0}] is pending security scan – The PDF requires an antivirus scan.
  • Undefined – Sys_id provided does not exist or is not a PDF attachment.
  • <URL> is not listed in whitelisted URL, please check URL whitelisting property : "glide.pdf.url.whitelisting.enabled" and "com.snc.pdf.whitelisted_urls" – If the system property glide.pdf.url.whitelisting.enabled is set to true, the PDF does not process URL content unless it is listed in the Value field of the com.snc.pdf.whitelisted_urls system property. These properties are listed in the System Properties [sys_properties] table.

Data type: String

<Object>.request_id Sys_id of the change producer request record.

Data type: String

Example

The following example shows how to queue a task that converts HTML to a PDF. When the conversion is complete, the PDF named "myPDF" is attached to the target record in the Incident [incident] table.

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;

//  (Option) get HTML from the description field of an incident record
var gr = new GlideRecord("incident");
var html;

if (gr.get("<tableSysId>")) {
 html = gr.description.toString();
}

var result = v.convertToPDFAsync(html, "incident", "<target_sys_id>", "myPDF");
gs.info(JSON.stringify(result));

Output:

{"message":"HTML to PDF Conversion is in progress.","request_id":"<sys_id>"}

PDFGenerationAPI – convertToPDFWithHeaderFooter(String html, String targetTable, String targetTableSysId, String pdfName, Object headerFooterInfo, String fontFamilySysId, Object documentConfiguration)

Converts an HTML string into a PDF with header and footer content.

Use this method to generate PDFs with page settings:
  • Header and footer information
  • Margin sizes
  • Orientation
  • Enumeration
  • Page size

Example

The following example shows how to convert HTML to a PDF named "myPDF" and add the PDF as an attachment to a record in the Incident [incident] table. The PDF contains header and footer provided via attachment.

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;

//  (Option) get HTML from the description field of an incident record
var gr = new GlideRecord("incident");
var html;

if (gr.get("<tableSysId>")) {
 html = gr.description.toString();
}

var hfInfo = new Object();
hfInfo["HeaderImageAttachmentId"] = "<hdrImgAttSysId>";
hfInfo["HeaderImageAlignment"] = "left";
hfInfo["FooterImageAttachmentId"] = "<ftrImgAttSysId>";
hfInfo["FooterImageAlignment"] = "TOP_CENTER";
hfInfo["FooterText"] = "Sample Footer Message";
hfInfo["PageSize"] = "A4";
hfInfo["GeneratePageNumber"] = "false";
hfInfo["TopOrBottomMargin"] = "36";
hfInfo["LeftOrRightMargin"] = "24";

var result = v.convertToPDFWithHeaderFooter(html, "incident", "<targetTbl_sys_id>", "myPDF", hfInfo);
gs.info(JSON.stringify(result));

Output:

{"attachment_id":"<sys_id>","message":"Conversion is successful.","request_id":"<change_sys_id>","status":"success"}

PDFGenerationAPI – convertToPDFWithHeaderFooterAsync(String html, String targetTable, String targetTableSysId, String pdfName, Object headerFooterInfo, String fontFamilySysId, Object documentConfiguration)

Stages a job that converts an HTML string into a PDF with header and footer content asynchronously. Asynchronous processing enables you to work in the instance while the PDF conversion is in progress. This is especially helpful for larger PDF exports.

Use this method to generate PDFs with page settings:
  • Header and footer information
  • Margin sizes
  • Orientation
  • Enumeration
  • Page size
Table 9. Returns
Type Description
Object
<Object>.​message Message confirming success or error.
Possible values:
  • HTML to PDF Conversion is in progress. – Request to convert HTML to a PDF document is successful.
  • Footer Image alignment and text alignment cannot be in the same region with same alignment: <footerImageAlignment value> – Make sure that headerFooterInfo.​FooterImageAlignment and headerFooterInfo.​FooterTextAlignment values are not in the same area.
  • Exception while reading Source document contents. PDF header not found. – Input attachment provided is not a valid PDF. Provide the correct attachment sys_id.
  • Given target record [<tableName> - <targetTableSysId>] does not exist. – Target table sys_id is not in the table provided. Make sure you include the correct table name for the record.
  • Invalid footer image alignment: <invalid_option> is provided. – Provide a valid option in the headerFooterInfo.​FooterImageAlignment property.
  • Invalid footer text alignment: " + <invalid_option> + " is provided. – Provide a valid option in the headerFooterInfo.​footerTextAlignment property.
  • No Form associated with pdf to fill. attachmentSysId: <sys_id>
  • No editable fields exist with specified names. Please check and try again. field names: <field names>
  • Request cannot proceed as the attachment with sys_id [{0}] did not pass security scan – The PDF did not pass the antivirus scan.
  • Request cannot proceed as the attachment with sys_id [{0}] is pending security scan – The PDF requires an antivirus scan.
  • Unable to get the footer image. sysId: + <value provided> – Make sure the sys_id provided for headerFooterInfo.​footerImageId is accurate.
  • Unable to get the header image. sysId: + <value provided> – Make sure the sys_id provided for headerFooterInfo.​headerImageId is accurate.
  • Undefined – Sys_id provided does not exist or is not a PDF attachment.
  • <URL> is not listed in whitelisted URL, please check URL whitelisting property : "glide.pdf.url.whitelisting.enabled" and "com.snc.pdf.whitelisted_urls" – If the system property glide.pdf.url.whitelisting.enabled is set to true, the PDF does not process URL content unless it is listed in the Value field of the com.snc.pdf.whitelisted_urls system property. These properties are listed in the System Properties [sys_properties] table.

Data type: String

<Object>.request_id Sys_id of the change producer request record.

Data type: String

Example

The following example shows how to queue a task that converts HTML to a PDF. The PDF contains header and footer provided via attachment. When the conversion is complete, the PDF named "myPDF" is attached to the target record in the Incident [incident] table.

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;

//  (Option) get HTML from the description field of an incident record
var gr = new GlideRecord("incident");
var html;

if (gr.get("<tableSysId>")) {
 html = gr.description.toString();
}

var hfInfo = new Object();
hfInfo["HeaderImageAttachmentId"] = "<hdrImgAttSysId>";
hfInfo["HeaderImageAlignment"] = "left";
hfInfo["FooterImageAttachmentId"] = "<ftrImgAttSysId>";
hfInfo["FooterImageAlignment"] = "TOP_CENTER";
hfInfo["FooterText"] = "Sample Footer Message";
hfInfo["PageSize"] = "A4";
hfInfo["GeneratePageNumber"] = "false";
hfInfo["TopOrBottomMargin"] = "36";
hfInfo["LeftOrRightMargin"] = "24";

var result = v.convertToPDFWithHeaderFooterAsync(html, "incident", "<targetTbl_sys_id>", "myPDF", hfInfo);
gs.info(JSON.stringify(result));

Output:

{"message":"HTML to PDF Conversion is in progress.","request_id":"<sys_id>"}

PDFGenerationAPI – fillDocumentFields(Object fieldsMap, String sysId, String tableName, String tableSysId, String pdfName)

Fills fields in an editable PDF and attaches it to the provided record.

Use the following methods to determine if the PDF is fillable and get field information:
PDFGenerationAPI provides additional fill methods with different options:

Example

The following example shows how to fill fields in an editable PDF.

var fieldMap = new Object();
fieldMap["Address"] = "Address value here";
fieldMap["State"] = "State value here";

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;
var result = v.fillDocumentFields(fieldMap, "<attachmentSysId>", "<tableName>", "<tableSysId>", "pdfName");
gs.info(JSON.stringify(result));

Output:

{"attachment_id":"<sys_id>","message":"Request completed successfully.","status":"success"}

PDFGenerationAPI – fillDocumentFieldsAndFlatten(Object fieldsMap, String sysId, String tableName, String tableSysId, String pdfName, Object flatten)

Fills fields in an editable PDF, flattens the data fields, and attaches it to the provided record.

Use the following methods to determine if the PDF is fillable and get field information:
PDFGenerationAPI provides additional fill methods with different options:

Example

The following example shows how to fill fields and flatten an editable PDF.

var fieldMap = new Object();
fieldMap["Last Name First Name Middle Initial"] = "Tuter Abel E.";
fieldMap["Date of Birth"] = "08101952";
fieldMap["US SSN"] = "111-22-9999";
fieldMap["Address"] = "PO Box 344";
fieldMap["City"] = "Jerome";
fieldMap["State"] = "AZ";
fieldMap["Zip"] = "86331";

var flatten = new Object();
flatten["FlattenType"] = "partially_flatten";

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;
var result = v.fillDocumentFieldsAndFlatten(fieldMap, "<attachmentSysId>", "<tableName>", "<tableSysId>", "pdfName", flatten);
gs.info(JSON.stringify(result));

Output:

"attachment_id":"<sys_id>","message":"Request completed successfully.","status":"success"

PDFGenerationAPI – fillFieldsAndMergeSignature(Object fieldsMap, String sysId, String tableName, String tableSysId, String pdfName, PdfMergeSignRequestor requestor, Object flatten)

Fills fields in an editable PDF, adds signature image, flattens the data fields, and attaches it to the provided record.

Use the following methods to determine if the PDF is fillable and get field information:
PDFGenerationAPI provides additional fill methods with different options:

Example

The following example shows how to fill fields with signature with default settings to completely flatten the fields.

var fieldMap = new Object();
fieldMap["Address_Salutation"] = "Address value here";

var paramMap = new Object();
paramMap["FlattenType"] = "partially_flatten";

var requestor = new sn_pdfgeneratorutils.PdfMergeSignRequestor;
requestor.createRequest("<attachmentSysId>", "incident", "<tableSysId>", "filledPdf");
requestor.addSignatureMapping(6, 40, 50, 188, 44, "<signatureSysId>");

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;
var result = v.fillFieldsAndMergeSignature(fieldMap, "<attachmentSysId>", "incident", "<tableSysId>", requestor, "filledPdf", paramMap);
gs.info(JSON.stringify(result));
Output:
{"attachment_id":"5440d993dbed3010d66be1191396194e","message":"Request completed successfully.","status":"success"}

PDFGenerationAPI – getDocumentFields(String sysId)

Gets a list of editable fields in a PDF document. Enables listing editable PDF fields without manually opening the file to check.

Table 16. Parameters
Name Type Description
sysId String Sys_id of a PDF in the Attachments [sys_attachment] table.

Example

The following example shows how to retrieve fields in a PDF attachment.

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;
var result = v.getDocumentFields("attachmentSysId");
gs.info(JSON.stringify(result));

Output:

{"message":"Request completed successfully.","fields":["NP_formFillable","reset","print","1SSN","Signature.1","5sigDate","Check Box21"],"status":"success"}

PDFGenerationAPI – getDocumentFieldsType(String sysId)

Gets the field type of set of editable fields from a PDF document.

Table 18. Parameters
Name Type Description
sysId String Sys_id of a PDF in the Attachments [sys_attachment] table.

Example

The following example shows how to retrieve field types in a PDF attachment. Results include manual returns for readability and are truncated for brevity.

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;
var result = v.getDocumentFieldsType("<attachmentSysId>");
gs.info(JSON.stringify(result));

Output:

{"fields_type":{"1ADDLINE2.25":{"pageNumber":2,"type":"text"},"1ADDLINE2.24":{"pageNumber":2,"type":"text"},
"1ADDLINE2.23":{"pageNumber":2,"type":"text"},"1ADDLINE2.22":{"pageNumber":2,"type":"text"},
"1ADDLINE2.11":{"pageNumber":2,"type":"text"},
"Check Box1":{"fieldsDetails":[{"fieldName":"Yes"}],"pageNumber":2,"type":"check_box"},
"4consentDate.6":{"pageNumber":4,"type":"text"},"4consentDate.7":{"pageNumber":4,"type":"text"},
"3SSN.9":{"pageNumber":3,"type":"text"},"3SSN.8":{"pageNumber":3,"type":"text"},"3SSN.7":{"pageNumber":3,"type":"text"},
"pageNumber":2,"type":"check_box"},"Check Box8":{"fieldsDetails":[{"fieldName":"Off"},{"fieldName":"yes"}],
"4planAdminDate.8":{"pageNumber":4,"type":"text"},"4planAdminDate.7":{"pageNumber":4,"type":"text"},
"1FirstName_ID.7":{"pageNumber":2,"type":"text"},
"Check Box9":{"fieldsDetails":[{"fieldName":"Yes"}],"pageNumber":3,"type":"check_box"},
"1LN.1":{"pageNumber":2,"type":"text"},"1LN.2":{"pageNumber":2,"type":"text"},
"Check Box11":{"fieldsDetails":[{"fieldName":"Yes"}],"pageNumber":3,"type":"check_box"},
"1LN.9":{"pageNumber":2,"type":"text"},
"Check Box17":{"fieldsDetails":[{"fieldName":"Yes"}],"pageNumber":3,"type":"check_box"},
"Check Box16":{"fieldsDetails":[{"fieldName":"Yes"}],"pageNumber":3,"type":"check_box"},
"1LN.7":{"pageNumber":2,"type":"text"},"Check Box19":{"fieldsDetails":[{"fieldName":"Yes"}],
"1LN.8":{"pageNumber":2,"type":"text"},"Check Box18":{"fieldsDetails":[{"fieldName":"Yes"}],
"print":{"pageNumber":2,"type":"push_button"},"4planAdministrator.1":{"pageNumber":4,"type":"text"},
"1TaxID.9":{"pageNumber":2,"type":"text"},"4SSN.1":{"pageNumber":3,"type":"text"},"4SSN.2":{"pageNumber":3,"type":"text"},
"Signature.1":{"pageNumber":4,"type":"text"},"1ZIP.2":{"pageNumber":2,"type":"text"},"1ZIP.3":{"pageNumber":2,"type":"text"},
"message":"Request completed successfully.","status":"success"}

PDFGenerationAPI – getFilledDocumentWithSignatureAsBase64(Object fieldsMap, String sysId, PdfMergeSignRequestor requestor, Object flatten)

Fills fields in an editable PDF, creates an image, and converts it to a Base64-encoded PDF.

Base64 encoding enables you to output a PDF as a string within a text document, such as HTML or JSON, without damaging the binary character syntax.

Use the following methods to determine if the PDF is fillable and get field information:
PDFGenerationAPI provides additional fill methods with different options:
Table 21. Returns
Type Description
String If successful, PDF converted to Base64 format is added to the Attachments table [sys_attachment]. Contents reflect the PDF attachment provided with fields and signature filled. The fields are not editable unless an alternative flattening option was provided with the flatten parameter.
<Object>.message Message confirming success or error.
Valid values:
  • Exception while reading Source document contents. PDF header not found. – Input attachment provided is not a valid PDF. Provide the correct attachment sys_id.
  • Given target record [<tableName> - <targetTableSysId>] does not exist. – Target table sys_id is not in the table provided. Make sure you include the correct table name for the record.
  • No Form associated with pdf to fill. attachmentSysId: <sys_id>
  • No editable fields exist with specified names. Please check and try again. field names: <field names>
  • Request cannot proceed as the attachment with sys_id [{0}] did not pass security scan – The PDF did not pass the antivirus scan.
  • Request cannot proceed as the attachment with sys_id [{0}] is pending security scan – The PDF requires an antivirus scan.
  • Request completed successfully – Operation is successful.
  • Undefined – Sys_id provided does not exist or is not a PDF attachment.

Data type: String

<Object>.status Status indicating whether the operation is successful.
Possible values:
  • success - Operation was successful.
  • failure – Operation was not successful. The message provides details.

Data type: String

Example

The following example shows how to load two fields in a PDF attachment, flatten the fields, and convert the PDF to Base64 format.

var mymap = new Object();
mymap["City"] = "City value here";
mymap["State"] = "XX";

// create a requestor
var requestor = new sn_pdfgeneratorutils.PdfMergeSignRequestor;
requestor.createRequest("<sys_id>", "tableName", "<tableSysId>", "pdfName");
requestor.addSignatureMapping(6, 40, 50, 188, 44, "<signImgSysId>");
var processedRequestObj = requestor.processRequest();

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;

var result = v.getFilledDocumentWithSignatureAsBase64(mymap, "<attachmentSysId>", processedRequestObj);
gs.info (JSON.stringify(result));

PDFGenerationAPI – getPdfPageSizes(String sysId)

Gets the page size of a PDF document.

Table 22. Parameters
Name Type Description
sysId String Sys_id of a PDF in the Attachments [sys_attachment] table.

Example

The following example shows how to display the width and height of each page in a PDF attachment.

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;
var result = v.getPdfPageSizes ("<attachmentSysId>");
gs.info(JSON.stringify(result));

Output:

{"pages_size":{"1":[612,792],"2":[612,792],"3":[612,792],"4":[612,792],"5":[612,792]},"message":"Request completed successfully.","status":"success"}

PDFGenerationAPI – isDocumentFillable(String sysId)

Checks if the PDF document contains editable fields.

Table 24. Parameters
Name Type Description
sysId String Sys_id of a PDF in the Attachments [sys_attachment] table.

Example

The following example shows how to determine if PDF document fields are editable.

var v = new sn_pdfgeneratorutils.PDFGenerationAPI;
var result = v.isDocumentFillable("<attachmentSysId>");
gs.info(JSON.stringify(result));

Output:

{"message":"Request completed successfully.","document_editable":"true","status":"success"}

PDFGenerationAPI – redact(Object inputJson)

Applies redaction to a PDF document based on the given rectangle coordinates, search keywords, or both. A redacted copy of the original PDF is generated in the Attachments [sys_attachment] table.

Note:
  • Redaction results might include an unexpected white redacted text block that overwrites text not intended to be redacted. If this event occurs, you can manually select the content for redaction using the highlightedSections property or the PDF Generation Utilities plugin. For more information, see Redact data from documents.
  • This method doesn’t support redaction in PDFs containing JBIG2 images.

Example

The following example shows how to redact by rectangle and key word. On the redacted PDF, the areas selected on page 2 are blocked out. The string '23' is redacted on any page that it's found on.

var pdfRequest = {
  sysId: 'e4b3ae35fc128210f877789781ea59f3',
  highlightedSections: [
    {
      "pageNumber": 2,
      "x": 261.75,
      "y": 480,
      "width": 21,
      "height": 14.25
    },
    {
      "pageNumber": 2,
      "x": 249,
      "y": 390.75,
      "width": 63.75,
      "height": 15.75
    }
    // Add more coordinates as needed
  ],
  searchedKeywords: ['23']
};

// Convert the JSON object to a string
var jsonRequest = JSON.stringify(pdfRequest);
gs.info('JSON Request: ' + jsonRequest + '\n');

var PDFRedaction = new sn_pdfgeneratorutils.PDFGenerationAPI;
var result = PDFRedaction.redact(jsonRequest);
gs.info(JSON.stringify(result));

Output:

JSON Request: {"sysId":"e4b3ae35fc128210f877789781ea59f3","highlightedSections":[{"pageNumber":2,"x":261.75,"y":480,"width":21,"height":14.25},{"pageNumber":2,"x":249,"y":390.75,"width":63.75,"height":15.75}],"searchedKeywords":[23]}

{"attachment_id":"1744ae35fc128210f877789781ea59fc","message":"Request completed successfully.","status":"success"}