C#:itext Structuring PDF files

Source: Internet
Author: User

IText Construction PDF file

1.1 Build Document

Document is the container for all the elements of the PDF file that we want to generate, so to generate a PDF document, you must first define a Document object.
Document has three types of constructors:
public Document ();
Public Document (Rectangle pageSize);
Public Document (Rectangle pageSize, float marginleft, float marginright, float margintop, float marginbottom);
The first method does not define any parameters, and the resulting document will automatically take A4-sized paper; The second method allows the user to define the size of the paper, while the third method allows the user to define not only the paper size but also the left and right margins of the page.
We define a document object with the following statement, with a page size of A4 and a margin of 50.
Document document = new Document (PAGESIZE.A4, 50, 50, 50, 50);
If the page needs to be in horizontal mode, just modify the first parameter:
Document doc = new document (PageSize.A4.rotate (), 50,50,50,50);

1.2 Specify Document type is PDF

Once you have defined the Document object, you need to specify the type of the document object immediately. Because the use of the Itext library not only supports the creation of PDF documents, but also supports HTML, RTF, XML, Word and many other document types, we want to generate PDF document format, we need to call the following method:

PDFWriter writer = pdfwriter.getinstance (document,
New FileOutputStream ("C:\\itexttest.pdf"));
If you want to create a document other than PDF, you can choose to create HTMLWriter, Rtfwriter, XmlWriter, RtfWriter2 (note: Word document) objects based on the type of document you want to create. The specific supported document types can be viewed in the Itext API documentation.
You can set the appearance of the resulting PDF document, such as whether the menu bar, toolbar, etc. are displayed, as follows:
Writer.setviewerpreferences (Pdfwriter.hidemenubar);
Writer.setviewerpreferences (Pdfwriter.hidetoolbar);
Writer.setviewerpreferences (Pdfwriter.hidemenubar
| Pdfwriter.hidetoolbar);
The first statement hides the menu bar, the second statement hides the toolbar, and the third statement enables the hiding of the menu bar and toolbar.

1.3 towards Document Write content in

So far we've successfully created a PDF document that we can now write data into.
In order to write the data, the first thing we want to do is open the current document:
Document.open ();
The common elements that make up PDF files are chunk, Paragraph, Phrase, List, Image, table, and so on, which we introduce briefly.

1.4 Chunk

Chunk is the smallest element that can be added to the document, and you can add it directly to the document, Document.add (New Chunk ("ZipCode"));
You can assign a color to a chunk object, a font, but a chunk object can have only one color and font, which means that chunk is an atomic object, and you can't have different properties for a different character in a chunk object.
An interesting feature of the chunk object is the ability to underline, underline, and delete lines.
Chunk title = new Chunk ("title", Titlefont);
Title.setunderline (Color.Black, 2.0f, 0.0f, 24.0f, 0.0f, Pdfcontentbyte.line_cap_butt); Title.setunderline (Color.Black, 2.0f, 0.0f, -12.0f, 0.0f,pdfcontentbyte.line_cap_butt);
By calling the Setunderline () method and setting the parameters, you can add segments anywhere in the chunk object, and you can set the color, thickness, and shape of the segment (round, flat, and so on).
In addition to directly adding the chunk object to the document, you can also use it as part of a more advanced PDF element, such as:
Paragraph p = new Paragraph ();
Chunk Chunk = new Chunk ("General manager");
P.add (chunk);

1.5 Paragraph

Paragraph, as the name implies, is the meaning of a paragraph, like a paragraph in Word, you can define its spacing before, paragraph spacing, paragraph alignment, left and right indent:
P.setalignment (element.align_justified);

P.setindentationleft (15f);

P.setindentationright (15f);
P.setspacingbefore (15f);
P.setspacingafter (5f);
The first statement defines the alignment of the paragraph p, the second statement defines the left indent distance of P, the third statement defines the right indent distance of P, the fourth statement defines the spacing before the P, and the fifth statement defines the spacing after p, and the corresponding value can be defined according to the actual need.
After the good one paragraph object is defined, it is added to the document.
Document.add (P);

