Asp.Net Word、Excel转PDF在线预览

本文提供了一种使用C#将Office文档(包括Word和Excel)转换为PDF的方法。通过创建两个静态方法,分别针对Word和Excel文件,实现了文档的批量转换,并确保了资源的正确释放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步建一个类(ConvertPdf.cs)存放此代码

  public static class ConvertPdf    {        /// <summary>        /// Word转换Pdf        /// </summary>        /// <param name="sourcePath"></param>        /// <param name="targetPath"></param>        /// <param name="exportFormat"></param>        /// <returns></returns>        public static bool Convert(string sourcePath, string targetPath, Microsoft.Office.Interop.Word.WdExportFormat exportFormat)        {            bool result;            object paramMissing = Type.Missing;            Microsoft.Office.Interop.Word.ApplicationClass wordApplication = new Microsoft.Office.Interop.Word.ApplicationClass();            Microsoft.Office.Interop.Word.Document wordDocument = null;            try            {                object paramSourceDocPath = sourcePath;                string paramExportFilePath = targetPath;                Microsoft.Office.Interop.Word.WdExportFormat paramExportFormat = exportFormat;                bool paramOpenAfterExport = false;                Microsoft.Office.Interop.Word.WdExportOptimizeFor paramExportOptimizeFor =                        Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint;                Microsoft.Office.Interop.Word.WdExportRange paramExportRange = Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument;                int paramStartPage = 0;                int paramEndPage = 0;                Microsoft.Office.Interop.Word.WdExportItem paramExportItem = Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent;                bool paramIncludeDocProps = true;                bool paramKeepIRM = true;                Microsoft.Office.Interop.Word.WdExportCreateBookmarks paramCreateBookmarks =                        Microsoft.Office.Interop.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;            }            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>        /// Excel转换方法        /// </summary>        /// <param name="sourcePath"></param>        /// <param name="targetPath"></param>        /// <param name="targetType"></param>        /// <returns></returns>        public static bool Convert(string sourcePath, string targetPath, Microsoft.Office.Interop.Excel.XlFixedFormatType targetType)        {            bool result;            object missing = Type.Missing;            Microsoft.Office.Interop.Excel.ApplicationClass application = null;            Microsoft.Office.Interop.Excel.Workbook workBook = null;            try            {                application = new Microsoft.Office.Interop.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, Microsoft.Office.Interop.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;        }    }
复制代码
复制代码
 第二步:在事件或者方法下面调用即可
                string TempValue = Server.MapPath("../../../UploadFiles/OAFiles") + "\\" + this.FileName;                string SaveValue = Server.MapPath("../../../UpConvertPDF/OAFiles") + "\\";                string PdfFileName = Guid.NewGuid().ToString() + ".pdf";                                try                {                    string fileExtension = Path.GetExtension(this.FileName);                    if (fileExtension == ".doc" || fileExtension == ".docx")                    {                        ConvertPdf.Convert(TempValue, SaveValue + PdfFileName, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);                        OpenOnlineFile(PdfFileName);                    }                    else if (fileExtension == ".xls" || fileExtension == ".xlsx")                    {                        ConvertPdf.Convert(TempValue, SaveValue + PdfFileName, Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF);                        OpenOnlineFile(PdfFileName);                    }                }                catch                {                    Response.Write("请稍后文件等待转换!");                }
复制代码

      说明:在引用Microsoft.Office.Interop.Word 或者Microsoft.Office.Interop.Excel的时候可能还会报错,这时打开引用,选中Microsoft.Office.Interop.Word 右键-属性 将嵌入互操作类型 设为:false 。这时就操作完成了!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值