C # Use itextsharp to generate a PDF file

Source: Internet
Author: User

To generate a PDF document for the project, use vs2010 and ASP. NET.

I did not search for what I wanted for multiple times on the Internet, so I tried to go to the itextpdf official website to read the English documents and complete the task on time. The task was mainly practical and shared with me:

Creating a PDF template using an HTML file: one way to use a Custom font:
                FontFactory.Register(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\Fonts\\RAGE.TTF", "myFont");                Font myFont = FontFactory.GetFont("myFont");                BaseFont bf = myFont.BaseFont;

Here, rage. TTF is the font that comes with the Microsoft operating system. The directory is in c: \ windows \ fonts. We recommend that you copy the font to the project. Otherwise, the file cannot be referenced.
Use custom styles:

                StyleSheet css = new StyleSheet();                Dictionary<String, String> dict= new Dictionary<string, string>();                dict.Add(HtmlTags.BGCOLOR, "#01366C");                dict.Add(HtmlTags.COLOR, "#000000");                dict.Add(HtmlTags.SIZE,"25");                css.LoadStyle("css1", dict);

The loadstyle method of stylesheet can be used here. Note that itextsharp has poor support for HTML elements. attributes such as alignment and background color of elements such as label and Div do not support well. We recommend that you use table labels. Override the getfont method of Font:

Public class myfontfactory: ifontprovider {public font getfont (string fontname, string encoding, Boolean embedded, float size, int style, basecolor) {If (fontname = "") {string fontpath = system. web. httpcontext. current. request. physicalapplicationpath + "\ fonts \ msyh. TTF "; basefont bf3 = basefont. createfont (fontpath, basefont. identity_h, basefont. embedded); font fontcontent = new font (bf3, size, style, color); Return fontcontent;} else {font fontcontent = fontfactory. getfont (fontname, size, style, color); Return fontcontent ;}} public Boolean isregistered (string fontname) {return false ;}}

To use a Custom font, you must inherit the ifontprovider interface and override the getfont method of font.

Add the Custom font and style sheet to the document:
                Dictionary<String, Object> font = new Dictionary<string, object>();                font.Add(HTMLWorker.FONT_PROVIDER,new MyFontFactory());                               List<IElement> p = HTMLWorker.ParseToList(new StreamReader(html), css,font);

Add the background color to the element by using inclucontentbyte:

                PdfContentByte pcb = writer.DirectContentUnder;                pcb.SetRGBColorFill(0, 255, 0);                pcb.SetRGBColorFill(1, 54, 108);                pcb.Rectangle(20, 413, 800, 42);                pcb.Fill();

The disadvantage is obvious, that is, the absolute coordinates are required, and the younger brother is not easy to learn, and the time is tight. If Daniel knows a better method, I hope you will not be enlightened.

Complete code:
Using system; using system. collections. generic; using system. LINQ; using system. web; using itextsharp.text.pdf; using itextsharp. text; using system. io; using itextsharp.text.html. simpleparser; using itextsharp.text.html; // <summary> // Summary of createpdf /// </Summary> namespace WSE. lcpi {public class createpdf {public createpdf () {// todo: add the constructor logic here //} public class myfontfactory: ifontprovider {public font getfont (string fontname, string encoding, Boolean embedded, float size, int style, basecolor color) {If (fontname = "") {string fontpath = system. web. httpcontext. current. request. physicalapplicationpath + "\ lcpi \ fonts \ msyh. TTF "; basefont bf3 = basefont. createfont (fontpath, basefont. identity_h, basefont. embedded); font fontcontent = new font (bf3, size, style, color); Return fontcontent;} else {font fontcontent = fontfactory. getfont (fontname, size, style, color); Return fontcontent ;}} public Boolean isregistered (string fontname) {return false ;}} /// <summary> // generate a PDF // </Summary> /// <Param name = "html"> </param> /// <Param name = "FILENAME"> </param> // <returns> </returns> Public static Boolean htmltopdf (string HTML, string filename) {Boolean isok = false; try {textreader reader = new stringreader (HTML); // Step 1: creation of a document-object document = new document (pagesize. a4.rotate (), 30, 30, 30, 30); // Step 2: // We create a writer that listens to the document // and directs a XML-stream to a file filename = system. web. httpcontext. current. request. physicalapplicationpath + "\ PDF \" + filename + ". PDF "; filestream FS = new filestream (filename, filemode. create, fileaccess. write, fileshare. readwrite); writable writer = writable writer. getinstance (document, FS); htmlworker worker = new htmlworker (document); document. open (); worker. startdocument (); stylesheet CSS = new stylesheet (); dictionary <string, Object> font = new dictionary <string, Object> (); font. add (htmlworker. font_provider, new myfontfactory (); dictionary <string, string> dict = new dictionary <string, string> (); dict. add (htmltags. bgcolor, "# 01366c"); dict. add (htmltags. color, "#000000"); dict. add (htmltags. size, "25"); CSS. loadstyle ("CSS", dict); List <ielement> P = htmlworker. parsetolist (New streamreader (HTML), CSS, font); For (int K = 0; k <p. count; k ++) {document. add (ielement) P [k]);} export contentbyte PCB = writer. directcontentunder; PCB. setrgbcolorfill (0,255, 0); PCB. setrgbcolorfill (1, 54,108); PCB. rectangle (20,413,800, 42); PCB. fill (); worker. enddocument (); worker. close (); document. close (); reader. close (); isok = true;} catch (exception ex) {isok = false;} finally {} return isok ;}}}

Itextpdf Official Website: http://itextpdf.com/The end

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.