Convert Word Documents to PDF using CSharp Invoke Code Activity

How to convert Word documents to PDF using CSharp code into Invoke Code Activity?

Issue Description:

Sometimes the process of converting Word documents to PDF using the Save Document as PDF activity from the UiPath.Word.Activities package does not work as expected, causing issues with how the final generated PDF looks. Most of the time, this is caused due to size, view, layout, or the way the Word document opens.

Solution:

To overcome these issues, and prevent the changes in the document appearance, use a C# code while using the Invoke Code activity from the UiPath.System.Activities package. Find below the necessary steps for implementation.

Notes:

The below implementation is just an example and something that can be used as a proof of concept, the final implementation needs to be done by the final user or developer.

To run this automation in unattended mode, make sure to not disconnect from the VDI, instead, sign out from the robot user session.

1. Drag and drop an Invoke Code activity as shown below.

2. Once the activity is in place, add the below CSharp code. Make sure that the Language is set to CSharp in the Language input section of the activity Properties panel.

try
{
    // Path of the word document to be converted
    string yourDoc = InputWordPath;
// Create a new Microsoft Word application object
var appWord = new Microsoft.Office.Interop.Word.Application();

// Check if documents are present in the Word application
if (appWord.Documents != null)
{
    // Open the document
    var wordDocument = appWord.Documents.Open(yourDoc);
    
    // Activate the document
    wordDocument.Activate(); 
    
    // Maximizes the window of the Word application
    wordDocument.Application.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateMaximize;
    
    // Path of the pdf document to be created
    string pdfDocName = OutputPDFPath;
    
    // Check if word document was opened successfully
    if (wordDocument != null)
    {
        // Export the document as PDF
        wordDocument.ExportAsFixedFormat(pdfDocName, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
        
        // Close the word document
        wordDocument.Close();
    }  
}

// Quit the Word application
appWord.Quit();

}
catch (Exception ex)
{
// Write the exception to the console (or handle it in some other way)
Console.WriteLine(ex.Message);
}

Example:


3. Create two variables

in_DOCFilePath it will contain the path of the Docx file

o_PDFFilePath it will contain the path of the generated PDF file

The arguments for the Invoke Code will be InputWordPath and OutputPDFPath

    After this the sample project is ready to run and convert the Word Files to PDF Properly.