Export Excel to PDF with Microsoft.Office.Interop in impersonated context

17 Views Asked by At

I am trying to open and edit an Excel template and then exporting the modified Excel file to a PDF in an impersonated folder with ExportAsFixedFormat method, but It doesn't work:

using Excel = Microsoft.Office.Interop;

...

SafeTokenHandle safeTokenHandle;
        bool returnValue = LogonUser(Datos.DatosConfiguracion.usuario_red, Datos.DatosConfiguracion.dominio_red, Datos.DatosConfiguracion.pass_red,
                                  Datos.DatosConfiguracion.LOGON32_LOGON_INTERACTIVE, Datos.DatosConfiguracion.LOGON32_PROVIDER_DEFAULT,
                                   out safeTokenHandle);
        if (false == returnValue)
        {
            int ret = Marshal.GetLastWin32Error();
            throw new System.ComponentModel.Win32Exception(ret);
        }
        using (safeTokenHandle)
        {
            using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
            {
                using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                {
                    
                    try
                    {
                        // Open and edit Excel file...

                        // Export as PDF                            
                        objLibroExcel.ExportAsFixedFormat(Excel.Excel.XlFixedFormatType.xlTypePDF, ruta_pdf);
                        objLibroExcel.Close(false);
                    }
                    catch (Exception ex)
                    {
                        ...
                    }
                }
            }
        }

ruta_pdf is a string with the file path (something like C:\impersonated_folder\pdf_file.pdf)

excuting objLibroExcel.ExportAsFixedFormat(Excel.Excel.XlFixedFormatType.xlTypePDF, ruta_pdf); I get the Exception:

Message: The document has not been saved. It may be open or an error occurred while saving.

Source: Microsoft Excel

StackTrace: at Microsoft.Office.Interop.Excel._Workbook.ExportAsFixedFormat(XlFixedFormatType Type, Object Filename, Object Quality, Object IncludeDocProperties, Object IgnorePrintAreas, Object From, Object To, Object OpenAfterPublish, Object FixedFormatExtClassPtr) at NC2017.frmNC.PDFGenerator(NC my_nc) in C:\Users\my_user\Repository GitLab\NC2017\NC2017\frmNC.cs:line 1715

When I use the method but not in a impersonated context, it works.

The exception message I think is quite general, and could be about an access denied problem, that I don't understand because I try to do it inside the impersonated context where I can open and edit the excel document without problem but just the export is where it fails.

I have check many threads in stackoverflow about export Excel documents, but I couldn't find anything in impersonated contexts.

¿Any idea? Thanks!

0

There are 0 best solutions below