本文利用最少量的代码实现 Word 转 PDF 示例,原理就是将 Word 文档转交给 Adobe处理。类似在 Word 中打印,然后选择 Adobe 打印成 PDF文件
① 安装 Adobe Acrobat 9 Pro 后 Office 2007 就有了导出 PDF的能力,本文直接使用 ExportAsFixedFormat 方法完成导出 PDF;
② 另外一种思路就是调用打印方法,然后选择 Adobe 打印成 PDF文件;
一、开发环境
开发工具:
- Microsoft Visual Studio 2013
软件环境:
- Microsoft Office 2007
- Adobe Acrobat 9 Pro
二、引用
- Microsoft Office 12.0 Object Library
- Microsoft.Office.Interop.Word
- Microsoft.Office.Interop.PowerPoint
- Microsoft.Office.Interop.Excel
三、源代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//打印的代码如下:
Microsoft.Office.Interop.Word.Application app = null;
Microsoft.Office.Interop.Word.Document doc = null;
object missing = System.Reflection.Missing.Value;
object templateFile = Application.StartupPath + @"\1122.docx";
try
{
app = new Microsoft.Office.Interop.Word.Application();//.ApplicationClass();
doc = app.Documents.Add(ref templateFile, ref missing, ref missing, ref missing);
doc.ExportAsFixedFormat(Application.StartupPath + @"\1122.pdf", Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
MessageBox.Show("转换完成!");
}
catch (Exception exp)
{
MessageBox.Show(exp.Message, this.Text);
}
//销毁word进程
finally
{
object saveChange = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
if (doc != null)
doc.Close(ref saveChange, ref missing, ref missing);
if (app != null)
app.Quit(ref missing, ref missing, ref missing);
}
}
}
}