How to Merge Multiple PDF Attachments into One PDF?

longct10
Tera Contributor

The Requirement:

When a user submits a Catalog Item, the system needs to:

  • Retrieve all PDF attachments associated with the request.
  • Merge them into a single PDF document.
  • Preserve the original content, formatting, and page structure.
  • Attach the final merged PDF back to the ServiceNow record.
2 REPLIES 2

longct10
Tera Contributor

After investigating the requirement, I identified two possible implementation approaches:

Approach 1: Using an External PDF Merge API

Integrate ServiceNow with an external PDF processing service through REST API.

Implementation flow:

  1. Retrieve PDF attachments from ServiceNow (sys_attachment).

  2. Convert attachment content into Base64 or binary data.

  3. Send the files to the PDF Merge API.

  4. Receive the merged PDF response.

  5. Create a new attachment in ServiceNow using GlideSysAttachment.

Advantages:

  • Easier PDF processing.

  • Better support for different PDF formats.

  • Less custom PDF-processing logic inside ServiceNow.

Considerations:

  • External service dependency.

  • API costs and availability.

  • Data confidentiality and security.

  • Network and payload size limitations.

 Must check the security when using API

var PdfAttachmentMerger = Class.create();

PdfAttachmentMerger.prototype = {

    initialize: function() {},

    merge: function(targetSysId) {

        try {

            // 1. Get RITM
            var targetGr = new GlideRecord('sc_req_item');

            if (!targetGr.get(targetSysId)) {
                throw new Error('RITM not found');
            }

            var targetTable = 'sc_req_item';

            var gsa = new GlideSysAttachment();
            var base64Files = [];

            // 2. Query all PDF attachments
            var attGr = new GlideRecord('sys_attachment');

            attGr.addQuery('table_name', targetTable);
            attGr.addQuery('table_sys_id', targetSysId);
            attGr.addQuery('content_type', 'application/pdf');
            attGr.orderBy('sys_created_on');
            attGr.query();

            while (attGr.next()) {

                var fileName = attGr.getValue('file_name');

                // Avoid merging previously generated files
                if (/_mergeFile\.pdf$/i.test(fileName)) {
                    continue;
                }

                var bytes = gsa.getBytes(attGr);

                if (!bytes || bytes.length === 0) {
                    gs.warn('Skipping empty PDF: ' + fileName);
                    continue;
                }

                base64Files.push(
                    GlideStringUtil.base64Encode(bytes)
                );

                gs.info('Loaded PDF: ' + fileName);
            }

            // 3. Validate PDF count
            if (base64Files.length < 2) {
                throw new Error(
                    'At least 2 PDF attachments are required'
                );
            }

            if (base64Files.length > 20) {
                throw new Error(
                    'Maximum 20 PDF files per request'
                );
            }

            // 4. Call pdfia API
            var request = new sn_ws.RESTMessageV2();

            request.setEndpoint(
                'https://pdfia.com/api/v1/merge'
            );

            request.setHttpMethod('POST');

            request.setRequestHeader(
                'Content-Type',
                'application/json'
            );

            request.setHttpTimeout(120000);

            request.setRequestBody(
                JSON.stringify({
                    files: base64Files
                })
            );

            var response = request.execute();

            if (response.getStatusCode() !== 200) {
                throw new Error(
                    'PDF API error: ' +
                    response.getStatusCode() +
                    ' - ' + response.getBody()
                );
            }

            // 5. Decode response
            var apiResult = JSON.parse(response.getBody());

            if (!apiResult.file) {
                throw new Error('Merged PDF not returned');
            }

            var mergedBytes =
                GlideStringUtil.base64DecodeAsBytes(
                    apiResult.file
                );

            if (!mergedBytes || mergedBytes.length === 0) {
                throw new Error('Merged PDF is empty');
            }

            // 6. Generate output filename
            var currentDate = new GlideDateTime();

            var outputFileName =
                currentDate.getDate() + '_mergeFile.pdf';

            // 7. Delete previous output with same name
            var oldAtt = new GlideRecord('sys_attachment');

            oldAtt.addQuery('table_name', targetTable);
            oldAtt.addQuery('table_sys_id', targetSysId);
            oldAtt.addQuery('file_name', outputFileName);
            oldAtt.query();

            while (oldAtt.next()) {
                oldAtt.deleteRecord();
            }

            // 8. Save merged PDF
            var newAttachmentId = gsa.write(
                targetGr,
                outputFileName,
                'application/pdf',
                mergedBytes
            );

            if (!newAttachmentId) {
                throw new Error('Failed to save merged PDF');
            }

            gs.info(
                'PDF MERGE SUCCESS: ' + newAttachmentId
            );

            return newAttachmentId;

        } catch (ex) {

            gs.error(
                'PDF MERGE FAILED: ' + ex.message
            );

            return false;
        }
    },

    type: 'PdfAttachmentMerger'
};

longct10
Tera Contributor

Approach 2: Building a Custom Script Include

Develop a reusable Script Include to handle PDF merging directly within the ServiceNow instance.

Implementation flow:

  1. Query PDF attachments from sys_attachment.

  2. Retrieve attachment content using GlideSysAttachment.

  3. Process and merge PDF documents using available server-side capabilities.

  4. Generate the final PDF.

  5. Save the merged document back to the target record.

Advantages:

  • No dependency on an external PDF processing service.

  • Centralized and reusable implementation.

  • More control over the processing workflow.

Considerations:

  • ServiceNow server-side JavaScript limitations.

  • Availability and compatibility of PDF-processing libraries.

  • Memory and processing limitations for large documents.

  • Preserving original PDF structure and formatting.