introduction
When it comes to printing, I'm afraid many people are familiar with it. Both developers and non-computer professionals will come into contact with printing. There are many places to use printing in project development. In .NET projects, there are many ways to choose printing, such as original IE web page printing, crystal reports, JS plug-in printing, export document printing, and the use of the itextSharp component to implement PDF printing, etc. mentioned today.
There are many components that implement PDF printing in .NET, such as PDFsharp, sharpPDF, itextSharp, etc. Today, I will mainly briefly introduce the itextSharp component.
1.itextSharp component overview:
The PDF library allows you to create, adjust, inspect and maintain portable document format files (PDF):
(1). Generate files and reports based on data from XML files or databases.
(2). Create maps and books, leveraging numerous interactions available in PDF.
(3). Add bookmarks, page numbers, watermarks and other functions to existing PDF files.
(4). Split or connect the page from an existing PDF file; fill in the interactive form.
(5). It can generate or manipulate PDF documents dynamically to the web browser.
iText uses Java, .NET, Android and GAE developers to enhance applications with PDF functionality. iTextSharp is the .NET port.
Some characteristics of:
(1). PDF generation.
(2). PDF operation (stamp watermark, merge/split PDF files,...).
(3).Fill in PDF form.
(4).XML function.
(5). Digital signature.
The above is a brief introduction to some features of the itextSharp component. If you need to have a deeper understanding of the itextSharp component, you can carefully view the API documentation and itextSharp product introduction. /projects/ithtsharp/.
2.itextSharp component core classes and methods:
When it comes to printing, the first thing we need to consider in our projects is what we need to print. In the brain, there should be a concept of documents. In the process of programming, the word "document" is everywhere. This can be a broad concept or a narrow concept. A broad "document" refers to a container to store some elements; a narrow "document" refers to the actual file type.
For printed "documents", let's take a look at the broad concepts, which include elements and nodes, etc. When organizing printing, we need to create documents, write information such as elements and nodes, and finally combine them into what we need to print. The itextSharp component can insert paragraphs, tables, pictures and other information, which can easily complete the functions we need to complete.
Paragraph: text in the report; Image: picture in the report; PdfPTable: table; PdfPCell: cell.
Class Open() method: Open the document object.
public virtual void Open() { if (!) { = true; } foreach (IDocListener listener in ) { (); (, , , ); (); } }
As shown in the above code, we will set the document size, document page margin and other information when opening the document.
Class Add() method: Add elements to the paragraph.
public override bool Add(IElement o) { if (o is List) { List element = (List) o; += ; = ; (element); return true; } if (o is Image) { ((Image) o); return true; } if (o is Paragraph) { (o); IList<Chunk> chunks = ; if ( > 0) { Chunk chunk = chunks[ - 1]; (new Chunk("\n", )); } else { (); } return true; } (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 above add() method is to add elements to the 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 a block. We see that when adding elements to a paragraph, you can add List, Image, Paragraph, Chunk.
() Get an image instance.
public static Image GetInstance(Image image) { if (image == null) { return null; } return (Image) ().GetConstructor( | , 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 (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 == [0]) && (num2 == [1])) && ((num3 == [2]) && (num4 == [3]))) { return (imgb); } if ((num == 0xd7) && (num2 == 0xcd)) { return new ImgWMF(imgb); } if ((num == 0x42) && (num2 == 0x4d)) { return (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 = (s, 1); if ( == null) { = imgb; } return tiffImage; } finally { if (s != null) { (); } } } throw new IOException(("")); }
There are many ways to obtain image instances based on parameters, such as Image, PdfTemplate, PRIndirectReference, byte[], Stream, string, Uri, etc. The above is a sample of obtaining the ItextSharp based on Image and byte[].
ScaleAbsolute(): Sets picture information.
public void ScaleAbsolute(float newWidth, float newHeight) { = newWidth; = newHeight; float[] matrix = ; = matrix[6] - matrix[4]; = matrix[7] - matrix[5]; = 0f; }
As can be seen from the above code, the information for setting the picture mainly includes height, width, arrangement and other information.
The Process() method of the class: the processing method of rewriting the link.
public override bool Process(IElementListener listener) { try { bool flag = ( != null) && ("#"); bool flag2 = true; foreach (Chunk chunk in ) { if ((( != null) && flag2) && !()) { (); flag2 = false; } if (flag) { ((1)); } else if ( != null) { (); } (chunk); } return true; } catch (DocumentException) { return false; } }
As can be seen from the above method, this method is rewritten in this class to process related information about the link.
: 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 paper we need to print, and we can choose according to the actual situation. At the bottom we see two methods, one is PageSize() to set the paper size, and the other is GetRectangle() to draw the rectangle.
The above is a brief introduction to some classes and methods of the itextSharp component. The introduction to tables, cells and other classes will no longer continue. Those who are interested can view the source code information by themselves.
Three.itextSharp component instance:
The above introduces the background, features, as well as the core classes and methods of the itextSharp component. Here is a simple example of the operation of the itextSharp component. This example is just a brief introduction.
/// <summary> /// Font /// </summary> private Font _font; /// <summary> /// Document size /// </summary> private Rectangle _rect; /// <summary> /// Document object /// </summary> private readonly Document _document; /// <summary> /// Basic font /// </summary> private BaseFont _basefont; /// <summary> /// Constructor /// </summary> public PDFOperation() { _rect = PageSize.A4; _document = new Document(_rect); } /// <summary> /// Constructor /// </summary> /// <param name="type">Page size (such as "A4")</param> public PDFOperation(string type) { if ((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">Distance from the left border</param> /// <param name="marginRight">Distance from the right border</param> /// <param name="marginTop">Distance from the upper border</param> /// <param name="marginBottom">Distance from the lower border</param> public PDFOperation(string type, float marginLeft, float marginRight, float marginTop, float marginBottom) { if ((type)) { throw new ArgumentNullException(type); } SetPageSize(type); _document = new Document(_rect, marginLeft, marginRight, marginTop, marginBottom); } /// <summary> /// Set font /// </summary> public void SetBaseFont(string path) { if ((path)) { throw new ArgumentNullException(path); } _basefont = (path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); } /// <summary> /// Set font /// </summary> /// <param name="size">Font size</param> public void SetFont(float size) { _font = new Font(_basefont, size); } /// <summary> /// Set page size /// </summary> /// <param name="type">Page size (such as "A4")</param> public void SetPageSize(string type) { if ((type)) { throw new ArgumentNullException(type); } switch (()) { //Enum 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">Document-related information (such as path, opening method, etc.)</param> public void GetInstance(Stream os) { if (os == null) { throw new ArgumentNullException("os"); } (_document, os); } /// <summary> /// Open the document object /// </summary> /// <param name="os">Document-related information (such as path, opening method, etc.)</param> public void Open(Stream os) { if (os == null) { throw new ArgumentNullException("os"); } GetInstance(os); _document.Open(); } /// <summary> /// Close the open document /// </summary> public void Close() { _document.Close(); } /// <summary> /// Add paragraph /// </summary> /// <param name="content">Content</param> /// <param name="fontsize">Font size</param> public void AddParagraph(string content, float fontsize) { SetFont(fontsize); var pra = new Paragraph(content, _font); _document.Add(pra); } /// <summary> /// Add paragraph /// </summary> /// <param name="content">Content</param> /// <param name="fontsize">Font size</param> /// <param name="alignment">Alignment (1 is centered, 0 is left, and 2 is right)</param> /// <param name="spacingAfter">Number of empty lines after segment (0 is the default value)</param> /// <param name="spacingBefore">Number of empty lines before segment (0 is the default value)</param> /// <param name="multipliedLeading">Line spacing (0 is the default)</param> public void AddParagraph(string content, float fontsize, int alignment, float spacingAfter, float spacingBefore, float multipliedLeading) { SetFont(fontsize); var pra = new Paragraph(content, _font) { Alignment = alignment }; if (spacingAfter != 0) { = spacingAfter; } if (spacingBefore != 0) { = spacingBefore; } if (multipliedLeading != 0) { = multipliedLeading; } _document.Add(pra); } /// <summary> /// Add picture /// </summary> /// <param name="path">Picture path</param> /// <param name="alignment">Alignment (1 is centered, 0 is left, and 2 is right)</param> /// <param name="newWidth">Image width (0 is the default value, if the width is greater than the page width, it will be scaled by ratio)</param> /// <param name="newHeight">High picture</param> public void AddImage(string path, int alignment, float newWidth, float newHeight) { if ((path)) { throw new ArgumentNullException(path); } var img = (path); = alignment; // ReSharper disable once CompareOfFloatsByEqualityOperator if (newWidth != 0) { (newWidth, newHeight); } else { if ( > PageSize.) { (_rect.Width, * / _rect.Height); } } _document.Add(img); } /// <summary> /// Add a 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 ((content)) { throw new ArgumentNullException(content); } SetFont(fontSize); var auc = new Anchor(content, _font) { Reference = reference }; _document.Add(auc); } /// <summary> /// Add link point /// </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 ((content)) { throw new ArgumentNullException(content); } SetFont(fontSize); var auc = new Anchor(content, _font) { Name = name }; _document.Add(auc); }
The above examples are relatively simple, mainly used to briefly introduce the usage of components. If we need to design the component more general, we can rewrite the relevant classes and methods of the component, and we can develop a set of CSS or BS programs to implement graphical operations of the component and generate file templates in graphical operations. File templates can serialize relevant information (json or binary), directly load the model in the project, and bind the data into the template to realize dynamic configuration of PDF printing.
The development difficulty of this program is average. If you are interested, you can develop a set of tools yourself, which can better realize the PDF printing function of our project.
4. Summary:
The above introduces the relevant information of the itextSharp component. In this series of component introductions, the introduction of components is relatively simple, and aims to introduce this component to everyone. In actual development, we can choose the corresponding component by ourselves according to the actual situation. There is no absolute good or bad component, only suitable scenarios.
If there are any errors and shortcomings in the above explanation, I hope everyone will forgive and give more opinions and suggestions. I hope everyone supports it.
This is the article about C# using itextsharp to print pdf implementation code. For more related C# itextsharp to print pdf content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!