上传WORD并转成PDF格式

本文介绍了一个使用Microsoft Office Interop Word将Word文档转换为PDF的方法,并提供了详细的步骤来解决因权限问题导致的COM组件访问异常。此外,还说明了进行转换所需的Office版本及额外插件。

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

using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Word;
public static bool WordToPdf(object sourcePath, string targetPath)
        {
            bool result = false;
            WdExportFormat wdExportFormatPDF = WdExportFormat.wdExportFormatPDF;
            object missing = Type.Missing;
            Microsoft.Office.Interop.Word.ApplicationClass applicationClass = null;
            Microsoft.Office.Interop.Word.Document document = null;
            //try
            //{
                applicationClass = new Microsoft.Office.Interop.Word.ApplicationClass();
                document = applicationClass.Documents.Open(ref sourcePath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                if (document != null)
                {
                    document.ExportAsFixedFormat(targetPath, wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent, true, true, WdExportCreateBookmarks.wdExportCreateWordBookmarks, true, true, false, ref missing);
                }
                result = true;
            //}
            //catch
            //{
            //    result = false;
            //}
            //finally
            //{
                if (document != null)
                {
                    document.Close(ref missing, ref missing, ref missing);
                    document = null;
                }
                if (applicationClass != null)
                {
                    applicationClass.Quit(ref missing, ref missing, ref missing);
                    applicationClass = null;
                }
            //}
            return result;
        }

异常“检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件失败,原因是出现以下错误: 80070005 拒绝访问”:

解决方案如下:

     1、点击Win +R键输入comexp.msc -32(如果按钮的Word是64位的输入dcomcnfg)回车

      2、以此找到"组件服务---"计算机"---“我的电脑”---"DCOM配置"

      3、找到"Microsoft Word 97 - 2003 文档"右键属性。

      4、在"标识"一栏选择"交互式用户"

       5、在"安全"一栏可以看到“启动与激活”组,选择"自定义",点击"编辑"按钮,添加NetWork Service、当前用户,给于"本地启动","本地激活"权限。

       6、"访问权限"和"配置权限"同上。

       7、在web.config文件的<system.web></system.web>中添加<identity impersonate="true" userName="当前用户名" password="xxxxxxx" />


对于转换,需安装OFFICE2007以上版本,对于OFFICE2007及以下版本,需另外安装微软针对转换的“SaveAsPDFandXPS.exe”插件。



http://blog.youkuaiyun.com/huanglanan/article/details/51000694



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值