C#实现office文档转换为PDF格式

本文利用最少量的代码实现 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);
             }

         }
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值