1.6 Phrase

Phrase implements a function similar to paragraph, and if you want to add a paragraph to the document, we still find it appropriate to use the Paragraph object.

Phrase is constructed in many ways, and usually we only need a new Phrase (string string) or a new Phrase (string string, font font) to create a Phrase object. But there are constructors like phrase (float leading, string string). The parameter leading sets the line spacing of the phrase object, and when the phrase content exceeds one line, the function of the parameter is displayed. Usually leading should be a positive value, but if you set it to a negative value, you will find something interesting to happen.

1.7 List

The list class implements an effect similar to "bullets and numbering" in Word, and you can create a list object by using the following method:
List L = new List (true, false, 10);
L.add (New ListItem ("First item of List"));
L.add (New ListItem ("Second Item of List"));
The first parameter of the new list (true, False, 10) indicates whether you are creating a numbered list, true indicates that a numbered list is created, and the second parameter indicates whether to use letters for numbering, true for letters, and false for numbers The third parameter is the indent of the list.
Lists are made up of list items, and ListItem is a list item that can be added to the list after the list item has been created by using the Add () method.
You can also add a string directly to the list of lists:
L.add ("Third item of List");
You can also create a new list object and add it to the current list object:
List sublist = new List (false, True, 10);
Sublist.add ("First subitem of third item");
Sublist.add ("Second Subitem of third item");
L.add (sublist);
Finally, the list object is added to the document.
Document.add (l);

1.8 Table and the pdfptable

To create a table in a PDF file, Itext provides us with two classes, table and pdfptable. There are advantages to both approaches, in general, table-type tables are relatively simple to implement, but if the tables that need to be implemented are more complex, sometimes you must use the Pdfptable class.
Let's start with a brief introduction to how to generate tables using the table class:
Table T = new Table (3, 2);
T.setbordercolor (Color.White);
T.setpadding (5);
T.setspacing (5);
T.setborderwidth (1);
The first line of the program creates a 3x2 table, followed by a program that sets the table's border color, cell text spacing, cell spacing, and border width, respectively. If the user does not want the table border to appear, simply set the border color to match the background color. Because the default document background color is white, we also set the border color of the table to white.
A table is made up of cells. Here's how to create a cell:
Cell C1 = new cell ("Header1");
T.addcell (C1);
This allows us to write the content "Header1" in the first column of the first row of the table. Using the same method, we can continue to add content to the table. You'll notice that we don't specify the cell's position in the table, so where does the program add the cells we added? By default, the program adds cells from the first column of the first row to the cell from left to right, when the first row is full, and then fills the table from left to right, starting with the first column in the second row.
You can also call Addcell (cell Acell, int row, int column) or Addcell (cell Acell, point alocation) method if you do not want to write to the table in the default order of the program, You can put content directly into the table location you specify.
You can add a table to another table, that is, the table is nested, and the way it is implemented is inserttable (table table).
Table subtable = new Table (2, 2);
Subtable.addcell ("1.3.1");
Subtable.addcell ("1.3.2");
Subtable.addcell ("1.3.3");
T.inserttable (subtable);
The Pdfptable class generation table is implemented like this:
pdfptable table = new pdfptable (3);
This implements a 3-column table. You can also specify the width of each column in advance, using the following method to implement a table:
Float[] widths = {15f, 25f, 60f};
pdfptable table = new pdfptable (widths);
The above method defines a 3-column table with a width of 15%, 25%, and 60% for each column. Normally generated tables appear on the page by default at a scale of 80%, you need to call Pdfptable's setwidthpercentage (float widthpercentage) method to set the table width, and if you set the parameter to 100, the table will fill the entire width of the page.
You can also set the absolute width of the table: Table.settotalwidth (300), which sets the width of the table to 300px. However, if the contents of the table exceed 300px, the width of the table will be extended automatically. If you want to lock the table at 300px, you also need to add Table.setlockedwidth (true) settings.
When creating a Pdfptable object, you only need to specify the number of columns, rather than specifying the number of rows, because the number of rows can be added automatically. Once the table is created, you need to insert the cell element inside. The Pdfptable object adds a cell with the release of Addcell (Object object). Object objects can be Pdfpcell, String, Phrase, Image, or the Pdfptable object itself, which is a table nested within a table.
To implement some special tabular forms, you need to merge the cells. The Pdfpcell class provides a setcolspan (int colspan) method for merging horizontal cells, and the parameter colspan specifies the number of cells to merge. However, there is no Setrowspan () method in the Pdfpcell class, meaning you cannot merge vertical cells. However, you can use nested tables to achieve a similar effect by using Table.addcell (pdfptable table) to add a table to a cell.
The usual table requires a header, and you can define what each column of the table represents, as in the following list of insured items, where the first line is the header we need:
The contents of the header are also added to the table through the Table.addcell () method, and you need to call the Table.setheaderrows (1) method to tell the program that this is your table header. When the table content is large, a page cannot be displayed, the program will automatically page the table, it is necessary to let the program know what is the table header, the program will be on each page of the table header is added.
For some reason, you may have to pin the table to a location on the page, Pdfptable also provides us with this method: table.writeselectedrows (int rowstart, int rowend, float xPos, float YPos, Pdfcontentbyte Canvas). You can refer to the API documentation to understand what each parameter means.

