How to auto-download record PDF file to user's local PC after record insert/update?

Aki18
Tera Contributor

When an user insert or update the record, I would like the browser to automatically download the record as PDF to the user's local PC.

Of course I understand that the user can download the record manually from the form context menu, but I need to automate it.

I think some logics are needed in Business Rule, but could someone please advise me on what kind of script can achieve this?

 

Aki18_0-1688452214351.png

 

Best Regards,

Aki

1 ACCEPTED SOLUTION

All methods presented in this thread seem to be over complicated...

You need two new scripts:

1.) A new Business Rule:
Name: Set PDF Export
Table: Incident/Requested Item/wherever the export should happen
When: before
Advanced: true
Filter Conditions: <this should reflect whenever a pdf should be exported>
Insert: True
Update: True
Condition: gs.isInteractive()

Script:

 

(function executeRule(current, previous /*null when async*/) {

	var view = gs.action.getGlideURI().get('sysparm_view');
	gs.getUser().savePreference('onetime_export_pdf', JSON.stringify({
		table: current.getRecordClassName(),
		sys_id: current.getUniqueValue(),
		view: view,
		domain: current.getValue('sys_domain')
	})); 

})(current, previous);

 

2.) A new UI Script (sys_ui_script.do):
API Name: AutoExport PDF
UI Type: Desktop
Global: True
Script:

 

addAfterPageLoadedEvent(function () {
	var exportPDF = getPreference('onetime_export_pdf');
	if (exportPDF) {
		try {
			var pdfData = JSON.parse(exportPDF);
			if (pdfData.table && pdfData.sys_id) {
				var isLandscape = true;
				exportToPDF(pdfData.table, pdfData.sys_id, isLandscape, pdfData.view, pdfData.domain);
			}
		} catch (e) {

		} finally {
			setPreference('onetime_export_pdf', '');
		}
	}
});

 


The idea is that the business rule sets a "one time" user preference that a certain record shall be exported to PDF.

Whenever the user loads the page the next time, this user preference is checked and the PDF is exported. After the export the User Preference is cleared ("one time" export only).

 

If this solves your issue, a "Helpful + Mark Answer as Solution" is highly appreciated 🙂

View solution in original post

17 REPLIES 17

Don't modify the OOB UI Actions, you can disable the OOB UI Actions and use Insert and Stay to create a custom copy. Then activate the custom one and make modifications.

If your UI Actions are global and not on your specific table. You can override a UI Action for the child table. This will be a more simple approach.

Override a UI action for an extended table 

 

Also please check the below community post.

How to script a Pdf Form export 

 

Please mark the response as correct and helpful to make future seekers job easy 🙂

 

Thanks

Air

Aki18
Tera Contributor

Hi @AirSquire ,

Thank you for the reply. Well, the OOTB UI Actions such as "Update", "Save", etc. are server-side, correct? Then, will it work if I add the script you suggested which is client-side?

Riya Verma
Kilo Sage
Kilo Sage

Hi @Aki18 ,

Hope you are doing great.

 

To achieve the automatic download of a record as a PDF file to the user's local PC after a record insert or update in ServiceNow, we can implement a solution using a Business Rule with appropriate scripting.

  1.  Create a Business Rule
  2. Define the Business Rule Conditions --> Set the "When to run" field to "Before" to trigger the rule before the record is inserted or updated.
  3. In the "Advanced" section, specify the "Current" field as true to execute the Business Rule only for the current record being inserted or updated.
  4. Add the below reference script The script will generate the PDF and trigger the automatic download for the user. We'll use the GlideSysAttachment API to create the PDF and the GlideSysAttachment.get function to get the attachment's content

 

(function executeRule(current, previous /*, gs*/) {
  
    // Generate the PDF content (Replace "table_name" with the actual table name)
    var pdfContent = "<h1>PDF Content for Record: " + current.number + "</h1>";

    // Create the PDF as an attachment
    var pdfAttachment = new GlideSysAttachment();
    var pdfName = "Record_" + current.number + ".pdf"; // Customize the PDF name as needed
    pdfAttachment.write("table_name", current.sys_id, pdfName, "application/pdf", pdfContent);

    // Get the attachment content
    var attachmentContent = pdfAttachment.get(current.sys_id);
    if (attachmentContent) {
      // Set response headers for automatic download
      gs.getResponse().setHeader('Content-Disposition', 'attachment; filename=' + pdfName);
      gs.getResponse().setContentType('application/pdf');

      // Write the attachment content to the response
      gs.getResponse().write(attachmentContent);
    }
  
})(current, previous);

 

 
Please mark the appropriate response as correct answer and helpful, This may help other community users to follow correct solution.
Regards,
Riya Verma

Aki18
Tera Contributor

Hi @Riya Verma ,

Thank yo so much for the script! I created the Business Rule as per your instruction and updated the target record, but the following error showed up and the auto-download didn't work... Can you please debug this?

Error running business rule 'Test auto-download' on sc_req_item: RITM0020387, exception: org.mozilla.javascript.EvaluatorException: Can't find method com.glide.ui.SysAttachment.write(string,java.lang.String,org.mozilla.javascript.ConsString,string,org.mozilla.javascript.ConsString). (sys_script.e36ca7f9db33e5d05ed46b4b139619b4.script; line 9)

Aki18
Tera Contributor

Hi @Riya Verma ,

Do you have any ideas on this?