In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to open source. Net PDF printing component itextSharp, for this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
When it comes to printing, I am afraid it is not unfamiliar to many people, both developers and non-computer professionals will be exposed to printing. For project development, there will be many places to print, and in .NET projects, there are many options for printing, such as original IE web page printing, crystal reports, JS plug-in printing, export document printing, and today's use of itextSharp components to achieve PDF printing and so on.
There are many components to implement PDF printing in .NET, such as PDFsharp, Report.NET, sharpPDF, itextSharp and so on. Today, we will briefly introduce itextSharp components.
I. Overview of itextSharp components:
1.iText is the PDF library, which allows you to create, adjust, check, 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 and take advantage of the many interactive features available in PDF.
(3)。 Add bookmarks, page numbers, watermarks and other functions to existing PDF files.
(4)。 Split or connect pages from existing PDF files; fill out interactive forms.
(5)。 That is, dynamically generate or manipulate PDF documents to Web browsers.
IText is used by Java,.NET,Android and GAE developers to enhance applications with PDF functionality. The iTextSharp is a. Net port.
Some features of 2.itextSharp:
(1) .PDF generation.
(2) .PDF operations (stamping watermarks, 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 itextSharp components. If you need more in-depth information about itextSharp components, you can take a closer look at the API documentation and itextSharp product introduction. Https://sourceforge.net/projects/itextsharp/#overview .
II. Core classes and methods of itextSharp components:
When it comes to printing, the first thing we need to consider in our project is what we need to print. First of all, there should be a concept of documents in our mind. In the process of programming, the word "document" is everywhere, which can be either a broad concept or a narrow concept. Broad "document" refers to a container, used to store some elements; narrow "document" refers to the actual file type.
For a printed "document", look at the broad concept that the document contains elements, nodes, and so on. 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. ItextSharp components can insert paragraphs, tables, pictures and other information, it is very convenient to complete the functions we need to complete.
Paragraph: the text in the report; Image: the picture in the report; PdfPTable: table; PdfPCell: cells.
The Open () method of the 1.Document class opens the 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 ();}}
As you can see in the above code, when we open a document, we will set the document size, document page margins and other information.
The Add () method of the 2.Paragraph class adds elements to the 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 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 Chunks {get;} int Type {get;}}
The above add () method adds elements to the paragraph. We can see that the parameter is an interface "IElement". Let's take a look at this interface next. The main elements of the interface are blocks. We see that when you add elements to a paragraph, you can add List,Image,Paragraph,Chunk.
3.Image.GetInstance () gets the picture 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");}
There are many ways to obtain image instances based on parameters, such as Image,PdfTemplate,PRIndirectReference,byte [], Stream,string, Uri and so on. The image instances of ItextSharp based on Image and byte [] are given above.
ScaleAbsolute () of 4.Image: sets the picture 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;}
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 5.Anchor class: the handling of overridden links.
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 overridden in this class to handle information about links.
6.PageSize: sets the type of paper.
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 Landscap; 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 classes, we can see that we can set the type of paper that needs to be printed, which can be selected according to the actual situation. At the bottom we see two methods, one is to set the paper size by PageSize (), and the other is to draw a rectangle by GetRectangle ().
The above is a brief introduction to some classes and methods of itextSharp components, the introduction of tables, cells and other classes will not continue, interested can check the source code information.
3. ItextSharp component example:
The above introduces the background and characteristics of the itextSharp component, as well as the core classes and methods of the component. Here is a simple example of the operation of the itextSharp component, which is just a simple introduction.
/ private Font _ font; / document size / private Rectangle _ rect; / document object / private readonly Document _ document; / basic font / private BaseFont _ basefont / constructor / public PDFOperation () {_ rect = PageSize.A4; _ document = new Document (_ rect);} / constructor / page size (such as "A4") public PDFOperation (string type) {if (string.IsNullOrEmpty (type)) {throw new ArgumentNullException (type) } SetPageSize (type); _ document = new Document (_ rect) } / Constructor / Page size (such as "A4") / / content distance from left border / / content distance from right border / / content distance from top border / content distance from bottom border public PDFOperation (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);} / set font / public void SetBaseFont (string path) {if (string.IsNullOrEmpty (path)) {throw new ArgumentNullException (path);} _ basefont = BaseFont.CreateFont (path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED) } / set font size / font size public void SetFont (float size) {_ font = new Font (_ basefont, size) } / set page size / Page size (such as "A4") 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 Instantiate document / document-related information (such as path, opening method, etc.) public void GetInstance (Stream os) {if (os = = null) {throw new ArgumentNullException ("os");} PdfWriter.GetInstance (_ document, os) } / Open document object / document-related information (such as path, opening method, etc.) public void Open (Stream os) {if (os = = null) {throw new ArgumentNullException ("os");} GetInstance (os); _ document.Open () } / close the open document / public void Close () {_ document.Close ();} / add a paragraph / content / font size public void AddParagraph (string content, float fontsize) {SetFont (fontsize); var pra = new Paragraph (content, _ font) _ document.Add (pra) } / / add paragraph / content / / font size / one alignment (1 is center, 0 is left 2 is the number of blank lines after the segment (0 is the default) / / the number of blank lines before the segment (0 is the default) / the line spacing (0 is the default) 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) {pra.SpacingAfter = spacingAfter;} if (spacingBefore! = 0) {pra.SpacingBefore = spacingBefore;} if (multipliedLeading! = 0) {pra.MultipliedLeading = multipliedLeading;} _ document.Add (pra) } / / add Picture / Picture path / one alignment (1 for center, 0 for left, 2 for right) / / Picture width (0 is the default) The picture height 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 CompareOfFloatsByEqualityOperator 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); add link / link text / font size / link address 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) Add link point / link text / font size / link name 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 relatively simple and are mainly used to briefly introduce the use of components. If we need to make the component design more general, we can rewrite the related classes and methods of the component, and we can develop a set of cs or bs programs to realize the graphical operation of the component and generate the file template. The file template can serialize the relevant information (json or binary), load the model directly in the project, and bind the data in the template to realize the dynamic configuration of pdf printing.
The development of this program is generally difficult, if you are interested can develop a set of tools, you can better achieve our project pdf printing function.
The above introduces the relevant information of the itextSharp component, in this series of component introduction, the introduction of the component is relatively simple, in order to introduce this component, in the actual development, we can choose the corresponding component according to the actual situation, the component is not absolutely good or bad, only the appropriate scenario.
Net itextSharp printing components on how to share the answer here, I hope the above content can be of some help to you, if you still have a lot of doubts have not been solved, you can follow the industry information channel to learn more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.