c#实现word文档批量转换为pdf的方法

发布时间:2019-09-11编辑:脚本学堂
在c#编程中将word文档批量转换为pdf文件,只需要在office环境下使用本文的这段代码即可实现,注意本文末尾的注意事项,以正确处理word转pdf的问题。

c#实现批量word转pdf文件。

源码:
 

复制代码 代码示例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using Microsoft.Office.Interop.Word;

namespace Word2Pdf
{
class Program
{
public static Microsoft.Office.Interop.Word.Document wordDocument { get; set; }

static void Main(string[] args)
{
string strFolder_f = null;
string strFolder_t = null;
string strFlag = null;
System.Console.WriteLine("请输入Word文档所在目录");
strFolder_f = System.Console.ReadLine();
if (strFolder_f.Substring(strFolder_f.Length - 1, 1) != "")
{
strFolder_f += "";
}
strFolder_t = strFolder_f + @"pdf";
System.Console.WriteLine("n创建PDF文档,请确认!");
System.Console.Write("y(yes) or n(no) ?  ");
strFlag = System.Console.ReadLine();
if (strFlag == "y")
{
System.Console.WriteLine("n开始创建PDF文档...");
CheckFolder(strFolder_t);
string strPdfFile = null;
DirectoryInfo TheFolder = new DirectoryInfo(strFolder_f);

Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
object paramMissing = Type.Missing;

foreach (FileInfo NextFile in TheFolder.GetFiles())
{
strPdfFile = Path.ChangeExtension(strFolder_t + NextFile.Name, ".pdf");
wordDocument = appWord.Documents.Open(NextFile.FullName);
if (wordDocument != null)
{
wordDocument.ExportAsFixedFormat(strPdfFile, WdExportFormat.wdExportFormatPDF);
wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
wordDocument = null;
}
System.Console.Write(".. ");
}

if (appWord != null)
{
appWord.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
appWord = null;
}
}

//KillProcessByName("WINWORD");
GC.Collect();
GC.WaitForPendingFinalizers();

System.Console.Write("n处理完毕,输入任意键退出");
System.Console.ReadKey();
}

static void CheckFolder(string strFolderPath)
{
if (Directory.Exists(strFolderPath))
{
Directory.Delete(strFolderPath, true);
Directory.CreateDirectory(strFolderPath);
}
else
{
Directory.CreateDirectory(strFolderPath);
}
}

static void KillProcessByName(string name)
{
Process[] ps = Process.GetProcessesByName(name);
foreach (Process p in ps)
{
if (p.ProcessName == name)
p.Kill();
}
}
}
}

注意:
1、及时关闭代码中所打开的文档,见49行,否则会产生临时文件;
2、及时关闭“WINWORD”线程,否则所处理的Word文档会一直处于被该线程占用的情况。