您当前的位置:首页 > 计算机 > 编程开发 > .net

C# Word转换成Pdf的方法

时间:12-15来源:作者:点击数:

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");

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门