將Word (.doc) 文件轉換成PDF格式是許多應用程序中的常見需求。然而,找到一種簡潔、經濟的編程解決方案可能具有挑戰性。開源選項通常缺乏SDK,而專有解決方案通常價格過高。
為了應對這一挑戰,這裡有兩種編程方法:
此解決方案解決了先前使用for循環的代碼中的一個問題。使用如下所示的foreach循環實現代碼可以解決此問題:
<code class="language-csharp">int j = 0; foreach (Microsoft.Office.Interop.Word.Page p in pane.Pages) { var bits = p.EnhMetaFileBits; var target = path1 + j.ToString() + "_image.doc"; try { using (var ms = new MemoryStream((byte[])(bits))) { var image = System.Drawing.Image.FromStream(ms); var pngTarget = Path.ChangeExtension(target, "png"); image.Save(pngTarget, System.Drawing.Imaging.ImageFormat.Png); } } catch (System.Exception ex) { MessageBox.Show(ex.Message); } j++; }</code>
此解決方案利用Microsoft Word Interop來實現轉換:
<code class="language-csharp">using Microsoft.Office.Interop.Word; using System; using System.IO; // ...其他using语句... // 创建新的Microsoft Word应用程序对象 Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); // C#没有可选参数,所以我们需要一个虚拟值 object oMissing = System.Reflection.Missing.Value; // 获取指定目录中Word文件的列表 DirectoryInfo dirInfo = new DirectoryInfo(@"\server\folder"); FileInfo[] wordFiles = dirInfo.GetFiles("*.doc"); word.Visible = false; word.ScreenUpdating = false; foreach (FileInfo wordFile in wordFiles) { // 转换为Object类型以用于word Open方法 Object filename = (Object)wordFile.FullName; // 使用虚拟值作为可选参数的占位符 Document doc = word.Documents.Open(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); doc.Activate(); object outputFileName = wordFile.FullName.Replace(".doc", ".pdf"); object fileFormat = WdSaveFormat.wdFormatPDF; // 将文档保存为PDF格式 doc.SaveAs(ref outputFileName, ref fileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); // 关闭Word文档,但保持Word应用程序打开。 // doc必须转换为_Document类型,以便找到正确的Close方法。 object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; } // word必须转换为_Application类型,以便找到正确的Quit方法。 ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); word = null;</code>
以上是如何有效且廉價地將Word文件編程轉換為PDF?的詳細內容。更多資訊請關注PHP中文網其他相關文章!