Detailed description of the free and stable. net pdf print component itextSharp (. NET Component Introduction 8) and itextsharp
In this. the introduction series of the net component has been supported by many park friends. Some park friends (such as the top of data and the great gods such as [Qin shiyue]) have also provided me with corresponding suggestions, I am trying to correct the problem. I hope you will forgive me for any shortcomings. While spreading some simple knowledge, I also got some improvement, which is the biggest benefit I feel. Knowledge needs to be disseminated. In the process of dissemination, the learner should be promoted, and in the process of communication, the thinker should be expected, I hope that I can make a contribution in this dissemination process. Due to your limited ability, I hope you will forgive me for the errors and some inadequate explanations during blog writing.
After selling out the feelings above, let's get started.
I am afraid that printing is not unfamiliar to many people. Developers and non-computer professionals will be able to access printing. There will be a lot of places for printing in project development. in the. NET project, there are many printing methods, such as the original IE web page printing, Crystal Reports, and JS plug-ins to print and export documents, and the use of the itextSharp component to implement PDF printing.
There are many components that implement PDF printing in. NET, such as PDFsharp, Report. NET, sharpPDF, and itextSharp. Today we will briefly introduce itextSharp components.
I. itextSharp component Overview:
1. iText is a PDF library that allows you to create, adjust, check, and maintain portable document format files (PDF ):
(1) generate files and reports based on data in XML files or databases.
(2). Create maps and books, and use the functions available for numerous interactions in PDF.
(3) add bookmarks, page numbers, watermarks, and other functions to an existing PDF file.
(4). Split the existing PDF file or connect to the page. Fill in the interactive form.
(5) dynamically generate or manipulate PDF documents to a Web browser.
IText uses Java,. NET, Android, and GAE developers to enhance their applications with the PDF function. ITextSharp is the. NET port.
2. Some features of itextSharp:
(1). PDF generation.
(2). PDF operation (stamping watermark, merging/splitting PDF files ,...).
(3) Fill in the PDF form.
(4). XML function.
(5). Digital Signature.
The above is a brief introduction to some features of the itextSharp component. If you need more in-depth information about the itextSharp component, You can carefully view the API documentation and itextSharp product introduction. Https://sourceforge.net/projects/itextsharp/#overview.
Ii. Core classes and methods of itextSharp components:
When talking about printing, the first thing we need to consider in our project is what we need to print. In the brain, we should first have a document concept. In our programming process, the word "document" is everywhere. This can be a broad concept, it can also be a narrow concept. A broad "document" refers to a container used to store some elements. A narrow "document" refers to the actual file type.
For printed "documents", take a look at the broad concept. The documents contain elements and nodes. When printing an organization, we need to create a document, write elements, nodes, and other information, and finally combine them into what we need to print. The itextSharp component can insert paragraphs, tables, images, and other information to easily complete the functions we need to complete.
Paragraph: text in the report; Image: Image in the report; PdfPTable: Table; partition pcell: cell.
1. Document class Open () method: Open a Document Object.
public virtual void Open(){ if (!this.close) { this.open = true; } foreach (IDocListener listener in this.listeners) { listener.SetPageSize(this.pageSize); listener.SetMargins(this.marginLeft, this.marginRight, this.marginTop, this.marginBottom); listener.Open(); }}
The code above shows that when opening a document, we will set the document size, document margins, and other information.
2. Paragraph class Add () method: Add elements to a Paragraph.
public override bool Add(IElement o){ if (o is List) { List element = (List) o; element.IndentationLeft += this.indentationLeft; element.IndentationRight = this.indentationRight; base.Add(element); return true; } if (o is Image) { base.AddSpecial((Image) o); return true; } if (o is Paragraph) { base.Add(o); IList<Chunk> chunks = this.Chunks; if (chunks.Count > 0) { Chunk chunk = chunks[chunks.Count - 1]; base.Add(new Chunk("\n", chunk.Font)); } else { base.Add(Chunk.NEWLINE); } return true; } base.Add(o); return true;}
public interface IElement{ // Methods bool IsContent(); bool IsNestable(); bool Process(IElementListener listener); string ToString(); // Properties IList<Chunk> Chunks { get; } int Type { get; }}
The add () method above adds an element to a paragraph. We can see that the parameter is an interface "IElement". Let's take a look at this interface. The main element of the interface is block. We can see that when adding elements to a Paragraph, you can add List, Image, Paragraph, and Chunk.
3. Image. GetInstance () to obtain the Image instance.
public static Image GetInstance(Image image){ if (image == null) { return null; } return (Image) image.GetType().GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(Image) }, null).Invoke(new object[] { image });} public static Image GetInstance(byte[] imgb){ int num = imgb[0]; int num2 = imgb[1]; int num3 = imgb[2]; int num4 = imgb[3]; if (((num == 0x47) && (num2 == 0x49)) && (num3 == 70)) { GifImage image = new GifImage(imgb); return image.GetImage(1); } if ((num == 0xff) && (num2 == 0xd8)) { return new Jpeg(imgb); } if (((num == 0) && (num2 == 0)) && ((num3 == 0) && (num4 == 12))) { return new Jpeg2000(imgb); } if (((num == 0xff) && (num2 == 0x4f)) && ((num3 == 0xff) && (num4 == 0x51))) { return new Jpeg2000(imgb); } if (((num == PngImage.PNGID[0]) && (num2 == PngImage.PNGID[1])) && ((num3 == PngImage.PNGID[2]) && (num4 == PngImage.PNGID[3]))) { return PngImage.GetImage(imgb); } if ((num == 0xd7) && (num2 == 0xcd)) { return new ImgWMF(imgb); } if ((num == 0x42) && (num2 == 0x4d)) { return BmpImage.GetImage(imgb); } if ((((num == 0x4d) && (num2 == 0x4d)) && ((num3 == 0) && (num4 == 0x2a))) || (((num == 0x49) && (num2 == 0x49)) && ((num3 == 0x2a) && (num4 == 0)))) { RandomAccessFileOrArray s = null; try { s = new RandomAccessFileOrArray(imgb); Image tiffImage = TiffImage.GetTiffImage(s, 1); if (tiffImage.OriginalData == null) { tiffImage.OriginalData = imgb; } return tiffImage; } finally { if (s != null) { s.Close(); } } } throw new IOException(MessageLocalization.GetComposedMessage("the.byte.array.is.not.a.recognized.imageformat"));}
This method is used to obtain Image instances by parameters, such as Image, template, PRIndirectReference, byte [], Stream, string, and Uri, the preceding figure shows an Image instance that obtains ItextSharp Based on image and byte.
4. ScaleAbsolute () of the Image: sets the Image information.
public void ScaleAbsolute(float newWidth, float newHeight){ this.plainWidth = newWidth; this.plainHeight = newHeight; float[] matrix = this.Matrix; this.scaledWidth = matrix[6] - matrix[4]; this.scaledHeight = matrix[7] - matrix[5]; this.WidthPercentage = 0f;}
The code above shows that the picture information mainly includes the height, width, and arrangement information.
5. Anchor class Process () method: rewrite the link processing method.
public override bool Process(IElementListener listener){ try { bool flag = (this.reference != null) && this.reference.StartsWith("#"); bool flag2 = true; foreach (Chunk chunk in this.Chunks) { if (((this.name != null) && flag2) && !chunk.IsEmpty()) { chunk.SetLocalDestination(this.name); flag2 = false; } if (flag) { chunk.SetLocalGoto(this.reference.Substring(1)); } else if (this.reference != null) { chunk.SetAnchor(this.reference); } listener.Add(chunk); } return true; } catch (DocumentException) { return false; }}
As you can see from the above method, this method is overwritten in this class to process information related to the link.
6. PageSize: Set the paper type..
public class PageSize{ // Fields public static readonly Rectangle _11X17; public static readonly Rectangle A0; public static readonly Rectangle A1; public static readonly Rectangle A10; public static readonly Rectangle A2; public static readonly Rectangle A3; public static readonly Rectangle A4; public static readonly Rectangle A4_LANDSCAPE; public static readonly Rectangle A5; public static readonly Rectangle A6; public static readonly Rectangle A7; public static readonly Rectangle A8; public static readonly Rectangle A9; public static readonly Rectangle ARCH_A; public static readonly Rectangle ARCH_B; public static readonly Rectangle ARCH_C; public static readonly Rectangle ARCH_D; public static readonly Rectangle ARCH_E; public static readonly Rectangle B0; public static readonly Rectangle B1; public static readonly Rectangle B10; public static readonly Rectangle B2; public static readonly Rectangle B3; public static readonly Rectangle B4; public static readonly Rectangle B5; public static readonly Rectangle B6; public static readonly Rectangle B7; public static readonly Rectangle B8; public static readonly Rectangle B9; public static readonly Rectangle CROWN_OCTAVO; public static readonly Rectangle CROWN_QUARTO; public static readonly Rectangle DEMY_OCTAVO; public static readonly Rectangle DEMY_QUARTO; public static readonly Rectangle EXECUTIVE; public static readonly Rectangle FLSA; public static readonly Rectangle FLSE; public static readonly Rectangle HALFLETTER; public static readonly Rectangle ID_1; public static readonly Rectangle ID_2; public static readonly Rectangle ID_3; public static readonly Rectangle LARGE_CROWN_OCTAVO; public static readonly Rectangle LARGE_CROWN_QUARTO; public static readonly Rectangle LEDGER; public static readonly Rectangle LEGAL; public static readonly Rectangle LEGAL_LANDSCAPE; public static readonly Rectangle LETTER; public static readonly Rectangle LETTER_LANDSCAPE; public static readonly Rectangle NOTE; public static readonly Rectangle PENGUIN_LARGE_PAPERBACK; public static readonly Rectangle PENGUIN_SMALL_PAPERBACK; public static readonly Rectangle POSTCARD; public static readonly Rectangle ROYAL_OCTAVO; public static readonly Rectangle ROYAL_QUARTO; public static readonly Rectangle SMALL_PAPERBACK; public static readonly Rectangle TABLOID; // Methods static PageSize(); public PageSize(); public static Rectangle GetRectangle(string name);}
In the above class, we can see that we can set the type of the paper to be printed and can choose according to the actual situation. We can see two methods at the bottom. One is PageSize () to set the paper size, and the other is GetRectangle () to draw a rectangle.
The above is a brief introduction to some classes and methods of the itextSharp component. The introduction of tables, cells, and other classes will not continue. If you are interested, you can view the source code information on your own.
Iii. itextSharp component instance:
The background, features, and core classes and methods of the itextSharp component are described above. Here we provide a simple itextSharp component operation example. This example is just a simple introduction.
/// <Summary> /// Font /// </summary> private font _ Font; /// <summary> /// document size /// </summary> private Rectangle _ rect; /// <summary> /// Document Object /// </summary> private readonly document _ Document; /// <summary> /// base font /// </summary> private BaseFont _ basefont; /// <summary> /// constructor /// </summary> public writable operation () {_ rect = PageSize. a4; _ document = new Document (_ rect);} // <summary> // Constructor /// </Summary> /// <param name = "type"> page size (for example, "A4") </param> public parameter operation (string type) {if (string. isNullOrEmpty (type) {throw new ArgumentNullException (type);} SetPageSize (type); _ document = new Document (_ rect );} /// <summary> /// constructor /// </summary> /// <param name = "type"> page size (such as "A4 ") </param> /// <param name = "marginLeft"> content distance from the Left Border </param> /// <param name = "marginRight"> content distance from the Right Border </param> /// <Param name = "marginTop"> content distance from upper border </param> // <param name = "marginBottom"> content distance from lower border </param> public border operation (string type, float marginLeft, float marginRight, float marginTop, float marginBottom) {if (string. isNullOrEmpty (type) {throw new ArgumentNullException (type);} SetPageSize (type); _ document = new Document (_ rect, marginLeft, marginRight, marginTop, marginBottom );} /// <summary> /// set the font /// </Summary> public void SetBaseFont (string path) {if (string. isNullOrEmpty (path) {throw new ArgumentNullException (path);} _ basefont = BaseFont. createFont (path, BaseFont. IDENTITY_H, BaseFont. NOT_EMBEDDED );} /// <summary> /// set the font /// </summary> /// <param name = "size"> font size </param> public void SetFont (float size) {_ font = new Font (_ basefont, size) ;}/// <summary> /// set the page size /// </summary>/ // <Param name = "type"> page size (such as "A4") </param> public void SetPageSize (string type) {if (string. isNullOrEmpty (type) {throw new ArgumentNullException (type);} switch (type. trim () {// enumerate the required document paper size case "A3": _ rect = PageSize. a3; break; case "A4": _ rect = PageSize. a4; break; case "A8": _ rect = PageSize. a8; break ;}} /// <summary> /// instantiate the document /// </summary> /// <param name = "OS"> file-related information (such as path and open mode) </param> Public void GetInstance (Stream OS) {if (OS = null) {throw new ArgumentNullException ("OS");} specified writer. getInstance (_ document, OS );} /// <summary> /// open the Document Object /// </summary> /// <param name = "OS"> related documentation information (such as path, open Mode, etc.) </param> public void Open (Stream OS) {if (OS = null) {throw new ArgumentNullException ("OS");} GetInstance (OS ); _ document. open () ;}/// <summary> /// close the opened document /// </summary> public voi D Close () {_ document. close ();} /// <summary> /// Add a paragraph // </summary> /// <param name = "content"> content </param> /// <param name = "fontsize"> font size </param> public void AddParagraph (string content, float fontsize) {SetFont (fontsize); var upa = new Paragraph (content, _ font); _ document. add (HPA );} /// <summary> /// Add a paragraph // </summary> /// <param name = "content"> content </param> /// <param name = "fontsize"> font size </par Am> /// <param name = "alignment"> alignment (1 is center, 0 is left, and 2 is right) </param> /// <param name = "spacingAfter"> Number of empty lines after a segment (0 is the default value) </param> /// <param name = "spacingBefore"> Number of blank lines before a segment (0 is the default value) </param> /// <param name = "multipliedLeading"> line spacing (0 is the default value) </param> public void AddParagraph (string content, float fontsize, int alignment, float spacingAfter, float spacingBefore, float multipliedLeading) {SetFont (fontsize); var upa = new Paragr Aph (content, _ font) {Alignment = alignment}; if (spacingAfter! = 0) {upa. SpacingAfter = spacingAfter;} if (spacingBefore! = 0) {upa. SpacingBefore = spacingBefore;} if (multipliedLeading! = 0) {upa. multipliedLeading = multipliedLeading;} _ document. add (HPA );} /// <summary> /// add an image /// </summary> /// <param name = "path"> image path </param> /// <param name = "alignment"> alignment (1 is centered, 0 indicates the left and 2 indicates the right.) </param> // <param name = "newWidth"> image width (0 indicates the default value, if the width is greater than the page width, the page is scaled proportionally.) </param> // <param name = "newHeight"> the image height </param> public void AddImage (string path, int alignment, float newWidth, float newHeight) {if (string. IsNullOrEmpty (path) {throw new ArgumentNullException (path);} var img = Image. GetInstance (path); img. Alignment = alignment; // ReSharper disable once ready if (newWidth! = 0) {img. scaleAbsolute (newWidth, newHeight);} else {if (img. width> PageSize. a4.Width) {img. scaleAbsolute (_ rect. width, img. width * img. height/_ rect. height) ;}}_ document. add (img );} /// <summary> /// add link /// </summary> /// <param name = "content"> link text </param> /// <param name = "fontSize"> font size </param> // <param name = "reference"> link address </param> public void AddAnchorReference (string content, float fontSize, string reference) {if (string. isNullOrEmpty (content) {throw new ArgumentNullException (content);} SetFont (fontSize); var auc = new Anchor (content, _ font) {Reference = reference}; _ document. add (auc );} /// <summary> /// add a link // </summary> /// <param name = "content"> link text </param> /// <param name = "fontSize"> font size </param> // <param name = "name"> Link name </param> public void AddAnchorName (string content, float fontSize, string name) {if (string. isNullOrEmpty (content) {throw new ArgumentNullException (content);} SetFont (fontSize); var auc = new Anchor (content, _ font) {Name = name}; _ document. add (auc );}
The above examples are simple and mainly used to briefly introduce the usage of components. To make the component design more universal, we can rewrite the related classes and methods of the component, and develop a set of cs or bs programs to implement graphical operations of the component, graphical operations to generate a file template. File templates can serialize the relevant information (json or binary), load the model directly in the project, and bind the data to the template to achieve dynamic configuration of pdf printing.
This program is generally difficult to develop. If you are interested, you can develop a set of tools to better implement the project pdf printing function.
Iv. Summary:
The information about the itextSharp component is introduced above. In this series of component introduction, the introduction of components is relatively simple. It aims to introduce this component to you. In actual development, we can select the appropriate components based on the actual situation. The components are not absolutely good or bad, but only suitable scenarios.
If there are any errors or deficiencies in the above explanation, I hope you will forgive me and give more comments and suggestions. We also hope that you can support the customer's home.