引用 Microsoft Word 15.0 Object Library
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Word;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace word2pdf
{
class Program
{
static void OutputNullHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
//Console.WriteLine(outLine.Data);
}
//static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
//{
// String str = outLine.Data;
// if (str != null && str.Contains("动态"))
// Console.WriteLine(outLine.Data);
//}
//WINWORD.EXE POWERPNT.EXE 有.EXE后缀
static void KillProcess(String processName)
{
Process process = new Process();
process.StartInfo.FileName = "taskkill";
process.StartInfo.Arguments = "/f /im " + processName;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.OutputDataReceived += new DataReceivedEventHandler(OutputNullHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(OutputNullHandler);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
}
public static bool word2PDF(string sourcePath, string targetPath)
{
KillProcess("WINWORD.EXE");
bool result = false;
Application application = new Application();
Document document = null;
try{
document = application.Documents.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
document.SaveAs(targetPath, WdSaveFormat.wdFormatPDF);
result = true;
}
catch (Exception e){
Console.WriteLine("Error " + e.Message);
result = false;
}
finally
{
if (document != null)
{
try{
document.Close();
}
catch (Exception e){
result = false;
}
try{
Marshal.ReleaseComObject(document);
}
catch (Exception e){
result = false;
}
document = null;
}
if (application != null)
{
try{
application.Quit();
}
catch (Exception e){
result = false;
}
try{
Marshal.ReleaseComObject(application);
}
catch (Exception e){
result = false;
}
application = null;
}
if (!result)
KillProcess("WINWORD.EXE");
//主动激活垃圾回收器,主要是避免超大批量转文档时,内存占用过多,而垃圾回收器并不是时刻都在运行!
//GC.Collect();
//GC.WaitForPendingFinalizers();
}
return result;
}
//type 为1表示word转pdf, type为3表示ppt转pdf, 预留2,excel2pdf
static void Main(string[] args)
{
Console.WriteLine("start word2pdf");
int len = args.Length;
if (len > 1)
{
String srcPath = args[0].Replace("\"", ""); //路径有空格,用""括起来
String tarPath = args[1].Replace("\"", "");
word2PDF(srcPath, tarPath);
}
Console.WriteLine("end!");
}
}
}