Operate PDF-iTextSharp-add text using blocks, phrases, and paragraphs in Asp. Net

Source: Internet
Author: User

This article is the third article in the series that describes how to use the open-source iTextSharp component. net to create PDFs, just like HTML and ASP. net provides multiple containers for text. iTextSharp provides the Chunk, Phrase, and Paragraph classes as containers. If you haven't read my previous articles before, the address is:

Create PDF-iTextSharp in ASP. NET

Operate PDF-iTextSharp-Use font in Asp. Net

 

Chunks

 

Chunks are the smallest containers that hold text, just like <ASP: Label> in asp. Net. Just like using Label, you need to be careful when using the block. The following code shows how to set text for the block and write it to PDF three times.

 

String path = Server. MapPath ("PDFs ");

 

Rectangle r = new Rectangle (400,300 );

 

Document doc = new Document (r );

 

Using writer. GetInstance (doc, new FileStream (path + "/Blocks.pdf", FileMode. Create ));

 

Doc. Open ();

 

Chunk c1 = new Chunk ("A chunk represents an isolated string .");

 

For (int I = 1; I <4; I ++)

 

{

 

Doc. Add (c1 );

 

}

[Pay special attention to the next section, which we will use later]

The results are as follows. We can see that the text has been added to the document, but it is displayed as messy. The Chunk does not know when the text length exceeds the document width and is automatically wrapped. You can use "\ n" or Environment. NewLine, or even Chunk. NEWLINE, as part of assigning values to the Chunk object.

Chunk has a series of methods that allow you to set styles for text, such as setUnderLine (), setBackGround (), setTextRise (), and some constructors to set the font type and style.

 

 

 

Chunk chunk = new Chunk ("Setting the Font", FontFactory. GetFont ("dax-black "));

Chunk. SetUnderline (0.5f,-1.5f );

 

 

 

PHRASE

Phrase is a level-1 container larger than Chunk. Phrase can be understood as a group of chunks and will automatically wrap the lines when the length exceeds the document width, the line spacing between each row (measured by the distance between the bottom of each row) is 1.5 times the font size, because the example between iTextSharp line spacing is 12pt, therefore, the line spacing between the following codes is 16pt. you can set the font and line spacing during Phrase initialization. of course, you can also add content to Phrase during initialization through its multiple constructors.

The following code shows the results of adding the preceding three chunks to Phrase:

 

 

Phrase phrase = new Phrase ();

 

For (int I = 1; I <4; I ++)

 

{

 

Phrase. Add (c1 );

 

}

 

 

 

Paragraphs

So far, we have seen how to add the most basic text block in PDF. in fact, the most common class you should use is Paragraphs. paragraph is actually a set of ordered Phrase and Chunk. Paragraph is derived from Phrase, so like Phrase, Paragraph will automatically wrap when the length exceeds the document length. in addition, Paragraph and Paragraph will automatically empty a line (just like the Text Processing Software). In front of this article, Chunk sets the format of some text, which is frequently needed, in the following code, I will add formatted text to Paragraphs through Chunk and Phrase:

 

 

String path = Server. MapPath ("PDFs ");

 

Rectangle r = new Rectangle (400,300 );

 

Document doc = new Document (r );

 

 

 

Try

 

{

 

Using writer. GetInstance (doc, new FileStream (path + "/Blocks2.pdf", FileMode. Create ));

 

Doc. Open ();

 

 

 

String text = @ "The result can be seen below, which shows the text

 

Having been written to the document but it looks

 

Mess. Chunks have no concept of how to force a new

 

Line when the length exceeds the available width in

 

The document. Really, all they shoshould be used for is

 

To change or set the style of a word or phrase inline .";

 

Text = text. Replace (Environment. NewLine, String. Empty). Replace ("", String. Empty );

 

Font brown = new Font (Font. COURIER, 9f, Font. NORMAL, new Color (163, 21, 21 ));

 

Font lightblue = new Font (Font. COURIER, 9f, Font. NORMAL, new Color (43,145,175 ));

 

Font courier = new Font (Font. COURIER, 9f );

 

Font georgia = FontFactory. GetFont ("georgia", 10f );

 

Georgia. Color = Color. GRAY;

 

Chunk beginning = new Chunk (text, georgia );

 

Phrase p1 = new Phrase (beginning );

 

Chunk c1 = new Chunk ("You can of course force a newline using \" ", georgia );

 

Chunk c2 = new Chunk (@ "\ n", brown );

 

Chunk c3 = new Chunk ("\" or ", georgia );

 

Chunk c4 = new Chunk ("Environment", lightblue );

 

Chunk c5 = new Chunk (". NewLine", courier );

 

Chunk c6 = new Chunk (", or even", georgia );

 

Chunk c7 = new Chunk ("Chunk", lightblue );

 

Chunk c8 = new Chunk (". NEWLINE", courier );

 

Chunk c9 = new Chunk ("as part of the string you give a chunk.", georgia );

 

Phrase p2 = new Phrase ();

 

P2.Add (c1 );

 

P2.Add (c2 );

 

P2.Add (c3 );

 

P2.Add (c4 );

 

P2.Add (c5 );

 

P2.Add (c6 );

 

P2.Add (c7 );

 

P2.Add (c8 );

 

P2.Add (c9 );

 

Paragraph p = new Paragraph ();

 

P. Add (p1 );

 

P. Add (p2 );

 

Doc. Add (p );

 

}

 

Catch (incluentexception dex)

 

{

 

Throw (dex );

 

}

 

Catch (IOException ioex)

 

{

 

Throw (ioex );

 

}

 

Finally

 

{

 

Doc. Close ();

 

}

 

 

First, let's look at the results, and then I will explain the Code:

 

 

Adding Exception Handling in code is not complicated. Of course, it is best to use try... Catch. For the Document Object of iTextSharp, The DocumentException exception still needs to be handled. I also found several other trivial exceptions in iTextSharp. When I wrote the test code to generate a PDF file, I accidentally passed two parameters to the Font object constructor, I first passed in the Font. NORMAL, the text size is passed in, and then the tragedy occurs. The font size is set to 0. execute the code to the doc. an exception is thrown during Close (). I have to Close VS to release the PDF file in the memory.

 

Therefore, exception handling is very important. At least before the document is released from the memory, you also need to note that when the font type is passed in, an f suffix should be added to the end, to indicate that the compiler is of the FLOAT type, which can prevent you from encountering the same errors as me.

 

The first text, that is, @ + quotation marks, or plain text, does not allow empty spaces or line breaks in the middle. Otherwise, spaces and line breaks are displayed in PDF as they are. In addition, each font with style styles needs to be included in a Chunk, and then added to the Phrase to ensure that the text will wrap automatically. Finally, all Phrase and Chunk are added to the Paragraph object. You can also use Paragraph. setAlignment () sets the Paragraph alignment. This method accepts a String type parameter, which can be "Left", "Center", "Justify", and "Right ". set p. setAlignment ("Justify"); Display Effect of center:

Paragraph has many other ways to set indentation:

 

 

 

Paragraph. FirstLineIndent // allows you to apply a float value to indent the first line

Paragraph. IndentationLeft // allows you to add space to the left hand side

Paragraph. IndentationRight // allows you to add space to the right hand side

Paragraph. setSpacingBefore // adds a specified amount of space abve the paragraph

Paragraph. setSpacingAfter // adds the specified amount of space after the paragraph

 

The next article will explore more text-based functions, especially inList.

 

Original article: iTextSharp-Adding Text with Chunks, Phrases and Paragraphs

Translated by CareySon

<Script> </script>

Related Article

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.