網上有很多將Web頁面轉成PDF的方法,還有許多收費的第三方插件。其實利用Office 自帶的將EXCEL發布成PDF的功能就可以實現,如果你的需求沒有多復雜,可以采用筆者的方法。
首先將web頁面html保存為EXCEL文件(此步驟有多種方法,就不詳細探討了。只要能將web頁面轉成EXCEL文件,剩下的就好說了。)
StringWriter html = new StringWriter();HtmlTextWriter tw = new HtmlTextWriter(html);base.Render(tw);//excelName存放Excel的地址FileStream fs = new FileStream(excelName, FileMode.Create);StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("utf-8")); //開始寫入 sw.Write(html); //清空緩沖區 sw.Flush(); //關閉流 sw.Close(); fs.Close();
然后利用Microsoft.Office.Interop.Excel將EXCEL 轉成PDF
首先引用Microsoft.Office.Interop.Excel.dll,并設置dll 的屬性值無法嵌入互操作類型 為false 。否則會報 類型“Microsoft.Office.Interop.Excel.applicationClass”未定義構造函數無法嵌入互操作類型“Microsoft.Office.Interop.Excel.ApplicationClass”。請改用適用的接口 錯誤。然后安裝SaveaspDFandXPS.exe (安裝此插件才能將excel 另存為 pdf)源代碼如下:/// <summary> /// Excel保存PDF /// </summary> /// <param name="excelPath"> EXCEL全路徑 </param> /// <param name="pdfPath"> PDF保存路徑 </param> /// <returns></returns> public static bool CovertExcelToPDF( string excelPath, string pdfPath) { object missing = Type .Missing; ////創建excel應用程序實例 ApplicationClass application = null ; ////創建工作薄實例 Workbook workBook = null ; try { application = new ApplicationClass (); ////打開工作簿 workBook = application.Workbooks.Open(excelPath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); ////打開sheet Worksheet ws = (Worksheet )workBook.Worksheets.Item[1]; ////設置打印放放為水平 ws.PageSetup.Orientation = XlPageOrientation .xlPortrait; ////設置打印時excel內容在一個頁面上顯示。Zoom必須設置為false ws.PageSetup.Zoom = false ; ws.PageSetup.FitToPagesTall = 1; ws.PageSetup.FitToPagesWide = 1; ////將工作簿發布為PDF或XPS格式 ws.ExportAsFixedFormat( XlFixedFormatType .xlTypePDF, pdfPath , XlFixedFormatQuality .xlQualityStandard , true , false ////忽略打印區域 , missing, missing, missing, missing); return true ; } catch { throw ; } finally { ////工作簿關閉 if (workBook != null ) { workBook.Close( true , missing, missing); workBook = null ; } //// excel應用程序退出關閉 if (application != null ) { application.Quit(); application = null ; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } }
【代碼示例】
新聞熱點
疑難解答