Convert HTML to Docx file

Hai Long Do
Tera Contributor

Hi,

Do anyone know how to convert HTML body to Docx file type in ServiceNow?

3 REPLIES 3

Samaksh Wani
Giga Sage

Hello @Hai Long Do 

 

You need to create a UI Action and add the below script in it.

 

function createDoc() {  
  var sysparm_table = g_form.getTableName();  
  var sysparm_sys_id = g_form.getUniqueValue().toString();  
  var url = sysparm_table + '.do?DOCX&sys_id=' + sysparm_sys_id;  
  window.open(url);  
}  

 

 

 

Plz mark my solution as Accept, If you find it helpful.

 

Regards,

Samaksh

Hi,

This approach does not work for sys_attachment table

Community Alums
Not applicable

Hello @Hai Long Do ,

 

  1. ServiceNow doesn't have a built-in functionality for DOCX conversion. You'll need to leverage external libraries/applications or services capable of converting HTML to DOCX.
  2. Create a script include or use a business rule to invoke an external service/library that performs HTML to DOCX conversion.
  3. Utilize JavaScript or GlideRecord to get the HTML content and pass it to the external service.
    Here's a simplified example using an external API:
    var htmlContent = '<h1>Hello</h1><p>This is a paragraph.</p>'; // Replace with your HTML content
    var apiUrl = 'https://example.com/api/convert'; // Replace with the API endpoint for conversion
    
    var requestBody = {
       html: htmlContent,
       format: 'docx'
    };
    
    var response = gs.submitRESTMessage('POST', apiUrl, JSON.stringify(requestBody));
    var docxContent = response.getBody(); // This will contain the converted DOCX content
    var response = docxContent;
    // Save the DOCX content or further process as needed
    if (response.getStatusCode() === 200) {
       // Extract the converted DOCX file content
       var docxContent = response.getContent();
    
       // Create a new attachment record
       var attachmentRecord = new GlideRecord('sys_attachment');
       attachmentRecord.name = 'converted_document.docx';
       attachmentRecord.content = docxContent;
       attachmentRecord.content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
       attachmentRecord.insert();
    
       // Log the attachment record ID
       gs.log('Converted DOCX attachment ID: ' + attachmentRecord.sys_id);
    } else {
       gs.log('Error converting HTML to DOCX: ' + response.getStatusCode());
    }​
  4. You might integrate with a service like convertapi [WEBSITE LINK], which has APIs for converting HTML to DOCX.

Remember, the exact implementation will depend on the specific requirements, the chosen external service/library, and its API specifications. Also, consider any limitations, such as file complexity of the HTML content, when performing the conversion.

 

If you found this helpful, a 'like' is the secret handshake of appreciation! Accept it as a solution, as it will help others find the correct solution quickly.

- Prasad 😉