利用Aspose組件將word轉成pdf文件,轉換的性能比較好,轉換的比較快,格式兼容性也挺好。另外服務器或PC上不用安裝msoffice word軟件就可以轉換。下面分享一下.NET Core中調用Aspose組件轉pdf代碼。
特別注意: Aspose組件在進行word轉成pdf文件的時候,如果word文件包含有圖片,就會報錯,轉換失敗
1、Aspose組件下載
Aspose下載地址:https://products.aspose.com/words/net
破解版下載地址:本人網盤里面 (aspose.words 18.7破解版含net 和 .net core 2.0版本)
官方文檔地址:https://docs.aspose.com/display/wordsnet/Home
官方Demo代碼:https://github.com/aspose-words/Aspose.Words-for-.NET
2、Word轉Pdf代碼
注意:除了引用Aspose.Words.dll,還要用Nuget安裝System.Text.Encoding.CodePages和SkiaSharp
using Aspose.Words;
using System; using System.IO; namespace WordToPdf { class Program { static void Main(string[] args) { try { if (args == null || args.Length < 2) throw new ArgumentException("參數不正確!"); var sourceFilePath = args[0]; var objectFilePath = args[1]; if (!File.Exists(sourceFilePath)) throw new FileNotFoundException("文件未找到", sourceFilePath); if (File.Exists(objectFilePath)) File.Delete(objectFilePath); WordToPdf(sourceFilePath, sourceFilePath); //WordToPdf(@"f:\1.doc", @"f:\1.pdf"); } catch (Exception ex) { Console.Write("Error:{0}", ex.Message + Environment.NewLine + ex.StackTrace); } } public static void WordToPdf(string wordPath, string pdfPath) { try { //Aspose.Words.License lic = new Aspose.Words.License(); //lic.SetLicense("Aspose.Total.lic");破解版不用設置license //打開word文件 Document doc = new Aspose.Words.Document(wordPath); //驗證參數 if (doc == null) { throw new Exception("Word文件無效"); } doc.Save(pdfPath, Aspose.Words.SaveFormat.Pdf);//還可以改成其它格式 } catch (Exception ex) { Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace); } } } }