[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();
}
}
參考網頁:
- http://www.kuqin.com/office/20080504/7814.html (不錯的參考)
- http://www.codeproject.com/KB/aspnet/wordapplication.aspx
- http://www.iwms.net/n1045c12.aspx
- http://forums.asp.net/t/1177955.aspx
- http://www.dotblogs.com.tw/rainmaker/archive/2010/01/25/13275.aspx
- http://www.dotblogs.com.tw/rainmaker/archive/2009/10/14/11054.aspx(解決Win2008 Asp.NET使用Word.Selection會有System.NullReferenceException的問題)
留言
張貼留言