ITEXT instructions
1. Simple IText
Chapter 1: Create a document
5 steps to create a document: Hello World
Download the first example source file: chap0101.java
This example contains five most important steps that generate PDF files using IText:
Step 1: Create an object instance of a com.lowagie.text.document: Document Document = New Document ();
Step 2: Create a Writer for viewing the document and writing documents based on your output: Pdfwriter.GetInstance (Document, New FileoutputStance ("chap0101.pdf");
Step 3: Open the document: Document.Open ();
Step 4: Write the content to document: Document.Add (New Paragraph ("Hello World");
Step 5: Close the document: Document.close ();
Check results: chap0101.pdf
Test Step 1: Document Object
COM.LOWAGIE.TEXT.Document has three constructors
Public Document (); Public Document (Rectangle PageSize); Public Document (Rectangle PageSize, Int Marginleft, Int Marginright, Int Margintop, Int Marginbottom);
The first constructor calls the second constructor by using PageSize.A4 as a parameter, the second constructor calls the third constructor by using 36 as the value of each page blank.
PageSize (Page Size)
You can create your own rectangular object, you can set a color. In the example chap0102.java, we created a long narrow document with yellow as a background.
Rectangle PageSize = New Rectangle (144, 720); PageSize.SetBackground; Document Document = New Document (Pagesize); Document (PageSize);
This is the result: chap0102.pdf, usually, you don't have to worry about creating this rectangle, because you can use the data in the PageSize.java class, with the following page sizes available: A0-A10, Legal, Letter, Halfletter, _11x17 , Ledger, Note, B0-B5, Arch_a-Arch_e, FLSA, and FLSE. Most of these page sizes are portrait form. If you want them to be landscape form, what you have to do is Rotate () this rectangle: Document Document = New Document (PageSize.A4.Rotate ());
View this example: chap0103.java and its results.
Page blank
When you are creating a document, you can define the page spacing left and right: Document Document = New Document (PageSize.a5, 36, 72, 108, 180); in an example chapter CHAP0104.java (this is its result: chap0104. PDF), you can see this document
0.5
inch
Left distance and
1
inch
The right margin, the upper margin is 1.5
inch
The next distance is
2.5
inch
.
Measurement method
When you are creating a rectangle or if you choose a margin of a page, you may be confused to use the unit: cm, inches or pixels. In fact, the default metric unit is roughly corresponding to a variety of varnish printing units, this metrics are points (Point)
An inch
There are 72 points, if you want to create a PDF document with a A4 rectangular size, you must calculate the number of points:
21 cm
/ 2.54 = 8.2677 Inch 8.2677 * 72 = 595 Points
29.7 cm
/ 2.54 = 11.6929 inch 11.6929 * 72 = 842 Points
The default 36 points are similar to half inches.
Note: If you change the size of the page, this will only affect the next page (see page initialisations). If you change the margins of the page, there will be real-time influence, so be careful.
Test Step 2: Writer object
Once we created a document, we can create one or multiple Writer instances are used to listen documents. All Writers inherited from com.lowagie.text.docwriter. Abstract classes. So there are two possibilities: You can use com.lowagie.text.pdf.pdfwriter to generate documents in PDF format, or you can use com.lowagie.text.html.htmlwriter to generate HTML documents, for example, if you want to produce Tex's documentation, you can write a package: com.lowagie.text.tex.texwriter
Note: I am writing HTML classes for the purpose of testing. You don't actually use it in the product's environment. The results of HTML are not good, and there are many related tools. ITEXT's HTML package is useful for debugging. HTML is more simple than PDF. When generating a PDF file, it is difficult to find the bug that causes the wrong bug, and the PDF is destroyed and cannot open. Therefore, in the test phase I will generate HTML documents at the same time to get the actual location of the error, or an actual object that produces an exception.
There is also com.lowagie.text.xml and com.lowagie.text.rtf two packages, but XML and RTF generated functions are still unstable (see Chapter 7 and 8).
The Writer class constructor is still a private type, you can only generate an instance of the following method: Public Static XXXWriter GetInstance (Document Document, OutputStream OS) Throws DocumentException (xxx is PDF or HTML).
You can create this example: pdfwriter write = pdfwriter.getInstance (Document, New FileoutPutStance ("chap01xx.pdf")); but you will almost no Writer object (unless you want to generate advanced PDFs or you want to use some specific Functions, such as ViewerPreferences or Encryption, so only this instance is sufficient: pdfwriter.getInstance (Document, New FileoutputStance ("chap01xx.pdf");
The first parameter in the first step in creating a document is not important, the second parameter can be any of the output streams, until now, we have always written a document in java.io.fileoutputStream, but In the example chapter, the output stream is a javax.servlet.ServletOutputStream (this is not an independent example, you can only test in the servlet engine), if you use MSIE as a browser, you will see a blank page, this is due to Microsoft's specific version of the browser's bug is caused, in many mailing lists, and the newsgroup of Comp.Text.pdf, you can get a lot of information. If you want to try more difficult examples, try the following code: Calendar.java and Month.java, Tal Liron provides an example of JSP: PDF.jsp. Test Step 3: Metadata Open Document
Metadata
When you add the actual data (content), you may want to add some metadata to your document, you can use the following methods:
public boolean addTitle (String title) public boolean addSubject (String subject) public boolean addKeywords (String keywords) public boolean addAuthor (String author) public boolean addCreator (String creator) public boolean addProducer () public boolean addCreationDate () public boolean addHeader (String Name, String Content)
You can choose your own title, the subject, keyword, author, and creator, but how to add Procedure data has always been: IText (or IText), and add the creation date method to add current system time ( In fact, these two methods are automatically called).
You can also add a custom name to Header, but there is no effect on pdfwriter (because it is just applied to htmlwriter), if we look at the first step: chap0101.java, we will find it in the information window Only PRODUCER and DATE information, if we run CBHAP0106.java, the result is similar to chap0106.pdf but we can see more information in the information window.
As an additional statement of this fact, you can send the document to any output stream; Example 6 sent HTML to System.out
You can see a custom head that has been added "Expires" with an exception: if you add a custom header with htmlwriter.stylesheet, you got the link of Stylesheet
Document.add (new header (htmlwriter.stylesheet, "my.css");
The result is:
Things you need to do before you open your document
You can only add metadata before opening the document. This is the choice made by ITEXT developers, and is submitted in the header mark of the HTML meta. The way to call the open method caused the Writer to write the header to the output stream. Therefore, once the document is opened, there is no way to modify the data. If the PDF header contains any metadata, it looks like:% PDF-1.2% 噌
The first line shows that the document generated is the version of PDF1.2.
The second line indicates the reference manual.
In the PDF document, metadata is controlled by the PDFO object, and when the document is turned off, written by PDFWriter. Therefore, why people cannot add or change the link library at any time, this is the choice of design.
Page initialization
Open methods triggered some initialization actions in different Writers, for example, if you want Watermark or HeaderFooter objects appear on the first page of the document, you must do some initialization actions before opening the document. In order to set the watermark, top, page, page number, and size of the remaining document, etc., it is also necessary to use this action.
When you call the following methods:
public boolean setPageSize (Rectangle pageSize) public boolean add (Watermark watermark) public void removeWatermark () public void setHeader (HeaderFooter header) public void resetHeader () public void setFooter (HeaderFooter footer) public void resetFooter () public void resetPageCount () public void SetPageCount (int Pagen)
The results of these methods will only appear in the next page (when this page is initialized), this can be referred to in Example 7, if you want to test this example, you will need a Watermark.jpg file, the result is chap0107.pdf .
View style
For PDF files, you may need the following method to set a view style:
Public void setViewerPreferences (int preferences)
In Example 8, see the following methods:
writerA.setViewerPreferences (PdfWriter.PageLayoutTwoColumnLeft); writerB.setViewerPreferences (PdfWriter.HideMenubar | PdfWriter.HideToolbar); writerC.setViewerPreferences (PdfWriter.PageLayoutTwoColumnLeft | PdfWriter.PageModeFullScreen | PdfWriter.NonFullScreenPageModeUseThumbs);
As you can see, these parameters can be set to some constants:
When the document is opened, the page plan will be used (select one)
Pdfwriter.pagelayoutsinglepage - Display a page at a time
Pdfwriter.pagelayoutoneColumn - Display all pages with a list
Pdfwriter.pagelayouttwocolumnleft - Show all pages with two columns, odd page in the left column
Pdfwriter.pagelayoutTwocolumnRight - Display all pages with two columns, odd page in right
When the document is opened, the page mode of the document (select one)
Pdfwriter.pagemodeUsenone - No document outline and document thumbnail
Pdfwriter.pagemodeuseoutLines - Document Outline can be seen. Pdfwriter.pagemodeusethumbs - thumbnail visible
Pdfwriter.pagemodefullscreen - full screen mode, no menu bar, Window control, or other form
Pdfwriter.hidetoolbar - Is it visible when the view's application toolbar is visible when the document is activated
PdfWriter.hideMenuBar - Is it visible when the view application menu strip is visible when the document is activated
PdfWriter.hidewINDOWUI - Whether to hide the user interface (such as scroll bar and navigation control) in the document window, only the contents of the document.
Pdfwriter.fitwindow - Whether the window for setting the document is suitable for the first page size
PdfWriter.centerWindow - Whether the window for setting the document is in the center of the screen
The page mode of the document defines how the document should be displayed in a full screen mode. This is only in the page mode.
PageModefullscreen is meaningful.
Pdfwriter.nonfullscreenPageModeUsenone - No document outline and document thumbnail
Pdfwriter.nonfullscreenPageModeUseoutlines - Document Outline
Pdfwriter.nonfullscreenPageModeUsethumbs - thumbnail visible
Note: You can only call these methods from pdfwriter classes.
encryption
Another thing you open in your document is setting encryption (that is, you want to encrypt the PDF file), in order to achieve this, you need to use the following methods:
Public Void SetNCryption (Boolean Stregth, String Userpassword, Int Permissions);
Stregth is one of the following two constants:
Pdfwriter.streamth40bits: 40
Pdfwriter.stregth128bits: 128 bits (only in Acrobat Reader 5.0 or higher)
Userpassword and OwnerPassword can be empty or 0 length, in which case OwnerPassword is replaced by a random string.
Permissions is set to the following constants or
Pdfwriter.Allowprinting
Pdfwriter.AllowModifyContents
Pdfwriter.AllowCopy
Pdfwriter.AllowModifyanNotations
Pdfwriter.allowfillin
Pdfwriter.AllowScreenReaders
Pdfwriter.Allowassembly
Pdfwriter.AllowdeGradedprinting
This feature shows in Example 9 and Example 10
Writer.setencryption (pdfwriter.streamth40bits, null, null, pdfwriter.allowcopy); chap0109.pdf can be opened without password, but users can not print, adjust documents
Writer.setencryption (pdfwriter.stregth128bits, "userpass", "ownerpass", pdfwriter.allowcopy | But you open chap0110.pdf, you are asked to provide a password (enter 'userpass'), because Joined AllowPrinting Preference, you can print documents for any questions. Test Step 4: Add content
In the different examples of steps 1 to 3,