1.使用 Office COM組件的Microsoft.Office.Interop.word.dll庫app
該方法須要在電腦上安裝Office軟件,而且須要Office支持轉換爲PDF格式,若是不支持,從官網下載一個SaveAsPDFandXPS.exe插件spa
Interop.word程序集能夠經過Nuget程序包獲取,實現代碼以下:插件
public bool WordToPDF2(string sourcePath) { bool result = false; Word.Application application = new Word.Application(); Word.Document document = null; try { application.Visible = false; document = application.Documents.Open(sourcePath); string PDFPath = sourcePath.Replace(".doc", ".pdf");//pdf存放位置 if (!File.Exists(PDFPath))//存在PDF,不須要繼續轉換 { document.ExportAsFixedFormat(PDFPath, Word.WdExportFormat.wdExportFormatPDF); } result = true; } catch (Exception e) { Console.WriteLine(e.Message); result = false; } finally { document.Close(); } return result; }
2.使用Aspose.Words組件 code
首先須要引用Aspose.Words.dll,連接地址:https://pan.baidu.com/s/1rJvjp-kMsEterYf_oud28Q 提取碼:awiworm
代碼以下:blog
public bool WordToPDF1(string sourcePath) { try { Document doc = new Document(sourcePath); string targetPath = sourcePath.ToUpper().Replace(".DOCX", ".PDF"); doc.Save(targetPath,SaveFormat.Pdf); } catch(Exception e) { Console.WriteLine(e.Message); return false; } return true; }