[ASP.NET] Word轉PDF 利用Office 2007

Word 轉 PDF,共分成三大步驟:
  • 前置作業:
    1. 首先~安裝Office 2007 。
    2. 安裝2007 Microsoft Office 增益集:Microsoft 另存 PDF 或 XPS (建議選英文版的下載,免費的) 。
  • VS2008加入參考:
    1. Microsoft Office 12.0 Object Library
    2. Microsoft Word 12.0 Object Library
    3. Microsoft Excel 12.0 Object Library (如果你手養想做Excel轉PDF的話就加入此參考)
  • 程式部分:
    至少要Include 下列三行:
    using System.IO;
    using Word = Microsoft.Office.Interop.Word;
    using Microsoft.Office.Core;

    同樣~若你手養要轉Excel to PDF 則
    using Excel = Microsoft.Office.Interop.Excel;

    直接貼Code:

    protected void Button1_Click(object sender, EventArgs e)
    {
    object missing = Type.Missing;
    Word.ApplicationClass oWordApp = new Word.ApplicationClass();
    Word.Document oWordDoc = null;
    try
    {

    object readOnly = false;
    object isVisible = true;
    object fileName = "C:\\統計(未修改).doc"; //來源word檔(.doc或.docx均可)
    string targetPath = Server.MapPath("~/Public/Edlee.pdf");//目的地完整路徑+檔名

    oWordDoc = oWordApp.Documents.Open(ref fileName,
    ref missing, ref readOnly,
    ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing,
    ref missing, ref missing, ref isVisible,
    ref missing, ref missing, ref missing, ref missing);

    Word.WdExportFormat paramExportFormat =
     Word.WdExportFormat.wdExportFormatPDF;
    bool paramOpenAfterExport = false;
    Word.WdExportOptimizeFor paramExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
    Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
    int paramStartPage = 0;
    int paramEndPage = 0;
    Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
    bool paramIncludeDocProps = true;
    bool paramKeepIRM = true;
    Word.WdExportCreateBookmarks paramCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
    bool paramDocStructureTags = true;
    bool paramBitmapMissingFonts = true;
    bool paramUseISO19005_1 = false;

    if (oWordDoc != null)
    oWordDoc.ExportAsFixedFormat(targetPath,
    paramExportFormat, paramOpenAfterExport,
    paramExportOptimizeFor, paramExportRange, paramStartPage,
    paramEndPage, paramExportItem, paramIncludeDocProps,
    paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
    paramBitmapMissingFonts, paramUseISO19005_1,
    ref missing);

    Response.Write("轉換完成!!");
    }
    catch (Exception ex)
    {
    Response.Write(ex.Message.ToString());
    }
    finally
    {
    if (oWordDoc != null)
    {
    oWordDoc.Close(ref missing, ref missing, ref missing);
    oWordDoc = null;
    }
    if (oWordApp != null)
    {
    oWordApp.Quit(ref missing, ref missing, ref missing);
    oWordApp = null;
    }
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
    GC.WaitForPendingFinalizers();
    }
    }

參考網頁:

留言

這個網誌中的熱門文章

[MS SQL] 使用PIVOT 做兩個欄位的交叉分析(動態欄位)

[ASP.NET] Gridview動態增加欄位與Null值處理

[MS SQL] 將輸入的時間(分、秒)轉換成中文時間的函數