1. 程式人生 > 其它 >C#將word文件轉為PDF

C#將word文件轉為PDF

使用Microsoft.Office.Interop.Word 將word文件轉為PDF

在NuGet中搜索Microsoft.Office.Interop.Word 安裝

方法 引數參考 微軟官網地址

  /// <summary>
        /// 將word轉成PDF office
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
public static bool WordToPDFWithOffice(string sourcePath, string targetPath, int fromPage = 1, int toPage = 1) { bool result = false; Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application(); Document document
= null; try { application.Visible = false; document = application.Documents.Open(sourcePath); /* 引數參考 https://docs.microsoft.com/zh-cn/office/vba/api/visio.document.exportasfixedformat */ document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF,
false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportFromTo, fromPage, toPage); result = true; } catch (Exception e) { //Console.WriteLine(e.Message); result = false; } finally { document.Close(); } return result; }