Foreword
Lishui Automobile Transportation Group Co., Ltd. Information Center, Qiaitan PDF file is currently a popular electronic document format. In the development of software automation (OA), it is often used in this format, but introduces how to make PDF format files. Very few, search online, reposted, the same "violent" crack method, the code snippet is as follows:
Streamwriter PPDF = New StreamWriter (FilePath);
ArrayList Xrefs = new arraylist ();
Float ypos = 0f;
Long streamstart = 0;
Long streamend = 0;
Long streamlen = 0;
String strpdfMessage = NULL;
// PDF document header information
StrpdfMessage = "% PDF-1.1 / N";
ConvertTobyTeandAddTREAM (STRPDFMESSAGE);
Xrefs.Add (MPDF.Length);
StrpdfMessage = "1 0 obj / n";
ConvertTobyTeandAddTREAM (STRPDFMESSAGE);
StrpdfMessage = "<< / length 2 0 r >> / n";
ConvertTobyTeandAddTREAM (STRPDFMESSAGE);
StrpdfMessage = "stream / n";
ConvertTobyTeandAddTREAM (STRPDFMESSAGE);
......
I saw the above production method, my glasses broke three, if I use the original way to make satisfactory PDF files, it is a genius. Later, I saw the introduction of the control of the PDF file from a website (Website: http://itextsharp.sourceforge.net/index.html), and the Darkness of the Truna, the Trial Download Test, and I really make it very easily. Want PDF file, because the website is English, the content is more, read very laborious, after solving his own problems, seeing many netizens are also depressed for PDF files, and decided to translate this content into Chinese, Because of my English level, many places are hard to understand, so the quality of translation is not very satisfied, please ax, but most can understand. The purpose of this article is to solve some of the urgent urgent needs of some netizens. The second is to throw bricks. If you are willing to translate the content of the website accurately, it is a great fortune.
To generate a PDF file with this method, you need two controls: ITextSharp.dll and ICsharpcode.sharpziplib.dll, because the sample code is too much, I put all the code all, put it in another file "sample code .doc" All of these resources, I am in the "安 廷" folder on my FTP site (ftp://202.107.251.26), the file name "PDF file production .rar" (two other two in the compression package) The RAR compressed file is the source code for two controls. For you to learn research, you can download the corresponding resources here, or download them directly to the original website.
In order to facilitate debugging and narrative, all examples are DOS console programs, and the Windows program is exactly the same. Follow the steps below to create a debugged item: 1, open the VS2003;
2. Click Menu "File" → "New" → "Project", select "Visual C # item" in the project type, select "Console Application" in the template, enter the name of the file, such as "Makepdf", specify storage Path, then click OK button;
3. Right-click "Reference" in "Solution Explorer", select "Add Reference" from the pop-up menu, select "Browse" in the ".NET" option, add the two previously mentioned previously ,As shown below:
4, add two references at the top of the code window:
Using ITextsharp.Text;
Using itextsharp.text.pdf;
At this point, the preparation is completed.
Simple application of ITEXT
Chapter 1 Create a Document
Create a PDF file using IText 5: HelloWord.
The first step is to create an instance of an ITEXTSHARP.TEXT.Document object:
Document Document = New Document ();
Step 2, create a Writer instance for this document:
Pdfwriter.getInstance (Document, New FileStream ("chap0101.pdf", filemode.create));
The third step, open the current document
Document.open ();
Step 4, add content for the current document:
Document.Add (New Paragraph ("Hello World"));
Step 5, close the document
Document.close ();
The complete code is found in the sample code 0101.
In the example, it is not difficult to see that it is very simple to make a PDF file.
Note: If you will be "Document.Add (New Paragraph (" Hello World "));" String "Hello Word" is changed to Chinese, such as "This is my first PDF file", generated As a result, you must have a big disappointment because there is no Chinese display in the generated PDF file. Don't worry, in Chapter 9, you need to explain the font problem, Chinese display will also solve it. If you can't display Chinese correctly, there is no need. Translation of this article.
Let's take a detailed introduction to these steps.
Create a Document instance:
ItexTsharp.text.document-object has three constructor:
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 as a parameter as a parameter, and the second constructor calls the third constructor with a 36-pound margin of each side.
u page size:
You can create your own pages via the specified colors and size, sample code 0102 Create a pale light yellow background page:
Rectangle PageSize = New Rectangle (144, 720);
PageSize.backgroundColor = New Color (0xFF, 0xFF, 0xDE); Document Document = New Document (PageSize);
Typically, you don't have to create such pages, and you can choose from below the page size:
A0-A10, Legal, Letter, Halfletter, _11x17, Ledger, Note, B0-B5, Arch_a-Arch_e, FLSA and FLSE
In most cases, use the vertical page, if you want to use the horizontal page, you only need to use the rotate () function:
Document Document = New Document (PageSize.A4.Rotate ());
The details code 0103 is shown in detailed code.
u page margin:
When you create a file, you can also define the margins: up, left, left, right page:
Document Document = New Document (PageSize.a5, 36, 72, 108, 180);
In the sample code 0104, you can see that there is a 0.5-inch left distance and 1 inch right distance, the upper distance is 1.5 inches, and the lower distance is 2.5 inches.
Description:
When creating a rectangle or setting the margin, you may want to know what metron, inches or pixels, in fact, the default metric is based on the type of mortgage, such as 1 inch = 72 pounds, if you want to create a rectangle in the PDF in the A4 page, you need to calculate the following data:
21 cm / 2.54 = 8.2677 inches
8.2677 inches * 72 = 595 pounds
29.7 cm / 2.54 = 11.6929 inches
11.6929 inches * 72 = 842 pounds
The default width is 36 pounds, half inches.
If you modify the page size, you only affect the next page, if you modify the margin, it affects all, so caution.
For the initial value of the page, please refer to the third step.
Step 2 Create a WRITER instance
Once Document is created, we can create multiple Writer of this document, all of which inherit the abstract class "ITextsharp.Text.docwriter".
At the same time, there is another situation, you can generate a document PDF file with itemsharp.text.pdf.pdfwriter, if you want to create a Tex document, you can use the ITextsharp.Text.Tex.Texwriter package.
The constructor of the Writer class is private, you can only create an instance by the following method:
Public Static XXXWriter GetInstance (Document Document, Stream OS); (xxx is PDF or XML)
You can create an instance by the following method:
PdfWriter Writer = Pdfwriter.GetInstance (Document, New FileStream ("chap01xx.pdf");
But you almost never use Writer instances (unless you want to create advanced PDF or want to use some very special functions, such as ViewerPreferences or Encryption). So by the following approach is sufficient: pdfwriter.getinstance (Document, New FileStream ("chap01xx.pdf");
When creating a document in the first step, the first parameter is not large, and the second parameter can be any kind of stream, so we have always written Document to the file using System.IO.FileStream, Sample Code 0105 Used system.io.MemoryStream (this is not an independent example, you must test these code in Servlet Engine. Step 3 Open Document
U summary
Before you write any actual data, you may want to write some summary about this document through the following ways:
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, theme, keyword, author, create a program, but the following product information will always be added: ITextSharp (reference) and create time (actually these two methods are automatically called).
You can also add a custom name to "header information", but this does not have any effect on PDFWriter. If you look at the "Document Properties" of the PDF file generated by the instance code 0101, we can see only PDF creation programs and products. Date, and more information in the Document Properties box of the sample code 0106.
Want to do what you want to do in Document:
You can only add a summary before the Open method call, which is a choice provided by the ITEXT development tool.
In HTML, the header information is placed in the middle of the header identification of the document, and the OPEN method will cause the header information to write flow, so it cannot be changed after the Document is opened.
PDF header information does not include a summary, it looks similar to:
% PDF-1.2
The line shows the generated document is a version of the PDF format of 1.2. In the PDF, the summary is saved in the PDFOFO object. When the document is turned off, it has been written in pdfwriter, so there is no change to why can't modify the library to meet any Technical reasons for adding or changing summary
u page initialization
Open method will generate initialization events at different Witer, for example, if you need a watermark or header-angle object appears in the beginning of the document, you need to add these before opening the document, the same Set this document other page watermark, header, page corner, number of pages, and size.
When calling the following methods:
Public Bool SetPageSize (Rectangle PageSize)
Public Bool Add (Watermark Watermark)
Public void removewatermark ()
Setting Header Property
Public void resetHeader ()
Setting Footer Property
Public void recsetfooter ()
Public void resetPageCount ()
Setting pageCount Property
The result of the result can only be seen in the next new page (when calling the initialization method on this page), see the sample code 0107, you must prepare a picture called Watermark.jpg, as shown below: U reader parameters :
You can specify some readers (such as Adobe Reader) parameters for your PDF files.
Public void setViewerPreferences (int preferences)
In the sample code 0108, some parameters are specified:
Writera.SetViewerPreferences (pdfwriter.pagelight);
Writerb.setViewerPreferences (pdfwriter.hidemen | pdfwriter.hidetoolbar);
Writerc.setViewerPreference (pdfwriter.pagelight | pdfwriter.pagemodefullscreen | pdfwriter.nonfullscreenpagemodeusethumbs);
As you can see, the parameters can use some constants:
l When the file is opened, the page layout uses one of the following:
Pdfwriter.pagelayoutsinglepage - only one page is displayed
Pdfwriter.pagelayoutoneColumn - single column display
Pdfwriter.pagelayouttwocolumnleft - Dual Lie Show, odd page is left
Pdfwriter.pagelayouttwocolumnright - Dual Lie Show, odd page in right
l When the file is opened, the page mode is used below:
Pdfwriter.pagemodeUsenone - no major steel nor displays thumbnails
Pdfwriter.pagemodeuseoutLines - Display Outline
Pdfwriter.pagemodeUsethumbs - Show thumbnails
PDFWRITER.PAGEMODEFULLSCREEN - full screen mode, no menu, Windows control, or any other Windows visible control
l Pdfwriter.hidetoolbar - Whether to hide read programs (such as Adobe Reader) when the document is activated
l Pdfwriter.HideMenubar - Whether the menu of the reader is hidden when the document is activated.
l Pdfwriter.Hidewindowui - Whether the interface element of the reading program is hidden when the document is activated, such as scroll bar, navigation bar, etc., but only reserves the document display.
l Pdfwriter.fitwindow - Adjust the document window size to show the first page.
l Pdfwriter.centerWindow - Whether to put the document window in the center of the screen
l In full screen mode, specify how to display interface elements (select one)
Pdfwriter.nonfullscreenPageModeUsenone - None Show big steel nor thumbnails
Pdfwriter.nonfullscreenPageModeUseoutlines - Show big steel
Pdfwriter.nonfullscreenPageModeUsethumbs - Show thumbnails
Note: You can only call these methods in class PDFWriter.
u encryption
One thing to do before opening the document is encryption (if you want the document encryption), you can use this purpose, you can use the following method: public void setncryption (Boolean Stregth, String Userpassword, String Ownerpassword, int permissions);
Stregth is one of the two constants below:
Pdfwriter.streamth40bits: 40
Pdfwriter.stregth128bits: 128 (Acrobat Reader 5.0 and above)
Userpassword and OwnerPassword can be empty or zero length, in which case OwnerPassword will be replaced by a random string
Permissions is one of the following constants:
Pdfwriter.Allowprinting
Pdfwriter.AllowModifyContents
Pdfwriter.AllowCopy
Pdfwriter.AllowModifyanNotations
Pdfwriter.allowfillin
Pdfwriter.AllowScreenReaders
Pdfwriter.Allowassembly
Pdfwriter.AllowdeGradedprinting
This feature see example code 0109 and sample code 0110.
Writer.setencryption (pdfwriter.stregth40bits, null, null, pdfwriter.allowcopy);
The file generated by the sample code 0109 can be opened without a password, but the user cannot print and modify this document.
Writer.seetencryption (pdfwriter.stregth128bits, "userpass", "ownerPass", pdfwriter.allowcopy | pdfwriter.allowprinting;
When you try to open the file generated by the sample code 0110, you will ask your password ('userpass') because you add the allowprinting parameter, you can print this document without any problems.
Fourth step Add content
In the different examples of the first step to the third step, you may have encountered some objects such as Phrase, Paragraph, etc. In the next few chapters, all of these issues will be explained in detail.
Sometimes you may want a Writer to deliberately ignore the behavior generated by Document, such as sample code 0111:
When we have created two writers: Writera and Writerb:
Pdfwriter Writera = Pdfwriter.GetInstance (Document, New FileStream ("Chap0111a.pdf", filemode.create));
Pdfwriter Writerb = Pdfwriter.getInstance (Document, New FileStream ("chap0111b.pdf", filemode.create);
We can create two documents with fine difference:
Writera.Pause ();
Document.add (New Paragraph ("This Paragraph Will Only Be Added To Chap0111b.pdf, Not to Chap0111a.pdf");
Writera.Resume ();
You can compare the file: chap0111a.pdf and chap011b.pdf distinction
Step 5, close the document
Close Document is very important because it will turn off the running Writer and write the content to the file, which is last called, you should always turn off the document. Advanced Topic: Reading PDF files
This part of the content describes that ITEXT can only generate files in PDF format and cannot resolve PDF format files, which is no longer translated.
Chapter 2 block, short sentences and paragraphs
Piece
Block (chunk) is the minimum unit of text that can be added to the document, blocks can be used to build other infrastructure such as short sentences, paragraphs, anchor points, etc., blocks are a string with determining fonts, to add blocks to documents All other layout variables are defined. In the following line, we created a block for "Hello World", red, slope, Courier font, dimension 20:
Chunk chunk = new chunk ("Hello World", FontFactory.getFont (FontFactory.courier, 20, Font.italic, New Color (255, 0, 0)));
u Typical font 1:
In this guide, in addition to the ninth chapter (you can learn to use other fonts here), we will always use typical fonts 1, these are different typical fonts 1:
Courier (this word is wide)
Helvetica
· Times Roman
Symbol
· Zapfdingbats
U underline / delete line
If you want some blocks to underline or delete the line, you can simply do the font style:
Chunk chunk1 = new chunk ("this text is underlined", FontFactory.getFont (FontFactory.helvetica, 12, font.underline));
Chunk chunk2 = new chunk ("this font is of type italic | strikethru", FontFactory.getFont (FontFactory.helvetica, 12, Font.italic | Font.Strikethru);
U Script / subscript
There are several ways to call in the block, most of which will be described in the next chapter, which only introduces a method setTextrise (FLOAT F) in this chapter. You can write blocks in the subscript or subscript.
U block background
If you want to change the background of the block, you can use MethodSetBackground (color color). This will add a color rectangle below the block text:
Ck.setBackground (New Color (0xFF, 0xFF, 0x00));
In the sample code 0101, you can overview the examples of typical font 1 and a method using setTextrise, setBackground.
Short sentence
The short sentence is a series of blocks with a specific spacing (distance between two lines) as the parameters, a short sentence has a master font, but some blocks in the short sentence have fonts different from the primary font, you have more Multi-selection to create a short sentence, some specifically see the code 0202.
U 古 希
Because ancient Greek is often used, there is a feature in the constructor of the class phrase: use a string as a parameter (if you want to avoid this, you can only use block work without using the string), just as you are in the example As seen in code 0203, this feature automatically changes all fonts in the range of 913 to 937 (divided 903) and 945 to 969 (ancient Greece) to Greek symbols. u non-main
It is said that this is a feature, it is better to say a defect, but in any case, this makes it possible to create a non-primary short sentence or paragraph, which will generate a temporary role written by the downward (see sample code 0204). If you want to move some locations to above on a page may be useful.
Note that when you cross the upper side, you can't check, there is no way to let you return to the previous page.
paragraph
The paragraph is a series of blocks and / or short sentences. Like a short sentence, the paragraph has a determined spac. The user can also specify a regeneration; reserved a certain blank on the side and / or right side, the paragraph can be aligned, right or aligned. Each paragraph added to the document will automatically be a row. There are several ways to build a paragraph, such as:
Paragraph P1 = New Paragraph (New Chunk ("this is my first paragraph.", FontFactory.GetFont (FontFactory.helvetica, 12)))))
Paragraph P2 = New Paragraph ("This Is My Second Paragraph.", FontFactory.GetFont (FontFactory.helvetica, 12)))))
Paragraph P3 = New Paragraph ("this is my think", FontFactory.GetFont (FontFactory.helvetica, 12));
All some objects will be added to the paragraph:
P1.Add ("You CAN Add Strings,"); P1.Add (New Chunk ("You CAN Add Chunks"); P1.Add ("Or You CAN Add Phrases.");
Note: A paragraph has one and only one spacing. If you add a short sentence or block of a different font, the original spacing is still valid, you can change the spacing through setleading, but all content in the paragraph will use new spacing. See the example code 0205.
u Keep the overall performance of paragraphs
In the sample code 0206, we used the setkeeptogether (TRUE) method to try to put a paragraph on the same page, which is not always valid, give an example, the first paragraph cannot be just in a page, so it is divided into Two parts. The second paragraph is placed in the second page, but the third paragraph will go to the third page.
Continuation of the font
You should master some rules for the font continuation, the application of these rules see the sample code 0207, when we create a short sentence with the specified font (non-default font), then add more content, then add more content, the font of the initial object The style will be continued, please see "Hello 1!" And "Hello 2":
Phrase myphrase = new phrase ("Hello 2!", New font (font.times_new_roman, 8, font.bold);
Myphrase.add (New Phrase ("Some Other Font", New Font (Font.helvetica, 8, Font.ITAlic))); Myphrase.Add (New Phrase ("this is the end of the sense./n", New Font (font.times_new_roman, 8, font.italic));
Document.add (myphrase);
We started by Times New Roman bold, add some text to use the Helvetica font without specifying the style, we found that the text was changed to a bold, when we add some text using the Times New Roman font and the slope, the result becomes Bold.
If we use FontFactory to create a font, the font style will not continue because FontFactory uses additional technologies to build a font:
Myphrase = New phrase ("Hello 1bis!", FontFactory.getFont (FontFactory.Times_New_Roman, 8, Font.Bold);
Myphrase.Add (New Phrase ("Some Other Font", FontFactory.getFont (FontFactory.helvetica, 8, Font.italic));
Myphrase.Add (New Phrase ("this is the end of it sincence./n", fontfactory.getfont (fontfactory.times_new_roman, 8, font.italic)));
Document.add (myphrase);
In the above code, the text wind font using the Helvetica font is not specified (neither a bold is not a bevel). The additional text using Times New Roman is only displayed as a bevel.
You also saw that we added a paragraph, add this paragraph as a short sentence.
Paragraph myparagraph = new paragraph ("Hello 1!", New Font (font.times_new_roman, 8, font.bold);
Myparagraph.Add (New Paragraph ("this is the end of the sense.", FontFactory.getFont (new font.times_new_roman, 8)))
Document.add (myparagraph);
You can do this, but will lose your font style, you don't have to create a paragraph in any font.
Myparagraph = new paragraph (12);
Myparagraph.Add (New Paragraph ("Hello 3!", New Font (Font.Times_New_Roman, 8, Font.Bold));
MyParagraph.Add (New Paragraph ("this is the end of the sentence.", New font (font.times_new_roman, 8, font.italic));
Document.add (myparagraph);
If you use a phrase object, you also lose the continuation of the font style:
Myphrase = new phrase (12);
Myphrase.Add (New Phrase ("Hello 4!", New Font (font.times_New_Roman, 8, Font.Bold)); Myphrase.Add ("this is the end of the sense.", NewFont (Font) .Times_new_roman, 8, font.italic));
Document.add (myphrase);
u change split
Usually, when text cannot be placed in a row, the text will be split into different parts, and IText will first find the split, if not found, the text will be truncated at the end of the line. There are some predetermined segments such as "" spaces and "-" even characters, but you can use the SetSplitcharacter method to overwrite these default values. In the sample code 0208, you can see how a block is split when it reaches the end. The separator is then changed to the point ".", The row is split at the character.
Chapter 3 Anchor, List and Comments
Anchor
We all know the hypertext link in HTML. When we click some statements, you can jump to other pages on the web. This function can also be implemented in the PDF. In fact, in the eleventh chapter, the entire chapter is introduced to the PDF link, but this is a more advanced application of IText. In this chapter, we handle simple IText.
If you want to add an external link in the document (for example, using the URL link to other documents on the web), you can simply use the Anchor object, which is derived from the phrase object, the same method is the same. Only two additional methods define two additional variables: SetName and SetReference.
External link example:
Anchor Anchor = New Anchor ("Website", FontFactory.getFont (FontFactory.helvetica, 12, Font.underline, New Color (0, 0, 255)));
Anchor.reference = "http://itextsharp.sourceforge.net";
Anchor.name = "Website";
If you want to add an internal link, you need to select the different name of the link, just like your phase in HTML as an anchor point. To achieve this, you need to add a "#".
Internal link example:
Anchor Anchor1 = New Anchor ("this is an internal link");
Anchor1.name = "link1";
Anchor Anchor2 = New Anchor ("Click Here To Jump To The Internal Link");
Anchor.reference = "# link1";
An example of these two links See the sample code 0301.
List
Through class List and ListItem, you can add a list to the PDF file, you can also choose whether to sort for the list.
Sort sequence representation example:
List list = new list (TRUE, 20);
List.Add (New ListItem ("first line");
List.add (New ListItem ("The Second Line Is Longer to See What Happens Once The end of the line is reached. Will IT Start On a new line?"))
List.Add (New ListItem ("Third Line")); the result is as follows:
First line
THE SECOND LINE IS LONGER TO SEE What HAPPENS ONCE The end of the line is reached. Will IT Start ON A New Line?
Third Line
No sorting examples are as follows:
List overview = new list (false, 10);
OverView.add (New ListItem ("this is an item");
Overview.add ("this is another item");
The results are as follows:
This is an item
This is another item
You can change the list symbol by setLismysymbol method:
// Use a string as a list symbol
List1.lismysymbol = "*";
// Use Chunk as a list symbol (contain "•" character)
List2.lismysymbol = New Chunk ("/ U2022", FontFactory.getFont (FontFactory.helvetica, 20));
// Use a picture as a list symbol
List3.listsymbol = new chun (Image.GetInstance ("Mybullet.gif"), 0, 0);
You can also use the setINDentationLeft and SetindentationRight method to set up a constitution, the rearrangement of the list symbol is set in the constructor. For more example, see Sample Code 0302.
Comment
IText supports annotations of different styles.
u Text Notes:
You can add a small text into your document, but it is not part of the documentation, the comment has title and content:
Annotation a = new annotation
Authors,
"Maybe It's Because I Wanted to Be An Author Myself That I Wrote ITEXT.");
u External link Note:
You need to specify a clickable rectangle and a string (URL description) or URL object:
Annotation Annot = New Annotation (100F, 700F, 200F, 800F, New URL ("http://www.lowagie.com));
Annotation Annot = New Annotation (100F, 700F, 200F, 800F, "http://www.lowagie.com");
u External PDF file link comment:
You need to specify a clickable rectangle and a string (file name) and destination file or page number.
Annotation Annot = New Annotation (100F, 700F, 200F, 800F, "Other.PDF", "Mark");
Annotation Annot = New Annotation (100F, 700F, 200F, 800F, "Other.PDF", 2);
u Specify behavior link comment
You need to specify a clickable rectangle and a specified behavior:
Annotation Annot = New Annotation (100F, 700F, 200F, 800F, PDFAction.FirstPage); U Application Link Note:
You need to specify a clicking rectangle and an application:
Annotation Annot = New Annotation (300F, 700F, 400F, 800F, "C: //winnt/notepad.exe", null, null, null;
We do not need to specify a location on the page, and IText will handle it. You can see the ITEXT Add Text Notes under the current position on the page, the first line under the first line, the second below the end of the short sentence.
All other comments require a rectangular area you want to match. In the sample code 0304, we draw some squares (used by the function will be introduced in Chapter 10), add some link comments to each square.
Chapter 4 Page Page, Chapter, Region and Drawing Objects
Use a large number of simple items described in Chapters Third to Chapters to avoid more advanced topics (ninth to twelfth chapters), in keeping in the functions of these simple object restrictions, a large number of complex features in the third part.
Page footbrow
The Headerfooter object can add header and footer to the document per page. Such a header or footer contains a standard short sentence (if needed) and the current page number, if you need more complex headers and footers (a few pages using the form or a few pages), please read the twelfth chapter.
In the sample code 0401, you can see that we first add a footer containing the page number without any border.
Headerfooter Footer = New Headerfooter (New Phrase ("this is page:"), true);
Footer.Border = Rectangle.NO_Border;
Document.footer = Footer
We can also use the following constructor:
Headerfooter Footer = New Headerfooter (New Phrase ("this is page"), new phrase ("."));
The constructor knows that you want to add a page number and place it in two short sentences. If you just set a headerfooter without changing the border, the header or footer has a straight line.
Headerfooter Header = New Headerfooter (New Phrase ("This Is A Header Without a page number"), FALSE);
Document.header = header;
Section and region
In Chapter 11, how to build an appearance of a tree, if you only need a simple chapter and (sub) area, you can automatically build a tree with the Chapter object and the Section object:
Paragraph Ctitle = New Paragraph ("This Is Chapter 1", ChapterFont;
Chapter Chapter = New Chapter (ctitle, 1);
Paragraph Stitle = New Paragraph ("This Is Section 1 in Chapter 1", sectionFont);
Section section = chapter.addsection (stitle, 1);
In the sample code 0402, we add a series of chapters and sub-areas, you can see the full tree, the tree structure opens, if you want some nodes to close, you must use the BookmarkOpen property to value False, Details See the example code 0403. Graphic
If you want to add graphics, such as straight lines, circles, geometric forms, you should read ten chapters, but if you only need some limited features, you can use Graphic objects.
Graphic grx = new graphic ();
// Add a rectangle
GRX.Rectangle (100, 700, 100, 100);
// Add a slash
GRX.Moveto (100, 700);
Grx.LineTo (200, 800);
// Show the graphic
GRX.STROKE ();
Document.Add (GRX);
For complete code, please see the sample code 0404. If you want to see all methods, see the PDFContentByte Object API.
The graphics object is useful when you want to add a border or draw a horizontal line on the current location of text. The following method uses the specified width, pitch (if needed) and color to draw a border.
Public void setBorder (Float LineWidth, Float ExtraSpace);
Public Void SetBorder (Float Linewidth, Float ExtraSpace, Color Color);
The following method uses a horizontal line with the specified width (if needed) and color, the length of the line is the percentage of the available area between the two edges.
Public void sethorizontalline (Float Linewidth, Float Percentage)
Public void sethorizontalline (Float Linewidth, Float Percentage, Color Color)
In the sample code 5, there is a border of 5 pounds from the boundary, 3 pounds of the line width, there are two horizontal lines, one is black, 5 pound wide, available space 100%, another one is red, 3 pounds of line width, available 80% of space.
Chapter 5
Key: If you only generate a PDF file (no XML, HTML, RTF ...), use class PDFPTable instead of class Table better.
Some simple forms
A form is a rectangular area that includes a cell arrangement into a matrix. The distance from the table does not require M × N, it can have a hollow or unit grid.
The most common way to create a form is to pre-know a few rows:
Public Table (int columns, int rows);
In the sample code 0501, we built a simple table:
Table Atable = New Table (2, 2);
ATABLE.ADDCell ("0.0");
ATABLE.ADDCell ("0.1");
ATABLE.ADDCell ("1.0");
ATABLE.ADDCell ("1.1");
This form has two rows, the cell is automatically added, starting from the first row, then the second column, and the next cell is automatically added to the first column of the next row.
You can also add cells to the location specified in the table, such as sample code 0502, don't add system.drawing.dll reference to get the Point object, we created a 4-row 4 column table then add some cells to Random position:
Table atable = new table (4, 4); atable.autofillemptycells = true;
Atable.addcell ("2.2", New Point (2, 2));
Atable.addcell ("3.3", New Point (3, 3));
Atable.addcell ("2.1", New Point (2, 1));
Atable.addcell ("1.3", New Point (1, 3));
You can see that we set the AutoFilleMptycells property to True, which will automatically, the default unit layout fills the empty cell, if we have forgotten this (just like the second table in this example), there will be no additional unit The grid is added, and the row that does not contain any single-handed is ignored. In this example, the first line will not be displayed because the line is a blank line.
Frequet of database query results, in most cases, you don't know how much it takes in advance, this is why there is a second constructor:
Public Table (int columns);
ITEXT is automatically added to the sample code 0503, in the sample code 0503, ITEXT automatically increases the number of rows to 7 when we add cells and 7th lines.
Increase the number of columns, but a little trouble, it can't be automatically generated, you must use the AddColumns method and set the column width, see Sample Code 0504 for details.
Some table parameters
The table in the previous example is not beautiful, we can set a large number of parameters to change the table. Class Table and class Cell derived from class Rectangle, we can use a large number of typical Rectangle methods to let us see sample code 0505.
Table Table = New Table (3);
Table.BorderWidth = 1;
Table.Bordercolor = New Color (0, 0, 255);
Table.cellpadding = 5;
5. Table.cellspacing = 5;
Cell Cell = New Cell ("HEADER");
Cell.header = true;
Cell.colspan = 3;
Table.Addcell (Cell);
10. Cell = New Cell ("Example Cell with Colspan 1 and RowsPan 2");
Cell.RowSpan = 2;
Cell.Bordercolor = New Color (255, 0, 0);
Table.Addcell (Cell);
Table.Addcell ("1.1");
15. Table.AddCell ("2.1");
Table.Addcell ("1.2");
Table.Addcell ("2.2");
Table.Addcell ("cell test1");
Cell = New Cell ("BIG Cell");
20. Cell.RowSpan = 2;
Cell.colspan = 2;
Cell.BackgroundColor = New Color (0xc0, 0xc0, 0xc0);
Table.Addcell (Cell);
Table.Addcell ("Cell Test2");
25. Document.Add (Table); U unit spacing and fill
In line 4, we set the pitch of the table, which is a certain amount of space between the cell boundary and the content. In the previous example, we see the text close to the boundary, you can use a specific fill distance. avoid.
In line 5, we set the spacing of the table, which is a certain number of space between cells and table boundations. Different cells use half space, and the specific code is shown in the sample code 0506.
u alignment
In the sample code 0506, we also changed the alignment of the cell "BIG CELL":
Cell.horizontalalignment = element.align_center;
Cell.VerticalAlignment = element.Align_middle;
Note: It is not always believed that vertical alignment.
u Box
If we add a cell to the 14th line, we will use the default cell layout (the default layout can be changed), if we use the Cell object, we can control the layout of each cell.
In 2nd and third, we set the border width and border color of the entire table, we can use in cells, in 12 lines, each cell is "box" as a boundary (就 象 in html Middle), but sample code 0507 shows that we have a lot more possible in PDF.
u color
In line 22, you can also define the background color of the cell, in the sample code 0507, we don't use the color just fill with a certain grayscale.
u rogue and column
Finally, you can set the line of cells (11/20 rows) and columns (8/21 columns). In this way, several cells can be combined into a large cell.
u Remarks
The 7th line does not make sense in the PDF, used to generate HTML, not always producing the same layout in HTML, the PDF form is a bit like:
HEADER
Example Cell with Colspan 1 and RowsPan 2
1.1
2.1
1.2
2.2
Cell Test1
Big Cell
Cell Test2
U table segmentation
If a table cannot be placed on a page, it will be automatically split, and the sample code 0508 shows the case that occurs when a table reaches the page, which will be explained in the next section.
Big form
A table across a few pages will be automatically split into different parts. Sample Code 0509 shows a report that spans multiple pages. The report has a header if you want this header to appear on each page, you can use the endheaders () method to mark the end point of the header area, see the sample code 0510.
In order to do such a report, it is recommended to set the unit spacing of 0 and only the specified fill.
You may have already noticed that some borders are lost when a form is split. This is because the cells are integrated in the previous page without passing to the next page.
u Forced to place a form or unit grid to a page
In some cases, you might want to avoid cells or entire tables to be split into two parts, the sample code 0511 is almost the same as the sample code 0508, but we set the parameter tableHastofit to True, see sample code 0508 and sample code 0511 results difference. In the sample code 0512 we modified the CellsHaveTofit property of the sample code 0510 as true, comparing the difference between the two example generation results.
Memory management
When we add an object to a document, the object may write an output stream, but when a table is created, the Table object has been saved, which will become a problem. Similarly, when you write an HTTPSERVLETRESPONSE object to the output stream, the browser may also time out. That's why you use FitSpage () method control table segmentation, sample code 0513 tells you how to do it.
Nested form
There are two ways nested forms, the first is to use the insertTable method to explicitly insert a table into another table, and the sample code 0514 shows 5 tables created by inserting into other forms. As you can see in the front two tables, all empty cells are automatically split because the original form is changed. If a cell is airless, the column span and / or line span will be automatically adjusted to a new location, and the third table on the page shows that the relevant width of the columns in all original table has been protected, the fourth table shows us Add additional cells after inserting the table: This cell is free to add to the next cell. Finally a depth nested form.
When you use the InsertTable method, the width percentage of the insert table will not be considered. If you want to insert a table only 80% of the cell (this is the default width percentage), you have to wind around the cell, see example code 0515, this is also the only way to allow a table to store other data in the same cell in the same cell, see example code 0516.
Remarks: You can only insert a table into a cell that is 1 column span and row span.
Table offset
The new row that is subject to the current pitch will be added (as the spacing of the previous insertion object) before a table is added to the document. Sometimes because the pitch between the previous insertion object and the current table is too big or too small, you don't want to do this, if you want to change this space, you have to set the table offset, such as sample code 0517.
Table of the absolute position
Itextsharp.text.table is a fairly simple class that creates a table through standard methods, but sometimes you want the form to have some special behaviors. In this case you will use more complex class com.lowagie.text.pdf.pdfptable, Example Code 0518 is a very simple example, there will be some more complex examples in Chapters and twelfth chapters.
Chapter VI Pictures
Image object
If you have learned the API, you may have noticed that you can create a picture through several constructors. In this manual, we will only tell you the easiest solution, such as accessing the image object generated by the image determined by the file name or URL. .
Public Static Image GetInstance (URI URL)
Public Static Image GetInstance (String FileName)
Image is an abstract class, so the method of obtaining an instance will determine the category of the given picture (GIF, JPEG, PNG ...) and return the category of the object GIF, JPEG, PNG ..., some pictures will be ignored, if you want I know which pictures will be ignored, please consult FAQ (http://www.lowagie.com/itext/faq.html#images).
u Get picture instances via URL
This is the simplest way to add a picture, see the sample code 0601, we add a WMF, a GIF, a JPEG and a PNG picture to the document, use 4 URLs to get:
Image WMF = image.getInstance (New url ("../ esamples / harbour.wmf"));
Image gif = image.getinstance (new url ("../ example / vonnegut.gif")); Image jpeg = image.getinstance (New Url ("../ Examples / Mykids.jpg"));
Image PNG = Image.GetInstance (New Url ("../ Examples / Hitchcock.png"));
Note: Many PDF libraries unzipped and converted into bitmap formats before inserting a picture. Here is why I don't do this:
This will result in an increase in the PDF file, which generated PDF file size is several tens of times the sum of different image files.
Faced with a legal issue: the LZW algorithm is protected by patent, so this algorithm is not allowed to decompress the GIF.
u Get image instances by file name
Change the sample code 0601 to sample code by simply changing the image reference path 0602:
Image gif = image.getInstance ("vonnegut.gif");
Image jpeg = image.getInstance ("mykids.jpg");
Image png = image.getinstance ("hitchcock.png");
The difference between the sample code 0601 is just that the image is acquired locally, and one other example is found to see the sample code 0603.
Picture location
u alignment
Set the picture alignment by the following method:
Alignment = image.right
Alignment = image.middle
Alignment = image.Left
See Sample Code 0604.
We put the picture of the vonnegut on the right, the picture of the child is placed in the middle, the picture of Hitchcock is placed on the left.
u picture and text
In addition, you can also specify the surrounding way text relative to the picture:
Alignment = image.right | image.textwrap
Alignment = image.middle
Alignment = image.Left | Image.underlying
See the example code 0506, the text is around the left side of the vonnegut picture, and is around my child, and it is ranked on the Hitchcock picture.
Description: This function has some bugs.
u absolute position
You may use this method when making a PDF file:
Public void setabsolutePosition (int Absolutex, int absolutey)
Picture of a picture from the page on a absolute position of the page 0606, we added two pictures at different coordinates, where the given coordinates will be placed in the lower left corner, by putting the width and height of the image. As the X and Y coordinates, the first picture will be set, and the second picture is set 2 times.
Zoom and rotate pictures
u Zoom
There are several ways to scale the picture:
Public void scaleabsolute (int newwidth, int newheight)
Public void scalepercent (int percent)
Public void scalepercent (int init percentx, int inity)
Public Void Scaletofit (int fitWidth, int fitting)
The picture size of the child is 194 × 202 pixels. If you want the picture small, you can zoom via ScaleabSolute (97, 101), and use Scalepercent (50) to reach the same effect. It is also possible to decrease by ScaleabSolute (194, 101), so these examples are placed in the sample code 0607.
u on resolution
If a picture is not scaled, the resolution is 72. If the scale scaled is 50%, the resolution is 144. If there is a lower zoom ratio, the resolution will be larger because of the pixel The same, but the size becomes smaller. Picture of 300DPI is placed using 72/300 = 24%, an example: You scan a 5 × 5-inch picture with 300DPI, the image result is 1500 × 1500 pixels (5 × 300), when you use 24% ( 72/300 = 0.24) When the image is placed in the PDF file, the pictures in the PDF will be 5 × 5 inch 1500x1500 pixels 300dpi, which will always be 1500x1500 pixels regardless of the size.
u Rotate
Picture can be rotated by the following method
Public Void Strotation (Double R)
See example code 0608 for details.
Original image data
So far, the images used in all examples come from local local disks or some websites, but it is also possible to use an array containing image information to get an instance of the image:
Public static image getInstance (byte [] img)
The method is the same as the effect of the previous method, returns a new GIF, JPEG or PNG category image object.
In the sample code 0609, we add a picture that read into the byte array from a JPEG file. It is obvious that it is more superior to use other GetInstance methods, but this is just an example, the GetInstance method creates those It is very useful when there is no picture that does not exist.
This example also demonstrates how to create and use an original image.
Public Static Image GetInstance (int Width, Int Height, Int Components, Int BPC, Byte Data [])
This example creates a picture of 100 × 100 pixels because each pixel is described with RGB, so the picture size is 100 × 100 × 3 bytes.
System.drawing.bitmap
Sample Code 0610 is a relatively advanced topic, the reasons are as follows:
The system.drawing.bitmap class is used for the first time. This class can use more types of pictures such as TIFF, GIF, and these images are not supported in ITEXT, you can check if you need the picture format you need to support.
In the example, there are some things to pay attention to: When adding a picture, there is no problem, the text is always floating above, in this case, we hope the picture is on the text. This is why we will use the reason why ITextsharp.Text.pdf.pdfcontentbyte class (see Chapter 10).
You will find the picture used for the transparent GIF format, you can download it at http://itextsharp.sourceforge.net/examples/h.gif.
TIFF and CCITT
Sample code 0611 is also a relatively advanced topic, and an example converts a TIFF file to the PDF file.
u picture mask
Sample code 0613, we created a picture 3C for masks
7E
E7
C3
C3
E7
7E
3C
The picture size is 8 × 8 pixels, each group of bytes, can be converted into a mask using the makemask () method.
Byte maskr [] = {(byte) 0x3c, (byte) 0x7e, (byte) 0xC3, (byte) 0xc3, (byte) 0x7, (Byte) 0x7e, (byte) 0x3c};
Image mask = image.getinstance (8, 8, 1, 1, maskr);
Mask.makemask ();
Mask.setinvertmask (True);
We can use this mask to cover a part of the other pictures.
PDFContentByte CB = Writer.directContent;
Image image = Image.getInstance ("vonnegut.gif");
Image.imagemask = MASK;
Or we use this mask in template blanking.
PDFContentByte CB = Writer.directContent;
Cb.setrgbcolorfill (255, 0, 0);
Cb.addImage (mask, mask.scaledwidth () * 8, 0, 0, mask.scaledheight () * 8, 100, 400);
For more information on ContentByte object, please refer to Chapter 10.
Pictures and other objects
u picture in block
Sometimes, it is convenient to place the picture in a block, and a picture is placed in a block by a certain offset:
Chunk CK = New Chunk (IMG, 0, -5);
For specific code, see sample code 0614, we can add this special picture block to a short sentence, table, etc., please go to http://itextsharp.sourceforge.net/examples/pngnow.png Download.
u picture in the form
You can add images to cells, but there are two side effects:
The width of the table is determined. When the picture exceeds the width of the cell, it will be automatically reduced.
l You can't make a text winding, and add an underscore to the image.
See Sample Code 0615.
u picture link notes
If you want to get a clickable picture, or want to add a link to comment on the image, you need to create an Annotation object and add it to the picture, you don't need to specify (you can use 0, 0, 0, 0), This location will be updated inside to suit the picture.
Gif.annotation = New Annotation (0, 0, 0, 0, "chap1102b.pdf", 3);
JPEG.ANNOTATION = New Annotation ("Picture", "There Are My Children", 0, 0, 0, 0);
Participate in the sample code 0616.
Second parts of other document formats
Chapter 7 XML and (X) HTML
This chapter mainly introduces how to use IText control to generate XLM documents and (X) HTML documents, but we are not interested in these, so it is only to introduce XML to PDF mentioned in this chapter.
In the first chapter, we produce a PDF file through 5 steps. In order to convert an XML file to a PDF file, you only need to rewrite steps 3 and 4, step 5, automatically processed by the parser.
// Step 3: Create a parser and set the document handle:
ITextHandler H = New ITEXTHANDLER (Document); // Step 4, convert this document:
H.PARSE ("chap0701.xml");
Sample code See Sample Code 0702
Chapter 8 RTF file
RTF package
The RTF package is based on the ITEXT package, allowing ITEXT to output the RTF file in addition to generating a PDF file, except for some features that are not supported in the RTF package, most PDF file features can be used.
Create an RTF document
Creating an RTF document and creating a PDF document method is the basic 5 step, the only difference is that in step 2 instead of PDFWriter, see the sample code 0801.
Step 1 Create an instance of an the itextsharp.text.document object:
Document Document = New Document ();
Step 2 Create a Document RTFWRITER Write Document to your selected output stream:
Rtfwriter.GetInstance (Document, New FileStream ("chap0801.rtf"), filemode.create;
Step 3 Open Document:
Document.open ();
Add content to Document in step 4
Document.Add (New Paragraph ("Hello World"));
Step 5 Close Document
Document.close ();
For how to create other objects and add to Document, see the contents of other chapters.
Not supported features
Watermark
Reader parameters
encryption
Embedded font
Block spacing
Paragraph right rolled
List right rollout
No round dot symbol list
Nested form
Additional pictures in JPEG and PNG
Header and footer extended in RTF
When writing RTF, you cannot change the header or footer of the document through the sethead method before starting the new page. There are two ways to solve this problem.
With "chapters", add a new "chapter" to the document, use SetHeader or SetFooter, you can use different headers or footers in different "chapters", see the sample code 0802. Use the RTFHeaderfooters class. This class allows you to set up 4 headers or footers and specify on which page appears. You can of course create 4 different headers or footers combined with Chapter, see the sample code 0803.
u Using the RTFHEADERFOOTERS class
Step 1 Create an RTFHEADERFOOTERS class:
Rtfheaderfooters headers = new rtfheaderfooters ();
Step 2 Add a Headerfooter object
Headers.add (RTFheaderfooters.Left_pages, New Headerfooter (New Phrase ("This Header Is Only On LEFT HAND PAG PAGES"))
Headers.add (RTFheaderfooters.right_pages, New Headerfooter (New Phrase ("This Header Is Only On Right Hand Pages));
Step 3 like RTFHeaderfooters like the header footage
Document.header = headers;
Using RTFHeaderfooters.Add (...):
First_Page: Use the header or footer in the first page of your document. You will use RTFWriter.haastitlePage = true to complete
LEFT_PAGES: All left pages use this header or footer
Right_pages: All pages use this header or footer all_pages: All pages use this header or footer, only with first_page combined with use.
One thing is very important: If you use left_pages or right_pages to set the header or footer, use all_pages, headers and footers.
See the sample code 0804.
Advanced application of the third part ITEXT
Chapter 9 Font
This chapter tells the use of many fonts, but it is not how to use Chinese. Therefore, the meaning is not big, and then, if Chinese is not supported, the front is translated, so according to some knowledge telling the original text, I Into the method of use of Chinese characters, I wrote this chapter, it should be "original", ^ _ ^ (Oops! Who touches me ...).
WINDOWS is generally using TrueType fonts. Each Chinese version of the Windows operating system is installed by default, the four fonts of the Song, black body and the body are installed. You can also install other third-party fonts. If you install Office 2000, you will automatically install it. The fonts such as Huawen are more strange. Insert a font of this computer in the PDF file, although there is no font on the computer that opens the PDF file, but still displayed normally! This is not in the Word file, the Word file will use the font in the current computer to replace the Song, which is probably an unexpected gain.
Font files are typically saved in the WINDIR / FONTS directory, extension is TTF, and the font file extension is TTC, but also a TrueType font, but a collection, which is a variety of fonts. The file names of the four standard fonts are listed below:
SIMSUN.TTC: Song and New Song
Simkai.ttf: 体
Simhei.ttf: black body
Simfang.ttf: imitation Song
TrueType font application
Write the black body text in the method below, size is 32 pounds:
Basefont bfhei = basefont.createfont (@ "c: /winnt/fonts/simhei.ttf", basefont.Identity_h, basefont.not_embedded;
Font font = new font (bfhei, 32);
String text = "This is a black-body test!";
Document.Add (New Paragraph (Text, Font);
Don't manage the second, three parameters of the basefont.createfont method, the 依 葫 画 画, the first parameter display is the location where the font file is stored.
The following code is very well understood, and will not be described again.
Trutype font collection application
The use of the font collection is similar to the above, just which font is used in the CreateFont party. Such as:
Basefont bfsun = basefont.createfont (@ "c: /winnt/fonts/simsun.ttc, 1", basefont.Identity_h, basefont.not_embedded;
Font = New font (bfsun, 16);
TEXT = "This is a new Song test in the font collection!"
Document.Add (New Paragraph (Text, Font);
It is not difficult to see that when using the basefont.createfont method, there is a "first parameter @" c: /winnt/fonts/simsun.ttc, 1 "," 1 ", indicating that the serial number is 1 font, the serial number is 0 The font is a Song. After all, we are not a typographic software. With the above way, it is basically enough. It is basically a very complicated PDF file production, and you may wish to make an XML file (the easiest way is to use Word typography, then save it as a web page), Then convert according to the seventh chapter.
See the sample code 0901 for the code.
Chapter 10 Image and the absolute position of the text
PDFContentByte
So far, we have used simple IText, we have added text, pictures, paragraphs, chapters, lists, tables, etc., and do not involve layout problems. ITEXT segmentation text into each page, and puts each word, sentence, paragraph to the page, but sometimes we don't need this automatic format, sometimes we want to place some images or text on a specified location of a page, To implement this feature, we will use the PDFContentByte class.
Instead of the first chapter, only the pdfwriter class GetInstance method is not enough, you must have a PDFWriter object, you can get the object by using the getDirectContent () in the use of Writer objects. example:
PdfWriter Writer = Pdfwriter.GetInstance (Document, New FileoutputStream ("Test.pdf"));
PDFContentByte CB = Writer.directContent;
NOTE: When you add an advanced object (such as a table), two PDFContentByte objects will be used internal: one for text, one with a background (such as a boundary or cell background). Text draws the top of the image.
When you use the PDFContentByte object through the getDirectcontent () method, all objects you add will float text and images. If you want to avoid this situation and want to add content behind the image or text, you need to use the getDirectcontentunder ().
In a word, when a page is completed, the 4-layer overlap follows the following order:
1, PDFContentByte obtained by getDirectcontentunder ()
2, including internal PDFContentByte, including images or advanced objects
3, internal PDFCONTENTENTETE for the disease or advanced object
4, PDFContentByte obtained by getDirectcontent ()
Simple graphics
In the sample code 1001, some simple graphics are drawn, we use such as Moveto and Lineto methods to move to the current location on the page and draw a straight line to other locations. We use such as SetLineWidth and SetLinedash methods to change the appearance of the straight line, such as:
Cb.LineWidth = 10F;
Cb.moveto (100, 700);
Cb.LineTo (200, 800);
Cb.stroke ();
Description: When you change properties such as color, line width, only you work when calling the stroke method. When the triangle is drawn in the example, we set the color to green. We change the color to red before using the stroke method, and the result of the drawing triangle is red instead of green, in this example, there is a rectangular, circular, etc.
text
When you want to write text to ContentByte, you must use method begintext () and endtext, you must also set fonts and sizes. As in graphical examples, there are many ways to write and place text, but you need most of the method ShowTextALIGNED and Method ShowText work with setTextMatrix. example 1:
Basefont bf = basefont.createfont (basefont.helvetica, basefont.cp1252, basefont.not_embedded); cb.begintext ();
Cb.SetFontAndsize (BF, 12);
Cb.ShowTextAligned (pdfcontentbyte.align_center, text "this text is centered", 250, 700, 0);
Cb.Endtext ();
Example 2:
Basefont bf = basefont.createfont (basefont.helvetica, basefont.cp1252, basefont.not_embedded);
Cb.begintext ();
Cb.SetFontAndsize (BF, 12);
Cb.SetTextMatrix (100, 400);
Cb.ShowText ("Text At Position 100,400.");
Cb.Endtext ();
See Sample Code 1002.
Form XOBJECTS
When we discuss the headers and footers in Chapter 4, we define a small piece of information to add to each page, in fact, the small block information writes to each new page of the file. This is not the most economical solution, a better way is to use this information as an Form XObject to add only one in the document, and repeatedly appears in its visible position. I reach this, we will use templates.
u Create a pdftemplate
u The best way to create PDFTemplate is to call the CreateTemplate method in the PDFContentByte object:
PdfContentByte-Object:
Pdftemplate Template = CB.CREATETEMPLATE (500, 200);
Thus, the width of the template is 500 and a height of 200.
We can make the same thing like PDFContentbyte through this template.
Template.moveto (0, 200);
Template.LineTo (500, 0);
Template.stroke ();
Template.begintext ();
Basefont bf = basefont.createfont (basefont.helvetica, basefont.cp1252, basefont.not_embedded);
Template.setFontAndsize (BF, 12);
Template.setTextMatrix (100, 100);
Template.showText ("Text At The Position 100, 100 (Relative to the Template!);
Template.endtext ();
u Add a template to the document
Add a template to the absolute position like the following:
Cb.AddTemplate (Template, 0, 400);
You can also do some interesting things, such as zooming or rotating them:
// Rotate the template 90 degrees
Cb.AddTemplate (Template, 0, 1, -1, 0, 500, 200);
// Zoom template is 50%
Cb.AddTemplate (Template, .5f, 0, 0, .5f, 100, 400); // Zoom template is 200%
Cb.AddTemplate (Template, 2, 0, 0, 2, -200, 400);
The specific presentation is shown in the sample code 1003.
u Sequence pages a few pages
In some cases, you want to insert some information you can't know when you write this page to the text, such as: In the first page of a document, you don't know how to have a total of a few pages. You can only know the total number of pages when you complete the entire document. This problem does not exist when using a template. In the sample code 0103, we add some information to the template before adding a template to ContentByte, which is not necessary. We can add information to the template at any time because IText adds form xobject to the end of the PDF (called when the document is turned off via the Close method). Sample code 1004 displays first creation 4 pages and adds a total number of pages, which is very simple and useful.
Columns
Before this chapter, you have mastered how to put text in an absolute position, in which case we want to determine the start coordinates of the text. If we want to know the end of the text, we have to do some calculations.
Now we have to add some text to a rectangular box, I hope that the text will automatically wrap when the right border is reached. Over the rectangular portion will not be displayed, can be implemented by the ColumnText class.
for example:
To display a specified short sentence in the rectangular internal rectangle of coordinates (100, 300) and (200, 500), we use the following code:
PDFContentByte CB = Writer.directContent;
ColumnText CT = New ColumnText (CB);
Ct.setsimpleColumn (phrase, 60, 300, 100, 500, 15, element.align_center);
Ct.go ();
By looking at the sample code 1005, you will immediately find that you can draw some complex forms without having a table object.
another example:
There is no need to add all the text in one time, you can define a rectangle first, then add some text, and finally display the column with the GO method.
PDFContentByte CB = Writer.directContent;
ColumnText CT = New ColumnText (CB);
Ct.setsim7plecolumn (60, 300, 100, 500, 15, element.align_center);
Ct.addtext (phrase1);
Ct.addtext (phrase2);
Ct.addText (phrase3);
Ct.go ();
See the sample code 1006 for details.
Multi-column
Of course, if the text exceeds the rectangular range, we don't want to lose these texts, and we want to display these text to other columns. That's why we have to check the reasons for the return value of the Go method. If the logo is "NO_MORE_COLUMN", it means that there is not enough space in this column to store the text, if all text is displayed, the identifier will be "no_more_text".
See Sample Code 1007.
Irregular column
Define a non-rectangular area to display the bar. By using the setColumns method, we define a left and right boundaries for the text.
FLOAT [] Left = {70, 790, 70, 60};
Float [] Right = {300, 790, 300, 700, 240, 700, 240, 590, 300, 590, 300, 106, 270, 60};
Ct.setColumns (Left, Right);
The left boundary is a straight line, and the right border is irregular. The result of this function can lead to some very interesting layout, see example code 1008, this example you will use a picture called caesar_coin.jpg: pdftable
In Chapter 5, we briefly tell the PDFPTable object, now we will discuss more features of this object.
You can create PDFTables with three different ways:
Pdfptable (float [] relativeWidths;
PDFPTABLE (INT NumColumns);
Pdfptable; PDFPTable Table;
You can set more parameters to the table, such as table width, column width, horizontal alignment, etc. You can add cells by the following approach:
Public Void AddCell (PDFPCell Cell);
Public void addcell (pdfptable table);
Public void addcell (phrase phrase);
Public void addcell (String text);
These methods are very similar to the Table object in addition to cell fill and spacing. These parameters are set to each cell individual, of course, you can set the default value of the cell, to change the default value of the cell, use getDefaultcell () and call one or more PDFPCell methods (you can set Alignment, spacing, border, color or even minimum height).
Note: With PDFPTABLE, you can change the column span of a cell, but you can't change the line span! Inside the PDFPTable is some independent rows, let it support line span changes to make great adjustments to PDFPTable objects, do not expect to implement in the near future, you can use nested tables to solve these problems.
You can add a pdfptable to the current document like Chapter 5, but you can also add a table in the absolute position in the current page:
Public Float WriteSelectedRows (int RowStart, int Rownd, Float Xpos, Float Ypos, PdfcontentByte Canvas);
The parameter rowstart is the number of rows you want to start, and the parameter Rowend is the last line you want to display (if you want to display all the rows, use -1), XPOS and YPOS are the coordinates of the table, canvas is a PDFContentbyTe object. In the sample code 1009, we added a table in (100,600):
Table.WriteselectedRows (0, -1, 100, 600, writer.directcontent);
With PDFPTABLE, you can't set row span and (or) span (how to have a little contradiction above?) You can use a nested table to resolve, see the sample code 1010.
Finally, sample code 1011 and sample code 1012 demonstrates that PDFTABLE can be used with Templates and Columns, which will be used in sample code 1012 as follows:
Color (Spotcolors) and Pattern (Patterns)
The use of the color (Spotcolors) see example code 1013, sample code 1014, and sample code 1015 demonstrate the method of use of pattern.
Chapter 11 Local and Differential Turn, Goals and Overview
Local steering
Sometimes you need a link that allows the reader to jump to another place from a place to another place, you can implement two ways to CHUNK SETLOCALGOTO and SETLOCALDESTINATION: Chunk localgoto = New Chunk ("this word", fontfactory.getFont (FontFactory.helvetica, 12, Font.Normal, New Color (0, 0, 255))). SetLocalgoto ("Test");
Chunk destination = New Chunk ("Local Destination", FontFactory.getFont (FontFactory.helvetica, 12, Font.Normal, New Color)). SetLocalDestination ("Test");
See the example code 1101.
Outdoor steering
In Chapter 3, we demonstrate how an anchor turned to other URLs, an anchoring through different fonts, style and colors, can contain different chunks, in the Advanced Application of ITEXT, the following definition links to the URL. method:
Chunk chunk = new chunk ("Anchor", FontFactory.getFont (FontFactory.helvetica, 12)). SetAnchor ("http://www.lowagie.com/itext/");
u Go to the specified location in the PDF document
If you specify a destination in the document, you can jump from another document to here, to implement this feature, you can use the method:
SetRemotegoto: Chunk Chunk = New Chunk ("Jump", FontFactory.getfont (FontFactory.helvetica, 12, Font.italic)). SetRemotegoto ("Test.pdf", "Test");
Test.pdf is another PDF file, "Test" is a destination of the file.
Jump to another PDF file specified page
Use the method setREMOTEGOTO, with the page number parameter instead of the name parameters, you can easily jump on the specified page of another document:
Chunk = New Chunk ("Jump", FontFactory.getFont (FontFactory.helvetica, 12, Font.italic)). SetRemotegoto ("Test.pdf", 3));
See example code 1102
u Start an application
You can use the following method to start an application:
Public PdFaction (String Application, String Parameters, String Operation, String Defaultdir)
If Application is "c: /winnt/notepad.exe" (the remaining parameters can be null), you can start the Notepad program through the link in the PDF file.
u File and URL
If you want to jump to another document or URL, you need to create one by one of the following constructor:
PdFaction (String filename, String Name);
PdFaction (String FileName, INT Page);
PDFAction (URL URL);
Pdfaction (String URL);
The front two constructors allow you to jump to the specified location or page number, the latter two constructor allows you to jump to other URLs. The rest is slightly.
Chapter 12 Page and Table Events
slightly.