C # generates PDFs based on HTML

Source: Internet
Author: User

Using the Itextsharp control



Using system;using system.collections.generic;using system.web;using system.web.ui;using System.Web.UI.WebControls; Using itextsharp.text;using itextsharp.text.pdf;using system.io;using itextsharp.tool.xml;using System.Text;using System.net;namespace pdftools{public partial class CreatePdf:System.Web.UI.Page {string Inpath = SYSTEM.W Eb.        HttpContext.Current.Server.MapPath ("~/bin/temp.html"); protected void Page_Load (object sender, EventArgs e) {string path = System.Web.HttpContext.Current.Serv Er.            MapPath ("~/uploadpdf"); if (!            Directory.Exists (path)) directory.createdirectory (path);            WebClient WC = new WebClient (); Download the HTML string WC from the URL.            Encoding = System.Text.Encoding.UTF8;            String htmltext = Getwebcontent (); Byte[] Pdffile = this.            Converthtmltexttopdf (HTMLText);            String fileId = "/file_" + DateTime.Now.ToString ("YYYYMMDDHHMMSS") + ". pdf"; System.IO.File.WrIteallbytes (path + fileId, pdffile); }//<summary>//To determine if garbled///</summary>//<param name= "TXT" ></param&        Gt <returns></returns> public bool Ismessycode (string txt) {var bytes = Encoding.ut F8.            GetBytes (TXT); 239 191 189 for (var i = 0; i < bytes. Length; i++) {if (I < bytes.                    Length-3) if (bytes[i] = = 239 && bytes[i + 1] = = 191 && bytes[i + 2] = = 189)                    {return true;        }} return false; }///<summary>//For website content, including HTML+CSS+JS//</summary>//<returns>strin  G Returns Web information </returns> public string getwebcontent () {try {WebClient                Mywebclient = new WebClient (); Mywebclient.credentials = credentialcache.defaultcredentials;                Gets or sets the network credential used to authenticate requests to Internet resources byte[] Pagedata = Mywebclient.downloaddata (Inpath);                Download data from the specified Web site string pagehtml = Encoding.UTF8.GetString (pagedata); If the Get Site page uses GB2312, then use this bool Isbool = Ismessycode (pagehtml);//determine which encoding to use to read the Web page information if (                    !isbool) {String pageHtml1 = Encoding.UTF8.GetString (pagedata);                pagehtml = PAGEHTML1;                    } else {string pageHtml2 = Encoding.Default.GetString (pagedata);                pagehtml = PAGEHTML2;            } return pagehtml;                } catch (WebException webEx) {Console.WriteLine (webEx.Message.ToString ());            return webex.message; }}///<summary>//Export HTML text to PDF file///</summary>//<param name= "HTMLText" ></param>//<returns></returns> Public byte[] Converthtmltexttopdf (string htmltext) {if (string.            IsNullOrEmpty (HTMLText)) {return null; }//Avoid htmltext when the text is not in any HTML tag tag, the PDF will be dropped, so add <p> tag htmltext = "<p>" + HTMLText + "&L            T;/p> "; MemoryStream outputstream = new MemoryStream ()//to which stream the PDF is to be written byte[] data = Encoding.UTF8.GetBytes (htmltext);//Word            String turn into byte[] MemoryStream msinput = new MemoryStream (data); Document doc = new document ();//To write a PDF file, the constructor is not filled with the pre-set straight A4 PDFWriter writer = pdfwriter.getinstance (doc, Outputstre            AM); Specifies that the file preset is scaled to 100% pdfdestination pdfdest = new Pdfdestination (pdfdestination.xyz, 0, Doc.            Pagesize.height, 1f); Open the document file doc.            Open (); Use Xmlworkerhelper to parse HTML into PDF file// Xmlworkerhelper.getinstance ().            Parsexhtml (writer, doc, msinput, NULL, Encoding.UTF8, New Unicodefontfactory ()); Xmlworkerhelper.getinstance ().            Parsexhtml (writer, doc, msinput, NULL, ENCODING.UTF8);            Write the information pdfdest set to PDF file Pdfaction action = pdfaction.gotolocalpage (1, pdfdest, writer); Writer.            Setopenaction (action); Doc.            Close ();            Msinput.close ();            Outputstream.close ();        Return the PDF file to Outputstream.toarray (); }//Set font class public class Unicodefontfactory:fontfactoryimp {private static readonly Strin G Arialfontpath = Path.Combine (Environment.getfolderpath (Environment.SpecialFolder.Fonts), "Arialuni.ttf");//arial            Unicode MS is the complete Unicode font.            private static readonly string marked in italics Path = Path.Combine (Environment.getfolderpath (Environment.SpecialFolder.Fonts), "Kaiu. TTF ");//Standard italic public override Font GetFont (string fontname, string enCoding, bool embedded, float size, int style, Basecolor color, bool cached) {Basefont bfchiness = Basefont.createfont (@ "C:\Windows\Fonts\SIMSUN.                ttc,1 ", Basefont.identity_h, basefont.not_embedded); Use Arial or superscript italic, choose a basefont Basefont = Basefont.createfont (marked in italics path, Basefont.identity_h, basefont.embedded                );            return new Font (bfchiness, size, style, color); }        }    }}


C # generates PDFs based on HTML

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.