C USES itextsharp to generate the implementation code for the PDF file

  • 2020-05-17 06:13:01
  • OfStack

Project requirements need to generate one PDF document using VS2010, ASP.NET.
I didn't find what I wanted after searching on the Internet for many times, so I went to the official website of itextpdf to read the English documents, and finished the task on time. It is mainly practical.
Create PDF templates using the HTML file:
1 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;

RAGE.TTF is Microsoft operating system font, the directory in C: \ Windows \ Fonts, it is recommended to copy the required font to the project for use, otherwise there will be no reference.
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);

You can use both the LoadStyle method of StyleSheet.
Note that itextsharp has poor support for HTML elements, such as label, div, and other elements, such as alignment, background color, and other attributes. It is recommended to use table tags.
Override Font's GetFont method:

public  class MyFontFactory : IFontProvider
        {
            public  Font GetFont(String fontname,String encoding, Boolean embedded, float size,int style, BaseColor color)
            {
                if (fontname == " Microsoft jas black ")
                {
                    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 need to inherit the IFontProvider interface and override the GetFont method of Font.
Add custom fonts and style sheets 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);

Use PdfContentByte to add background color to the element:

                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, is the need for absolute coordinates, little brother learning thin, and then the time is pressing, can only be so. If Daniel knows a better way, I hope you can give me some advice.
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>
///CreatePDF  Summary of 
/// </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 == " Microsoft jas black ")
                {
                    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 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 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);
                PdfWriter writer = PdfWriter.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]);
                }
                PdfContentByte 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;
        }
    }
}


Related articles: