ASP.NET 用 Office COM 组件将 docx\pptx\xlsx 转换成 PDF 文件

本文内容

  • 软件环境
  • 解决方案结构
  • 演示 ASP.NET 用 Office COM 组件将 docx\pptx\xlsx 转换成 PDF 文件

 

软件环境


  • VS 2010 framework 4.0
  • Windows 7 旗舰版
  • Office 2007

 

解决方案结构


2013-03-04_215339

  • Upload 目录。客户端上传目录。
  • PDF 目录。上传后,转换成 PDF 文件的目录。

 

演示 ASP.NET 用 Office COM 组件将 docx\pptx\xlsx 转换成 PDF 文件


ConvertToPDF 类将 docx\pptx\xlsx 转换成 PDF 文件,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Office;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
 
namespace ConvertToPDF
{
    public class ConvertToPDF
    {
        public ConvertToPDF()
        {
        }
        /// <summary>
        /// DOC 2 PDF
        /// </summary>
        /// <param name="sourcePath">源路径</param>
        /// <param name="targetPath">目标路径</param>
        /// <returns></returns>
        public bool DOC2PDF(string sourcePath, string targetPath)
        {
            bool result = false;
            Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF;
            object paramMissing = Type.Missing;
            Word.ApplicationClass wordApplication = new Word.ApplicationClass();
            Word.Document wordDocument = null;
            try
            {
                object paramSourceDocPath = sourcePath;
                string paramExportFilePath = targetPath;
 
                Word.WdExportFormat paramExportFormat = exportFormat;
                bool paramOpenAfterExport = false;
                Word.WdExportOptimizeFor paramExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
                Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                Word.WdExportCreateBookmarks paramCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;
 
                wordDocument = wordApplication.Documents.Open(
                ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing, ref paramMissing, ref paramMissing,
                ref paramMissing);
 
                if (wordDocument != null)
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                    paramExportFormat, paramOpenAfterExport,
                    paramExportOptimizeFor, paramExportRange, paramStartPage,
                    paramEndPage, paramExportItem, paramIncludeDocProps,
                    paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                    paramBitmapMissingFonts, paramUseISO19005_1,
                    ref paramMissing);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
        /// <summary>
        /// XLS 2 PDF
        /// </summary>
        /// <param name="sourcePath">源路径</param>
        /// <param name="targetPath">目标路径</param>
        /// <returns></returns>
        public bool XLS2PDF(string sourcePath, string targetPath)
        {
            bool result = false;
            Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF;
            object missing = Type.Missing;
            Excel.ApplicationClass application = null;
            Excel.Workbook workBook = null;
            try
            {
                application = new Excel.ApplicationClass();
                object target = targetPath;
                object type = targetType;
                workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                        missing, missing, missing, missing, missing, missing, missing, missing, missing);
 
                workBook.ExportAsFixedFormat(targetType, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
        /// <summary>
        /// PPT 2 PDF
        /// </summary>
        /// <param name="sourcePath">源路径</param>
        /// <param name="targetPath">目标路径</param>
        /// <returns></returns>
        public bool PPT2PDF(string sourcePath, string targetPath)
        {
            bool result;
            PowerPoint.PpSaveAsFileType targetFileType = PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
            object missing = Type.Missing;
            PowerPoint.ApplicationClass application = null;
            PowerPoint.Presentation persentation = null;
            try
            {
                application = new PowerPoint.ApplicationClass();
                persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
                persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);
 
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (persentation != null)
                {
                    persentation.Close();
                    persentation = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
    }
}

通过如下方式添加 Office COM 组件。

2013-03-04_214741

页面代码如下所示:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ConvertToPDF._Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="margin: 50px auto; border: #e3e3e3 1px solid; height: 300px; width: 350px;
        background-color: #8ABAE3; padding: 20px 20px 20px 20px;">
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="Btn_Upload" runat="server" Text="上传" OnClick="Btn_Upload_Click" />
        <br />
        <br />
        选择列表框中的文件,查看:
        <br />
        <asp:ListBox ID="ListBox1" runat="server" Height="205px" Width="290px"></asp:ListBox>
    </div>
    </form>
</body>
</html>

后台代码如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
 
namespace ConvertToPDF
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }
 
        /// <summary>
        /// 文档上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Btn_Upload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                try
                {
                    string fileName = FileUpload1.FileName;
                    string fileExtention = FileUpload1.FileName.Substring(fileName.LastIndexOf(".") + 1);
                    string filePath = HttpContext.Current.Server.MapPath("~/Upload\\") + fileName;
                    FileUpload1.SaveAs(filePath);
                    ListBox1.Items.Add(new ListItem(fileName, fileName));
 
                    bool bl = Convert(fileName, fileExtention);
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", bl ? "<script>alert('上传、转换成功!')</script>" : "<script>alert('上传、转换失败!')</script>");
                }
                catch
                {
 
                }
            }
        }
 
        private bool Convert(string fileName, string fileExtention)
        {
            string srcPath = HttpContext.Current.Server.MapPath("~/Upload\\") + fileName;
            string targetPath = HttpContext.Current.Server.MapPath("~/PDF\\") + fileName.Replace(".","-") + ".pdf";
 
            ConvertToPDF c = new ConvertToPDF();
            bool bl = false;
            switch (fileExtention.ToUpper())
            {
                case "DOC":
                case "DOCX":
                    bl = c.DOC2PDF(srcPath, targetPath);
                    break;
                case "XLS":
                case "XLSX":
                    bl = c.XLS2PDF(srcPath, targetPath);
                    break;
                case "PPT":
                case "PPTX":
                    bl = c.PPT2PDF(srcPath, targetPath);
                    break;
                default:
                    bl = false;
                    break;
            }
            return bl;
        }
    }
}

运行结果:

2013-03-04_215712_副本

o_%E5%8E%9F%E5%88%9B.jpg

下载 Demo

项目使用VS2017打开,.net 2.0下运行。 项目使用的微软官方的插件方法,可以将doc, docx, xls, xlsx, ppt, pptx文件转换为pdf文件,但是需要: 1、用户需要首先安装一个SaveAsPDFandXPS.exe的工具; 2、如果用户是xp系统,则: 2.1 如果用户安装的是office 2007,则用户在安装office 2007的时候必须要安装Visual Basic for Application 和 Microsoft Office Document Imaging这2个选项,否则转换失败; 2.2 如果用户安装的是office 2010,则在安装office 2010时必须要安装Visual Basic for Application选项,然后从office 2007安装包里面安装Microsoft Office Document Imaging(因为2010删除了这个选项,好麻烦~),否则转换失败; 2.3 xp不能安装office 2013/2016; 3、如果用户是win7系统,则: 3.1 如果用户安装的是office 2007,则用户在安装office 2007的时候必须要安装Visual Basic for Application 和 Microsoft Office Document Imaging这2个选项,否则转换失败; 3.2 如果用户安装的是office 2010,则在安装office 2010时必须要安装Visual Basic for Application选项(win7 + office 2010不需要安装Microsoft Office Document Imaging) 3.3 如果用户安装的是office 2013或2016,则不需要额外选项; 4、如果用户是win10系统,则: 4.1 如果用户安装的是office 2007,则用户在安装office 2007的时候必须要安装Visual Basic for Application这个选项,(win10 + office 2007不需要安装Microsoft Office Document Imaging)否则转换失败; 4.2 如果用户安装的是office 2010,则在安装office 2010时必须要安装Visual Basic for Application选项(win10 + office 2010不需要安装Microsoft Office Document Imaging) 4.3 如果用户安装的是office 2013或2016,则不需要额外选项; 5、如果用户安装了wps 2016或者wps 2019也可以正常转换。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值