With iTextSharp, how to rightalign a container of text (but keeping the individual lines leftaligned)

24,947

Just set the Paragraph.Align property:

using (Document document = new Document()) {
  PdfWriter.GetInstance(
    document, STREAM
  );
  document.Open();
  for (int i = 1; i < 11; ++i) {
    Paragraph p = new Paragraph(string.Format(
      "Paragraph {0}", i
    ));
    p.Alignment = Element.ALIGN_RIGHT;
    document.Add(p);
  } 
}

It even works with a long string like this:

string longString = @"
iText ® is a library that allows you to create and manipulate PDF documents. It enables developers looking to enhance web- and other applications with dynamic PDF document generation and/or manipulation.
";
Paragraph pLong = new Paragraph(longString);
pLong.Alignment = Element.ALIGN_RIGHT;
document.Add(pLong);

enter image description here

EDIT: After looking at the "picture" you drew...

It doesn't match with the title. The only way you can align individual Paragraph objects like your picture is if the "paragraph" does NOT exceed the Document object's "content" box (for a lack of a better term). In other words, you won't be able to get that type of alignment if the amount of text exceeds that which will fit on a single line.

With that said, if you want that type of alignment you need to:

  1. Calculate the widest value from the collection of strings you intend to use.
  2. Use that value to set a common left indentation value for the Paragraphs.

Something like this:

using (Document document = new Document()) {
  PdfWriter.GetInstance(
    document, STREAM
  );
  document.Open();
  List<Chunk> chunks = new List<Chunk>();
  float widest = 0f;
  for (int i = 1; i < 5; ++i) {
    Chunk c = new Chunk(string.Format(
      "Paragraph {0}", Math.Pow(i, 24)
    ));
    float w = c.GetWidthPoint();
    if (w > widest) widest = w;
    chunks.Add(c);
  } 
  float indentation = document.PageSize.Width
    - document.RightMargin
    - document.LeftMargin
    - widest
  ;
  foreach (Chunk c in chunks) {
    Paragraph p = new Paragraph(c);
    p.IndentationLeft = indentation;
    document.Add(p);
  }
}

enter image description here

UPDATE 2:

After reading your updated question, here's another option that lets you add text to the left side of the "container":

string textBlock = @"
Mr. Petersen
Elmstreet 9
888 Fantastic City  
".Trim();
// get the longest line to calcuate the container width  
var widest = textBlock.Split(
    new string[] {Environment.NewLine}
    , StringSplitOptions.None
  )
  .Aggregate(
    "", (x, y) => x.Length > y.Length ? x : y
  )
;
// throw-away Chunk; used to set the width of the PdfPCell containing
// the aligned text block
float w = new Chunk(widest).GetWidthPoint();
PdfPTable t = new PdfPTable(2);
float pageWidth = document.PageSize.Width 
  - document.LeftMargin 
  - document.RightMargin
;
t.SetTotalWidth(new float[]{ pageWidth - w, w });
t.LockedWidth = true;  
t.DefaultCell.Padding = 0;
// you can add text in the left PdfPCell if needed
t.AddCell("");
t.AddCell(textBlock);
document.Add(t);
Share:
24,947
Torben Junker Kjær
Author by

Torben Junker Kjær

Full-stack software developer at Miracle A/S

Updated on July 17, 2022

Comments

  • Torben Junker Kjær
    Torben Junker Kjær almost 2 years

    I don't know the width of the texts in the textblock beforehand, and I want the the textblock to be aligned to the right like this, while still having the individual lines left-aligned:

                                    Mr. Petersen      |
                                    Elmstreet 9       |
                                    888 Fantastic City|
    

    (| donotes the right edge of the document)

    It should be simple, but I can't figure it out.

    I've tried to put all the text in a paragraph and set paragraph.Alignment = Element.ALIGN_RIGHT, but this will rightalign the individual lines.

    I've tried to put the paragraph in a cell inside a table, and rightalign the cell, but the cell just takes the full width of the table.

    If I could just create a container that would take only the needed width, I could simply rightalign this container, so maybe that is really my question.

  • Torben Junker Kjær
    Torben Junker Kjær over 12 years
    Thanks for your answer. I can't believe it has to be this hard. Anyway, your suggestion to measure the widths and then indent worked for me.
  • kuujinbo
    kuujinbo over 12 years
    Unfortunately, since you don't know the width of the text block in advance, the longest line must be calculated. You could hard-code a width and put the text block in the second column of a PdfPTable, but you risk either [1] having too much space on the right, or [2] too little space and a line overflowing the PdfPCell width. After reading your edited question I updated my answer with another option more in line with creating a "container. The one difference with the updated code is that you can add text to the left of your text block.