PDF generation from record

rah dev
Tera Contributor

Hi community, good day,
I am working on a requirement.
On the incident table, I need a button so that when I click that button, the record gets downloaded in PDF format. But this is not happening.
I am using this approach...

rahdev_0-1759410201707.png

rahdev_1-1759410231869.png

function onClickGeneratePDF() {
    var ga = new GlideAjax('global.IncidentPDFGenerator');
    ga.addParam('sysparm_name', 'generatePDF');
    ga.addParam('sys_id', g_form.getUniqueValue());
    ga.getXMLAnswer(function(response) {
        if (response) {
            window.open(response, "_blank");
        } else {
            alert("Failed to generate PDF.");
        }
    });
}
Script include:
rahdev_2-1759410294207.png
var IncidentPDFGenerator = Class.create();
IncidentPDFGenerator.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    generatePDF: function() {
        var sysId = this.getParameter('sys_id');
        var gr = new GlideRecord('incident');
        if (!gr.get(sysId)) {
            return '';
        }

        // Collect fields
        var number = gr.getValue('number');
        var assignedTo = gr.getDisplayValue('assigned_to');
        var state = gr.getDisplayValue('state');

        // Prepare content (simple text for PDF)
        var content = "Incident Details\n\n";
        content += "Number: " + number + "\n";
        content += "Assigned To: " + assignedTo + "\n";
        content += "State: " + state + "\n";

        // Save as attachment
        var fileName = "Incident_" + number + ".pdf";
        var sa = new GlideSysAttachment();
        var attSysId = sa.write('incident', sysId, fileName, content);

        // Return a download URL
        return gs.getProperty('glide.servlet.uri') + "sys_attachment.do?sys_id=" + attSysId;
    }

});
3 REPLIES 3

Bhuvan
Mega Patron

palanikumar
Giga Sage
Giga Sage

Hi @rah dev ,

There is an default option to generate PDF without script. You can use below UI Action script

function onClickGeneratePDF({
  window.open("/incident.do?PDF&sys_id=" + g_form.getUniqueValue()+ "&sysparm_view=default", "_blank");
}

Note: If you want specific fields to be listed then either use existing view or create a new view with the fields you want in the PDF. Replace default in the above script with the name of the view created

 

Thank you,
Palani

Ankur Bawiskar
Tera Patron
Tera Patron

@rah dev 

you can use the easy approach shared by @palanikumar 

You need not use script include then.

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader