Kamil Będkowski
Kamil Będkowski

Reputation: 1092

How justify text using 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?

Upvotes: 6

Views: 16621

Answers (1)

Chris Haas
Chris Haas

Reputation: 55417

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.

Upvotes: 10

Related Questions