- A+
所属分类:.NET技术
一、基于Office的解决方案
1.获取指定文件夹下的所有word文件
static void Main(string[] args) { try { Console.WriteLine("------------开始---------------"); string path = @"XXXXXXXXXXXXXXXXXX";//word所在的文件夹 string SaveFile = @"XXXXXXXXXXXXXXXXXX";//保存路径 DirectoryInfo di = new DirectoryInfo(path); Console.Write("请输入指定名称(不输入获取所有文件):"); string filename = Console.ReadLine(); //找到该目录下的文件 FileInfo[] FileList; if (!string.IsNullOrEmpty(filename)) { FileList = di.GetFiles(filename); } else { FileList = di.GetFiles(); } int Success = 0; int Fail = 0; foreach (FileInfo item in FileList) { string Filescr = SaveFile + item.Name; bool bFlagPdf = Common.FileWordToPdf.ConvertToPdf(item.FullName, Filescr); if (bFlagPdf == true) { Success++; Console.WriteLine(item.Name + " ----- 转换成功"); } else { Fail++; Console.WriteLine(item.Name + " ----- 转换失败"); } } Console.WriteLine("------------本轮协议生成结束,结果如下:---------------"); Console.WriteLine("需生PDF共:" + FileList.Length + "份"); Console.WriteLine("成功PDF共:" + Success + "份协议"); Console.WriteLine("失败PDF共:" + Fail + "份协议"); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
2.创建一个Helper类
using Microsoft.Office.Interop.Word; using System.IO; public class FileWordToPdf_Helper { /// <summary> /// 直接使用Word转PDF /// </summary> /// <param name="mWordSrc">Word路径</param> /// <param name="SavsFile">保存路径</param> /// <returns></returns> public static bool ConvertToPdf(string mWordSrc,string SavsFile) { try { #region Com component Microsoft.Office.Interop.Word.Application appWord = null; object oMissing = System.Reflection.Missing.Value; if (appWord == null) { appWord = new Microsoft.Office.Interop.Word.Application(); } Microsoft.Office.Interop.Word.Document doc = appWord.Documents.Open(mWordSrc); doc.Activate(); string mPDFSrc = Path.ChangeExtension(SavsFile, "pdf"); doc.ExportAsFixedFormat(mPDFSrc, WdExportFormat.wdExportFormatPDF); object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; ((_Application)appWord).Quit(ref oMissing, ref oMissing, ref oMissing); appWord = null; GC.Collect(); GC.WaitForPendingFinalizers(); #endregion return true; } catch (Exception ex) { return false; throw (ex); } } }