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.csdn.net/huanglanan/article/details/51000694