Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How justify text using iTextSharp?

Tags:

c#

itextsharp

Have piece of code like below:

 var workStream = new MemoryStream();
 var doc = new Document(PageSize.LETTER, 10, 10, 42, 35);
 PdfWriter.GetInstance(doc, workStream).CloseStream = false;
 doc.Open();

 var builder = new StringBuilder();
 builder.Append("MY LONG HTML TEXT");
 var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(builder.ToString()), null);

 foreach (var htmlElement in parsedHtmlElements)
       doc.Add(htmlElement);

doc.Close();

byte[] byteInfo = workStream.ToArray();
workStream.Write(byteInfo, 0, byteInfo.Length);
workStream.Position = 0;
return new FileStreamResult(workStream, "application/pdf")

And have one problem-how make that pdf justified? Is any method or something which quickly do that?

like image 846
Kamil Będkowski Avatar asked Apr 13 '12 17:04

Kamil Będkowski


People also ask

What is the use of iTextSharp?

iTextSharp is a port of the iText Java PDF library that gives you the ability to add PDF functionality to your applications. Using iTextSharp, you can create and read PDF files without any costs or proprietary software, so you can deliver the functionality your users expect.

What is phrase in iTextSharp?

A Phrase is a series of Chunk s. A Phrase has a main Font , but some chunks within the phrase can have a Font that differs from the main Font . All the Chunk s in a Phrase have the same leading .


1 Answers

Ah, I get it, you mean "justified" instead of "adjusted". I updated your question. It's actually pretty easy. Basically it depends on the type of content that you're adding and whether that content supports this concept in the first place. Assuming that you have basic paragraphs you can set the Alignment property on them before adding them in your main loop:

foreach (var htmlElement in parsedHtmlElements){
    //If the current element is a paragraph
    if (htmlElement is Paragraph){
        //Set its alignment
        ((Paragraph)htmlElement).Alignment = Element.ALIGN_JUSTIFIED;
    }
    doc.Add(htmlElement);
}

There's two types of justification, Element.ALIGN_JUSTIFIED and Element.ALIGN_JUSTIFIED_ALL. The second is the same as the first except that it also justifies the last line of text which you may or may not want to do.

like image 195
Chris Haas Avatar answered Oct 17 '22 15:10

Chris Haas