1.9 Add header Footer

For multi-page documents, the page number flag is not limited, which involves the method of adding the header footer.
The header and footer class in the document container is called HeaderFooter, and there are two ways to create a headerfooter:
HeaderFooter (Phrase before, boolean numbered);
HeaderFooter (Phrase before, Phrase after);
HeaderFooter class can calculate the page number for you and write to the header or footer, the parameter numbered in method one is to let you choose whether to display page numbers, before and after parameters refer to what you want to display before and after the page number. Add the form that you want to show page numbers as "page I," through New HeaderFooter ("P", "page") method can be implemented.
With the setalignment (int alignment) method, you can set whether the header footer is left-aligned, right-aligned, or centered.
The default HeaderFooter object displays a border, which you can hide or select to display on one side of the border by means of the SetBorder () method.
Eventually you need to tell the program whether to display the HeaderFooter object as a header or a footer, and the corresponding method is Document.setheader () and Document.setfooter ().
Here is an example of implementing a header footer.
HeaderFooter footer = new HeaderFooter (New Phrase ("the", Fontfooter), New Phrase ("page", Fontfooter));
Footer.setborder (Rectangle.no_border);
Footer.setalignment (Element.align_bottom);
Document.setfooter (footer);
After the PDF document is generated, you may find that the header and footer of the document starts only from the second page, and the first page does not have the header footer you expect. This is because you add the wrong location, in order to produce a header footer on the first page of the document, you must put the above program before the Document.open () code.

1.10 Close Document

With the above steps, you can basically implement a desired PDF document. The last thing you need to do is call the Document.close () method to close the document. Of course, due to the Java anomaly mechanism, do not forget to put the above program in Try...catch () ... To catch a program exception that may occur.

2.1 Merging multiple PDF file

There are times when you need to combine several ready-made PDF documents into one document in development, and we only need to use pdfcopyfields to implement them. Let's say we have two files named Source1.pdf, Source2.pdf, and our goal is to merge them into a file called Concatenated.pdf.
The method is to get the source PDF file with the Pdfreader object first:
Pdfreader reader1 = new Pdfreader ("Source1.pdf");
Pdfreader reader2 = new Pdfreader ("Source2.pdf");
So our program gets the file content that we want to merge, and then we define a Pdfcopyfields object:
Pdfcopyfields copy = new Pdfcopyfields (New FileOutputStream ("Concatenated.pdf"));
Specifies that the generated file is concatenated.pdf. It then writes the read-in content to the object:
Copy.adddocument (Reader1);

Copy.adddocument (Reader2);
To close the Pdfcopyfields object:
Copy.close ();
You will find that a new PDF file is generated, which contains the contents of the Source1.pdf and source2.pdf two files.

Sorry: The URL from the source is not allowed to add up

C#:itext Structuring PDF files

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.