C# 使用 iTextSharp,如何右对齐文本容器(但保持各行左对齐)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8835892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:43:52  来源:igfitidea点击:

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

c#.netitext

提问by T.J.Kjaer

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.

我试图将所有文本放在一个段落中并设置paragraph.Alignment = Element.ALIGN_RIGHT,但这将使各个行右对齐。

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.

如果我可以创建一个只占用所需宽度的容器,我可以简单地右对齐这个容器,所以也许这真的是我的问题。

采纳答案by kuujinbo

Just set the Paragraph.Alignproperty:

只需设置Paragraph.Align属性:

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 onlyway you can align individual Paragraphobjects like your picture is if the "paragraph" does NOTexceed the Documentobject'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 willfit on a single line.

它与标题不符。该可以对准个体化的道路Paragraph就像你的图片对象是如果“段落”不超过Document对象的“内容”框(因为缺少一个更好的词)。换句话说,如果文本量超过单行容纳的量,您将无法获得这种类型的对齐方式。

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.
  1. 从您打算使用的字符串集合中计算最宽的值。
  2. 使用该值为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:

更新 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);