--- title : 使用Pechkin套件將網頁轉成PDF檔 tags: Pechkin , 網頁轉成PDF檔 creat-date: 2021-12-08 update_date : 2021-12-08 --- --- # 使用Pechkin套件將網頁轉成PDF檔(ASP.NET) --- Pechkin套件可以將網頁Html轉成PDF檔 而Pechkin只是把它包成.dll檔方便在.net程式碼中使用 參考:https://dotblogs.com.tw/shadow/2013/09/23/120277 <br/> >### **使用Url轉PDF檔** >**注意:產生PDF對象的Url,須是Http開頭的絕對路徑URL,而不是直接用Url.Action()方法** ```bat= using Pechkin; String url = "http://tm.gis.tw/SWOpen_Data/System/DataSetList.aspx"; Response.Clear(); using (IPechkin pechkin = Factory.Create(new GlobalConfig())) { try { pechkin.Error += new Pechkin.EventHandlers.ErrorEventHandler(pechkin_Error); pechkin.Warning += new Pechkin.EventHandlers.WarningEventHandler(pechkin_Warning); ObjectConfig oc = new ObjectConfig().SetPrintBackground(true) .SetLoadImages(true) .SetScreenMediaType(true) .SetFallbackEncoding(Encoding.UTF8) .SetPageUri(url) .SetAllowLocalContent(true); byte[] pdf = pechkin.Convert(oc); Response.Clear(); Response.Buffer = true; Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.pdf", Request.Params["id"])); Response.OutputStream.Write(pdf, 0, pdf.Length); this.Context.ApplicationInstance.CompleteRequest(); } catch (Exception ex) { Log.WriteLog(ex); } Response.End(); } ``` >### **使用Html轉PDF檔** >**實作:Https開頭的Url轉PDF,Url必需是相對路徑** ```bat= using Pechkin; String url = "DataSetList.aspx"; StringWriter strHTML = new StringWriter(); System.Web.UI.Page myPage = new Page(); myPage.Server.Execute(url, strHTML); Response.Clear(); using (IPechkin pechkin = Factory.Create(new GlobalConfig())) { try { pechkin.Error += new Pechkin.EventHandlers.ErrorEventHandler(pechkin_Error); pechkin.Warning += new Pechkin.EventHandlers.WarningEventHandler(pechkin_Warning); ObjectConfig oc = new ObjectConfig().SetPrintBackground(true) .SetLoadImages(true) .SetScreenMediaType(true) .SetFallbackEncoding(Encoding.UTF8) .SetAllowLocalContent(true); byte[] pdf = pechkin.Convert(oc, strHTML.ToString()); Response.Clear(); Response.Buffer = true; Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.pdf", Request.Params["id"])); Response.OutputStream.Write(pdf, 0, pdf.Length); this.Context.ApplicationInstance.CompleteRequest(); } catch (Exception ex) { Log.WriteLog(ex); } Response.End(); } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up