發布時間:2020-12-02 15:47 作者:獨孤劍 閱讀:1311
添加COM引用,本機已安裝 Microsoft Office 2013,如果COM引用里沒有"Microsoft Office x.x Object Library",則需要安裝 Microsoft Office 軟件。
C#代碼
using System; using System.IO; using Word = Microsoft.Office.Interop.Word; namespace ConsoleApp18 { class Program { static void Main(string[] args) { try { WordToPdf(AppDomain.CurrentDomain.BaseDirectory + "test.docx", AppDomain.CurrentDomain.BaseDirectory + "test.pdf"); Console.WriteLine("Success"); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } /// <summary> /// Word 轉 Pdf /// </summary> /// <param name="sorucePath">The word path.</param> /// <param name="savePath">Save pdf path.</param> public static void WordToPdf(string sorucePath, string savePath) { Word.Application application = new Word.Application(); Word.Document document = null; try { application.Visible = false; document = application.Documents.Open(sorucePath); // 目標存在則先刪除 if (File.Exists(savePath)) { File.Delete(savePath); } document.ExportAsFixedFormat(savePath, Word.WdExportFormat.wdExportFormatPDF); } catch { throw; } finally { document.Close(); application.Quit(); // 強制回收 GC.Collect(); GC.WaitForPendingFinalizers(); } } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