将DOC文件转化为PDF文件
首先在VS2013新建C#的Windows Form应用程序,并向窗体添加三个button控件、一个label控件、一个listBox控件。
1)添加引用Microsoft.Office.Interop.Word且添加相应using语句。
2)添加代码如下。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using Microsoft.Office.Interop.Word;
namespace WinFrmAppDOC2PDF
{
public partial class Form1 : Form
{
String strDOCSourcePath = "";
public Form1()
{
InitializeComponent();
}
private voidbutton1_Click(object sender, EventArgs e)
{
string strFolder_f = null;
string strFolder_t = null;
string strFlag = null;
strFolder_f = strDOCSourcePath; //strFolder_f= @"C:\ZSJCommData\Doc";
if (strFolder_f.Substring(strFolder_f.Length - 1, 1)!= "\\")
{
strFolder_f += "\\";
}
strFolder_t = strFolder_f + @"pdf\";
label1.Text = @"开始创建PDF文档,请耐心等待!...";
strFlag = "y";// 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.ApplicationappWord = new Microsoft.Office.Interop.Word.Application();
object paramMissing = Type.Missing;
listBox1.Items.Clear();
foreach (FileInfoNextFile in TheFolder.GetFiles("*.doc*"))
{
Microsoft.Office.Interop.Word.DocumentwordDocument = new Document();
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, refparamMissing);
wordDocument = null;
}
listBox1.Items.Add(strPdfFile);
}
if (appWord != null)
{
appWord.Quit(ref paramMissing, ref paramMissing, refparamMissing);
appWord = null;
}
}
KillProcessByName("WINWORD");
GC.Collect();
GC.WaitForPendingFinalizers();
label1.Text = @"转换处理完毕! PDF文件保存在 " + strFolder_t;
}
static voidCheckFolder(string strFolderPath)
{
if (Directory.Exists(strFolderPath))
{
Directory.Delete(strFolderPath, true);
Directory.CreateDirectory(strFolderPath);
}
else
{
Directory.CreateDirectory(strFolderPath);
}
}
static voidKillProcessByName(string name)
{
Process[] ps = Process.GetProcessesByName(name);
foreach (Process pin ps)
{
if (p.ProcessName == name)
p.Kill();
}
}
private voidbutton2_Click(object sender, EventArgs e)
{
this.Close();
}
private voidbutton3_Click(object sender, EventArgs e)
{//选择待转换文件夹
strDOCSourcePath = "";
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
string selFolder =folderBrowserDialog1.SelectedPath;
strDOCSourcePath = folderBrowserDialog1.SelectedPath;
label2.Text = "待转换Doc文件路径 " + strDOCSourcePath;
}
}
}
}
程序界面如下: