以编程方式将Word文档转换为PDF
问题:
有没有性价比高的或使用 C# 或免费编程方法将 Word (.doc) 文件转换为 PDF VB.NET?
答案:
选项 1:利用 foreach 循环
实现 foreach 循环而不是 for循环来寻址问题:
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++; }
选项 2:使用带有“另存为 PDF”插件的 Word 2007
利用 Word 2007 和“另存为 PDF”插件使用以下代码 -于:
// Create a new Microsoft Word application object Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); // C# doesn't have optional arguments so we'll need a dummy value object oMissing = System.Reflection.Missing.Value; // Get list of Word files in specified directory DirectoryInfo dirInfo = new DirectoryInfo(@"\server\folder"); FileInfo[] wordFiles = dirInfo.GetFiles("*.doc"); word.Visible = false; word.ScreenUpdating = false; foreach (FileInfo wordFile in wordFiles) { // Cast as Object for word Open method Object filename = (Object)wordFile.FullName; // Use the dummy value as a placeholder for optional arguments 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; // Save document into PDF Format 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); // Close the Word document, but leave the Word application open. // doc has to be cast to type _Document so that it will find the // correct Close method. object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; } // word has to be cast to type _Application so that it will find // the correct Quit method. ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); word = null;
以上是如何在 C# 或 VB.NET 中以编程方式将 Word (.doc) 文件经济高效地转换为 PDF?的详细内容。更多信息请关注PHP中文网其他相关文章!