Skip to content
  • Services
  • Solutions
  • Articles
  • Careers
  • Contact
Software, Technology

Unleashing the Power of PDFGeneration in ServiceNow

January 3, 2025 info@nowcompiler.com No comments yet

Introduction: Automated Reporting

Ever found yourself drowning in manual paperwork, wishing there was a smarter way to generatereports? Welcome to the world of ServiceNow PDF generation, where automation meetsprecision!Imagine transforming complex data into sleek, professional PDFs with just a few lines of code.Sounds like a developer’s dream, right? In this blog post, we’ll demystify the process of creatingdynamic PDFs that can revolutionize how you handle documentation in ServiceNow.

The Beginning: Setting Up Your Project

Before diving into the code, let’s walk through the setup process. Think of this as preparing yourcanvas before painting a masterpiece.

Step 1: Project Creation

  • Open ServiceNow
  • Create a new project (Pro tip: Choose a name that speaks to your project’s purpose!)
  • Get ready to transform your workflow

Step 2: Event Registry

Navigate to the Event Registry and create a new event. This is where the magic starts brewing!

Crafting Your PDF Generation Strategy

Email Notifications: Your Communication Backbone

Email notifications are the backbone of your automated reporting workflow. When you start in
ServiceNow, you’ll want to carefully navigate to the Event Registry and locate the Email –
Notifications section. This is where you’ll set up two key notifications that will power your PDF
generation.

Notification A: Trigger the initial report generation
The first notification (Notification A) acts as the primary trigger for your project report. It connects
directly with your project management system, initiating the report generation process.

Notification B: Handle follow-up communications
The second notification (Notification B) handles follow-up communications, ensuring that team
members stay informed throughout the project lifecycle.

  • When setting up these notifications, pay close attention to your project table selection. By
    targeting the specific pm_project table, you create a direct link between your project data and
    the reporting system.
  • One helpful tip is to use Excel files for data input—ServiceNow can easily convert these to
    HTML templates, making your data transformation smooth and efficient.
  • Further after creating the notification you’ll need to add the details of sender and receiver. Alsoadding a message of what you want to receive or send.


Custom Fields and Date Configuration

Custom fields are crucial for creating meaningful, project-specific reports. They allow you to tailor
your PDF to your organization’s unique needs. Think of them as the specific details that make
your report more than just a generic document.

Date configuration is more than just adding dates to a report. It’s about providing context. Include
key dates like project start, expected completion, and important milestones. The right date
formatting can quickly communicate your project’s status and progress.

UI Action Configuration

UI actions are powerful tools that automate complex processes with a single click. Located in the
Additional Actions menu, these actions can significantly reduce manual work and streamline your
workflow.

The key is to design UI actions that are both powerful and intuitive. Consider who will use the
action, what specific process it improves, and how it fits into your overall workflow.

Creating Effective UI Actions

When creating a UI action, start by clearly defining its purpose. Ask yourself:

  • What specific workflow am I improving?
  • Who will use this action?
  • What outcomes do I expect?

Configuration requires careful thought. Select the right table, set up conditional logic, and define
clear visibility rules. The goal is to create an action that is both powerful and easy to use.

The Heart of Operation: Code Breakdown

Let’s dive into the code that makes this all possible. We’ll break down each section like a skilled
mechanic dismantling an engine.

The Code

var firstName = current.getDisplayValue('u_first_name');
var lastName = current.getDisplayValue('u_last_name');
var email = current.getDisplayValue('u_email');
var contact = current.getDisplayValue('u_contact');
var address = current.getDisplayValue('u_address');
var html, updatedHtml;
var tableName = current.sys_class_name;
var targetTableSysId = current.sys_id;
var fileName = current.getDisplayValue('number');
var notificationName = 'NowCompilerReport';
var hfInfo = {
  "HeaderImageAlignment": "left",
  "FooterImageAlignment": "TOP_CENTER",
  "FooterText": "Now Compiler Footer",
  "PageSize": "A4",
  "PageOrientation": "LANDSCAPE",
  "GeneratePageNumber": "false",
  "TopOrBottomMargin": "36",
  "LeftOrRightMargin": "52"
};
// Retrieve the notification record
var notificationGR = new GlideRecord('sysevent_email_action');
notificationGR.addQuery('name', notificationName);
notificationGR.query();
if (notificationGR.next()) {
  html = notificationGR.message_html;
  gs.info("Retrieved HTML Content: " + html);
} else {
  gs.error("Notification not found: " + notificationName);
  // Exit if the notification doesn't exist
}
// Replace placeholders in the HTML
updatedHtml = html.replace('u_first_name', firstName)
  .replace('u_last_name', lastName)
  .replace('u_email', email)
  .replace('u_contact', contact)
  .replace('u_address', address);
