How to retrieve Binary PDF file from REST API File response.

harshitjamw
Tera Contributor

Hi Everyone,
I am calling a third-party API that returns a PDF file in the response. I need to attach this binary PDF file to a RITM record. Below is my code — it creates the attachment, but the file content is not being added correctly.

(function execute(inputs, outputs) {
var caseNumber = inputs.casenumber;
var language = 'english'; // Default language
var endPoint = gs.getProperty('baseURL') + '/case/' + caseNumber + '/notice?language=' + language;

try {
var request = new sn_ws.RESTMessageV2();
request.setHttpMethod('GET');
request.setEndpoint(endPoint);
request.setRequestHeader('Accept', 'application/pdf');
request.setRequestHeader('Authorization', 'Bearer ' + inputs.access_token);

var response = request.execute();
var httpResponseStatus = response.getStatusCode();

if (httpResponseStatus === 200) {
var inputStream = response.getBinaryResponseStream();
var gr = new GlideRecord('sc_req_item');
if (gr.get(inputs.requested_item)) {
var attachment = new GlideSysAttachment();
var attachmentSysId = attachment.write(gr, 'Further_Action_Notice.pdf', 'application/pdf', inputStream);

if (attachmentSysId) {
gs.info(':white_check_mark: FAN PDF attached successfully to RITM: ' + gr.number);
outputs.response = 'PDF attached successfully';
} else {
gs.error(':x: Failed to write PDF attachment');
outputs.response = 'Attachment write failed';
}
} else {
gs.error(':x: Requested item not found: ' + inputs.requested_item);
outputs.response = 'Requested item not found';
}
} else {
gs.error(':x: PDF fetch failed. Status: ' + httpResponseStatus + ', Body: ' + response.getBody());
outputs.response = 'Failed to retrieve PDF. Status: ' + httpResponseStatus;
}
} catch (ex) {
gs.error(':x: Exception occurred: ' + ex.getMessage());
outputs.response = 'Exception: ' + ex.getMessage();
}

})(inputs, outputs);
2 REPLIES 2

palanikumar
Mega Sage

Hi,

 

Check whether the script shared in this thread is useful. Use the base64EncodedData to GlideAttachment and see whether PDF is created properly

https://www.servicenow.com/community/developer-forum/attachments-api-converting-binary-files-to-base...

 

Thank you,
Palani

Ankur Bawiskar
Tera Patron
Tera Patron

@harshitjamw 

the write method takes content, but you are possibly getting content stream

check this link

Attachment API GET Convert Binary String to File Attachment 

Also check and try to use writeContentStream() method

AnkurBawiskar_0-1749548745306.png

 

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