欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# convert Word/PPT/Excel to pdf by Microsoft.Office.Interop

程序员文章站 2022-03-18 19:41:23
...
/********************************************************************************
** Company: github
** Auth:    Zhen(Evan)Wang 
** Date:    1/3/2018 1:59:32 PM
** Description:    
** Update Log:Nuget 
Microsoft.Office.Interop.Excel/Microsoft.Office.Interop.Word/Microsoft.Office.Interop.PowerPoint/Microsoft.Office.Core*********************************************************************************/

using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using log4net;




namespace Cortland.PDFService.Common
{
    public class WordToPDFHelper
    {
        private static Word.ApplicationClass MSdoc;
        private static Excel.ApplicationClass MSexcel;
        private static PowerPoint.ApplicationClass MSPowerPoint;
        private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);


        public static bool ConvertOfficeToPDF(string sourceFile, string destnationFile)
        {
            bool isNeedConvert = false;
            if (System.IO.File.Exists(sourceFile))
            {
                FileInfo fileInfo = new FileInfo(sourceFile);
                switch (fileInfo.Extension.ToUpper())
                {
                    case ".DOC":
                    case ".DOCX":
                        isNeedConvert = ConvertWordToPDF(sourceFile, destnationFile);
                        break;
                    case ".PPT":
                    case ".PPTX":
                        isNeedConvert = CovertPowerPointToPDF(sourceFile, destnationFile);
                        break;
                    case ".XLS":
                    case ".XLSX":
                        isNeedConvert = CovertExcelToPDF(sourceFile, destnationFile);
                        break;
                }
            }
            return isNeedConvert;
        }


        private static bool ConvertWordToPDF(object sourceFile, object destinationFile)
        {   //Creating the instance of Word Application   
            bool isSuccess = false;
            object missing = Type.Missing;
            if (MSdoc == null)
            {
                MSdoc = new Word.ApplicationClass();
            }
            try
            {
                MSdoc.Visible = false;
                MSdoc.Documents.Open(ref sourceFile, ref missing,
                     ref missing, ref missing, ref missing,
                     ref missing, ref missing, ref missing,
                     ref missing, ref missing, ref missing,
                     ref missing, ref missing, ref missing, ref missing, ref missing);
                MSdoc.Application.Visible = false;
                MSdoc.WindowState = Word.WdWindowState.wdWindowStateMinimize;


                object format = Word.WdSaveFormat.wdFormatPDF;


                MSdoc.ActiveDocument.SaveAs(ref destinationFile, ref format,
                        ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing,
                       ref missing, ref missing);
                isSuccess = true;
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
            finally
            {
                if (MSdoc != null)
                {
                    MSdoc.Documents.Close(ref missing, ref missing, ref missing);
                    //WordDoc.Application.Quit(ref Unknown, ref Unknown, ref Unknown); 
                }
                // for closing the application
                MSdoc.Quit(ref missing, ref missing, ref missing);
            }


            return isSuccess;
        }


        private static bool CovertExcelToPDF(string excelPath, string pdfPath)
        {
            bool isSuccess = false;
            object missing = Type.Missing;
            Excel.Workbook workBook = null;
            try
            {
                if (MSexcel == null)
                {
                    MSexcel = new Excel.ApplicationClass();
                }
                MSexcel.Visible = false;
                workBook = MSexcel.Workbooks.Open(excelPath, missing, missing, missing, missing, missing,
                                                      missing, missing, missing, missing, missing, missing, missing, missing, missing);
                //open sheet
                //excel.Worksheet ws = (excel.Worksheet)workBook.Worksheets.Item[1];//excel index start with 1
                //print portait
                //ws.PageSetup.Orientation = excel.XlPageOrientation.xlPortrait;
                //excel print setting。Zoom must need to set false
                //ws.PageSetup.Zoom = false;
                //ws.PageSetup.FitToPagesTall = 1;
                //ws.PageSetup.FitToPagesWide = 1;
                //export to pdf
                workBook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, pdfPath
                    , Excel.XlFixedFormatQuality.xlQualityStandard
                    , true
                    , false     //ignore print area
                    , missing, missing, missing, missing);
                isSuccess = true;
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
            finally
            {
                //close workbook
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                //close excel
                if (MSexcel != null)
                {
                    MSexcel.Quit();
                    MSexcel = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }


            return isSuccess;
        }


        private static bool CovertPowerPointToPDF(string pptPath, string pdfPath)
        {
            bool isSuccess = false;
            object missing = Type.Missing;
            PowerPoint.Presentation presentation = null;
            try
            {
                if (MSPowerPoint == null)
                {
                    MSPowerPoint = new PowerPoint.ApplicationClass();
                }
                //MSPowerPoint.Visible = MsoTriState.msoFalse;//this will be throw exception, must use below code to hide ppt window
                presentation = MSPowerPoint.Presentations.Open(pptPath,MsoTriState.msoFalse,MsoTriState.msoFalse,MsoTriState.msoFalse);
                presentation.SaveAs(
                    pdfPath,
                    PowerPoint.PpSaveAsFileType.ppSaveAsPDF
                   );
                isSuccess = true;
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
            finally
            {
                if (presentation != null)
                {
                    presentation.Close();
                }
                //close workbook
                if (MSPowerPoint != null)
                {
                    MSPowerPoint.Quit();
                    MSPowerPoint = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return isSuccess;
        }
    }
}