Prevent alert while converting Word to PDF in C#

247 Views Asked by At

I am converting docs in a folder to PDF using the code below

string[] filePaths = Directory.GetFiles(txtFolderPath.Text, "*.doc",
                                          SearchOption.TopDirectoryOnly);
                  foreach (string path in filePaths)
                {
                    Application app = new Application();
                    app.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                    app.Visible = true;

                    var objPresSet = app.Documents;
                    var objPres = objPresSet.Open(path, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
                    var temppath = path;
                    var pdfFileName = Path.ChangeExtension(path, ".pdf");
                    var pdfPath = Path.Combine(Path.GetDirectoryName(path), pdfFileName);

                    try
                    {
                        objPres.ExportAsFixedFormat(
                            pdfPath,
                            WdExportFormat.wdExportFormatPDF,
                            false,
                            WdExportOptimizeFor.wdExportOptimizeForPrint,
                            WdExportRange.wdExportAllDocument
                        );
                    }
                    catch
                    {
                        pdfPath = null;
                    }
                    finally
                    {
                        objPres.Close();                      
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                    }

But for every document I am getting the pop up below eventhough I have set the alerts to none. enter image description here

Since the number of files are huge how can I stop this alert programatically in C#.

1

There are 1 best solutions below

0
On BEST ANSWER

You have to set your second parameter to MsoTriState.msoFalse like so:

var objPres = objPresSet.Open(
                path, 
                MsoTriState.msoFalse /* ConfirmConversions */, 
                MsoTriState.msoTrue, 
                MsoTriState.msoFalse);

because you're looking at the Convert File dialog and the ConfirmConversions controls whether that dialog is thrown in your face or not:

True to display the Convert File dialog box if the file isn't in Microsoft Word format.

This is mentioned in the Documents.Open specification on MSDN.

It looks like not all your *.doc files are actual Word documents, hence the Convert File dialog popping up. I assume Word will throw an exception if its dreamed up conversion (in your example from Rich Text Format) turns out to be wrong, aka not an RTF fileformat.