ASP.NET将word文档转换成pdf的代码。
一、添加引用
using Microsoft.Office.Interop.Word;
二、转换方法
1、方法
/// <summary>
/// 把Word文件转换成pdf文件
/// </summary>
/// <param name="sourcePath">需要转换的文件路径和文件名称</param>
/// <param name="targetPath">转换完成后的文件的路径和文件名名称</param>
/// <returns>成功返回true,失败返回false</returns>
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;
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;
}
三、方法调用
OfficeToPdf.WordToPdf("d:\\1234.doc", "d:\\1234.pdf");