Itextsharp A simple example of generating a PDF

Source: Internet
Author: User

Code:

  <summary>///Compare page to generate PDF functionality. </summary>//<param name= "Country" > Country </param>//<param name= "PNS" >pn</par am>//<param name= "Language" > Languages </param>//<returns> response Objects </returns> Publ            IC string Comparepdf (String country, string[] PNS, String language) {var result = "";            Generate PDF Document document = new document ();            Write this: is to generate a file into a directory in//var directory = HttpContext.Current.Server.MapPath ("~/pdf");            String host = HttpContext.Current.Request.Url.Host;            int port = HttpContext.Current.Request.Url.Port; if (!            Directory.Exists (directory))//{//directory.createdirectory (directory);            }//var fileName = "";            foreach (var item in PNS)//{//FileName + = "_" + Item + "_"; }//filename = "Compare" + FileName + DateTime.Now.ToString ("YYYYMMDDHHMMSS") + ". pdf";            var pdfpath = directory + "\ \" + FileName;            var fileStream = new FileStream (Pdfpath, FileMode.Create);         PDFWriter PW = pdfwriter.getinstance (document, FileStream);            Write this: is to generate the file into memory to go to var MemoryStream = new MemoryStream (); PDFWriter PW = pdfwriter.getinstance (document, MemoryStream);//Generate into memory//data var list = Compare (countr            Y, PNS, language); Document. Open ();//opening file//writing data//registering font string fontpath = HttpContext.Current.Server.MapPath ("~/app_d            ATA ");            Basefont Customfont = Basefont.createfont (Fontpath + "\\Lato-Regular.ttf", basefont.cp1252, basefont.embedded);            var basefont = new Font (Customfont, 0.667f, Font.normal, New Color (68, 68, 68));            var leftfont = new Font (Customfont, 0.667f, Font.Bold, New Color (68, 68, 68));      #region Head      Pdfptable Tablelogo = new pdfptable (3);            TableLogo.DefaultCell.Border = Rectangle.no_border;            TableLogo.DefaultCell.MinimumHeight = 40f;            float[] headwidths = new float[] {60f, 60f, 150f};            Tablelogo.setwidths (headwidths); Logo var logo = iTextSharp.text.Image.GetInstance ("Http://d1fyvoqprbjuee.cloudfront.net/smartfindimages/logo".            PNG "); Logo.            Scaletofit (0.667f, 0.667f);            var Logocell = new Pdfpcell ();            Logocell.paddingleft = -1f;            Logocell.minimumheight = 45f;            Logocell.horizontalalignment = Element.align_left;            Logocell.border = 0;            Logocell.addelement (logo);             Tablelogo.addcell (Logocell);            var headfont = new Font (Customfont, 0.667f, Font.Bold, New Color (68, 68, 68));            var Scell = new Pdfpcell (New Paragraph ("Smartfind", Headfont));            Scell.border = 0;      Scell.paddingleft = 3f;      Scell.paddingbottom = 17f;            Scell.minimumheight = 45f;            Scell.horizontalalignment = Element.align_left;            Scell.verticalalignment = Element.align_bottom;            Tablelogo.addcell (Scell);            var Acell = new Pdfpcell ();            Acell.border = 0;            Acell.minimumheight = 45f;            Acell.paddingbottom = 17f;            Acell.horizontalalignment = Element.align_left;            Acell.verticalalignment = Element.align_bottom;            var accfont = new Font (Customfont, 0.667f, Font.normal, New Color (170, 170, 170));  var acc = new Paragraph ("|            Accessories ", accfont);            Acell.addelement (ACC);            Tablelogo.addcell (Acell); Document.            ADD (Tablelogo); #endregion document.            ADD (New Paragraph ("")); #region The middle table pdfptable table = new Pdfptable (list. Count + 1);//n column table.            Defaultcell.border = 0; Table. Defaultcell.horizontalalignment = element.align_center; Table.            Defaultcell.verticalalignment = Element.align_middle; Determines the number of columns and the column width if (PNS) based on the number of pictures.                Count () = = 1) {float[] widths = new float[] {2f, 3f}; Table.            Setwidths (widths); } else if (PNS.                Count () = = 2) {float[] widths = new float[] {2f, 3f, 3f}; Table.            Setwidths (widths); } else if (PNS.                Count () = = 3) {float[] widths = new float[] {2f, 3f, 3f, 3f}; Table.            Setwidths (widths); } else if (PNS.                Count () = = 4) {float[] widths = new float[] {2f, 3f, 3f, 3f, 3f}; Table.            Setwidths (widths);            }//Left cell var Leftcell = new Pdfpcell (New Paragraph ("Images", Leftfont));           Leftcell.minimumheight = 40f;            Leftcell.backgroundcolor = new Color (242, 242, 242); Leftcell.            HorizontalAlignment = Element.align_center;            Leftcell.verticalalignment = Element.align_middle; Table.            Addcell (Leftcell);            Right cell var Rightcell = new Pdfpcell ();            Rightcell.horizontalalignment = Element.align_center;            Rightcell.verticalalignment = Element.align_middle;            Rightcell.minimumheight = 40f;                foreach (var item in list) {var Imagecell = new Pdfpcell ();                imagecell.padding = 1f; Determines the left margin based on the number of pictures, ensuring that the picture is displayed in the middle. This place does not write well, temporarily such if (list.                Count = = 2) {imagecell.paddingleft = 30f; } if (list.                Count = = 1) {imagecell.paddingleft = 80f; } if (list.                Count = = 3) {imagecell.paddingleft = 10f; }//Make sure the network picture exists if (!string. IsNullOrEmpty (item. URL) && helper.isexists (item. URL + " -218.png")) {var image = ITextSharp.text.Image.GetInstance (item.                    URL + " -218.png"); if (list. Count = = 4) {image.                    Scaletofit (80f, 80f); } else {image.                    Scaletofit (100f, 100f);                } imagecell.addelement (image); } table.            Addcell (Imagecell);            }//product Title Leftcell.phrase = new Paragraph ("Product Title", Leftfont);            var titlefont = new Font (Customfont, 0.667f, Font.normal, New Color (255, 105, 0)); Table.            Addcell (Leftcell); foreach (var item in list) {rightcell.phrase = new Paragraph (item.                Title, Titlefont); Table.            Addcell (Rightcell); }//list Price leftcell.phrase = new ParagrapH ("List price", Leftfont); Table.            Addcell (Leftcell); foreach (var item in list) {rightcell.phrase = new Paragraph (item. Currency + Item.                Price, Basefont); Table.            Addcell (Rightcell);            }//part Number leftcell.phrase = new Paragraph ("part number", Leftfont); Table.            Addcell (Leftcell); foreach (var item in list) {rightcell.phrase = new Paragraph (item.                PN, Basefont); Table.            Addcell (Rightcell); }//facet var first = list.            FirstOrDefault (); foreach (var item in first.) Facets) {leftcell.phrase = new Paragraph (item.                Key, Leftfont); Table.                Addcell (Leftcell); Rightcell.phrase = new Paragraph (item.                Value, Basefont); Table.                Addcell (Rightcell); The rest of the list.                Remove (first);          var other = list;      foreach (var one in other) {rightcell.phrase = new Paragraph (one). Facets.firstordefault (o = O.key = = Item. Key).                    Value, Basefont); Table.                Addcell (Rightcell); }} document.            ADD (table);            #endregion//Footer Pdffooter footer = new Pdffooter (); Footer.            OnEndPage (PW, document); Document.            Close ();            var bytes = Memorystream.toarray ();            result = convert.tobase64string (bytes);        return result; }///<summary>///Footer class///</summary> public class Pdffooter:pdfpageeventhelper {//writ E on top of document public override void OnOpenDocument (PDFWriter writer, document document) {b Ase.            OnOpenDocument (writer, document);            Pdfptable tabfot = new pdfptable (new float[] {1F});            Tabfot.spacingafter = 10F;            Pdfpcell cell; Tabfot.totAlwidth = 300F;            Cell = new Pdfpcell (New Phrase ("Header"));            Tabfot.addcell (cell); Tabfot.writeselectedrows (0,-1, Max, document. Top, writer.        Directcontent);        }//write on start for each page public override void OnStartPage (PDFWriter writer, document document) {base.        OnStartPage (writer, document);            }//write on end of per page public override void OnEndPage (PDFWriter writer, document document) { Base.            OnEndPage (writer, document);            Pdfptable tabfot = new pdfptable (new float[] {1F});            Tabfot.totalwidth = 700f;          TabFot.DefaultCell.Border = 0;            var Footfont = Fontfactory.getfont ("Lato", 0.667f, New Color (60, 60, 60));            String fontpath = HttpContext.Current.Server.MapPath ("~/app_data");            Basefont Customfont = Basefont.createfont (Fontpath + "\\Lato-Regular.ttf", basefont.cp1252, basefont.embedded); var footFont = new Font (Customfont, 0.667f, Font.normal, New Color (170, 170, 170));            Pdfpcell cell; Cell = new Pdfpcell (New Phrase ("@ 2016").            All rights Reserved ", Footfont)); Cell.            VerticalAlignment = Element.align_center; Cell.            Border = 0; Cell.            Paddingleft = 100f;            Tabfot.addcell (cell); Tabfot.writeselectedrows (0,-1, Max, document. Bottom, writer.        Directcontent);        }//write on close of document public override void OnCloseDocument (PDFWriter writer, document document) {base.        OnCloseDocument (writer, document);  }    }

  

<summary>///        Determine if the network file exists///</summary>//        <param name= "url" ></param>        <returns></returns> public        static bool Isexists (string url)        {            try            {                using (new WebClient (). OpenRead (URL)) {}                return true;            }            catch (WebException)            {                return false;            }        }

  

Itextsharp A simple example of generating a PDF

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.