只需設置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);
}
}
它甚至有長長的一串像這樣工作的:
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);
編輯: 在看「照片後「你畫了...
它與標題不符。 只有方式,你可以對齊個人Paragraph
對象像你的圖片是如果「段落」不是超過Document
對象的「內容」框(缺乏一個更好的術語)。換句話說,如果文本的數量超過將合適的一行,則將無法獲得該類型的對齊方式。
隨着中說,如果你想要的類型定位的需要:
- 從您要使用的字符串的集合計算最大價值。
- 使用該值爲
Paragraph
設置共同的左縮進值。
事情是這樣的:
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);
}
}
更新2:
閱讀您的更新問題後,這裏的另一個選項,你可以添加文字的左側「容器」:
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);
根據你的頭銜,我實際上並不瞭解你想要做什麼。你不希望正常的段落對齊(左,右,對齊)?你是否嘗試對齊多個段落的邊緣? – 2012-01-12 14:24:37