// Initialize PDF generation utility
var pdfGenerator = new sn_pdfgeneratorutils.PDFGenerationAPI();
try {
  // Generate the PDF
  var result = pdfGenerator.convertToPDFWithHeaderFooter(updatedHtml,
tableName, targetTableSysId, fileName, hfInfo);
  gs.info("PDF Generation Result: " + JSON.stringify(result));
} catch (error) {
  gs.error("PDF Generation Error: " + error.message);
}
// Update the current record
current.update();
// Queue an event for further processing
gs.eventQueue('NowCompiler.report', current, current.project_manager);

User Data Extraction

var firstName = current.getDisplayValue('u_first_name');
var lastName = current.getDisplayValue('u_last_name');
var email = current.getDisplayValue('u_email');

These lines are your data hunters, retrieving specific user information from the current record. These variables store the display values of user-specific fields from the current record. They will be used to replace placeholders in the HTML template.

HTML and PDF Configuration

var hfInfo = {
  "HeaderImageAlignment": "left",
  "FooterImageAlignment": "TOP_CENTER",
  "FooterText": "Now Compiler Footer",
  "PageSize": "A4",
  "PageOrientation": "LANDSCAPE"
  // … other configurations
};

These variables are used to store information needed for generating the PDF. HTML will hold the
original HTML content, updatedHtml will hold the modified content, and hfInfocontains header
and footer settings for the PDF.

Magic Moment: This configuration is where you customize your PDF’s look and feel. Want a
landscape orientation? Check. Need a specific footer? You got it!

Retrieve Notification Record

var notificationGR = new GlideRecord('sysevent_email_action');
notificationGR.addQuery('name', notificationName);
notificationGR.query();
if (notificationGR.next()) {
  html = notificationGR.message_html;
  gs.info("Retrieved HTML Content: " + html);
} else {
  gs.error("Notification not found: " + notificationName);
  return; // Exit if the notification doesn't exist
}

This block retrieves the HTML content from the specified notification record. If the notification is found, the HTML content is stored in the html variable. If not, an error is logged, and the script exits.

Replace Placeholders in HTML

updatedHtml = html.replace('u_first_name', firstName)
  .replace('u_last_name', lastName)
  .replace('u_email', email)
  .replace('u_contact', contact)
  .replace('u_address', address);

This block replaces placeholders in the HTML content with actual values from the current record. The updated Html variable now contains the modified HTML content with user-specific details.

The PDF Generation

var pdfGenerator = new sn_pdfgeneratorutils.PDFGenerationAPI();
try {
  var result = pdfGenerator.convertToPDFWithHeaderFooter(
    updatedHtml,
    tableName,
    targetTableSysId,
    fileName,
    hfInfo
  );
} catch (error) {
  gs.error("PDF Generation Error: " + error.message);
}

This code snippet is your PDF creation wizard. It takes your carefully crafted HTML, initialises the
PDF generation utility and attempts to generate the PDF. If successful, the result is logged. If an
error occurs, it is caught and logged.

Update Current Record and Queue Event

current.update();
gs.eventQueue('NowCompiler.report', current, current.project_manager);

Generating and Downloading Your Report

Just click the “Now Compiler Generate Report PDF” link, and voilà! Your perfectly formatted PDF
is ready for download.

Troubleshooting: When Things Don’t Go as Planned

Common Pitfalls and Fixes

  1. Notification Not Found: Double-check your notification name
  2. HTML Placeholder Mismatch: Ensure your placeholders match exactly
  3. PDF Generation Errors: Check your HTML structure and configuration

Outline

Conclusion

You’ve just unlocked a powerful automation technique in ServiceNow. No more manual report
generation, no more formatting headaches. With these skills, you’re not just a developer – you’re
a workflow optimization superhero!
Happy coding, and may your PDFs be ever elegant!

info@nowcompiler.com

Post navigation

Previous
Next

Search

Categories

  • Insights 3
  • Marketing 2
  • Software 2
  • Technology 5

Recent posts

  • Agentic AI in ServiceNow: The Future of Intelligent Enterprise Automation
  • Release Management and Deployment in ServiceNow: Best Practices
  • Strategic Planning in SPM

Tags

aes App Engine studio Creative creator studio Enterprise Internet Javascript NowCompiler PDF ServiceNow studio

Related posts

Software, Technology

Future of ServiceNow App Engine Studio and the role of ServiceNow Studio, & Creator Studio

January 29, 2025 info@nowcompiler.com No comments yet

In today’s rapidly evolving digital landscape, organizations face mounting pressure to adapt quickly to market changes while simultaneously addressing internal process challenges. This dynamic environment has sparked a revolution in how applications are developed and maintained within the ServiceNow ecosystem, leading to the emergence of multiple development platforms: ServiceNow Studio, App Engine Studio (AES), Creator […]

Where
innovation meets implementation.

Company
  • About Us
  • Careers
  • Our Work
  • Articles
Resources
  • Twitter
  • LinkedIn
  • YouTube
Services
  • Implementation Solutions
  • Managed Support Services
  • Application Development
Want to receive news and updates?


    © Now Compiler. All Rights Reserved.

    • Privacy Policy