Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

c# - How to align two paragraphs to the left and right on the same line?

I want to display two pieces of content (it may a paragraph or text) to the left and right side on a single line. My output should be like

 Name:ABC                                                               date:2015-03-02

How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Please take a look at the LeftRight example. It offers two different solutions for your problem:

enter image description here

Solution 1: Use glue

By glue, I mean a special Chunk that acts like a separator that separates two (or more) other Chunk objects:

Chunk glue = new Chunk(new VerticalPositionMark());
Paragraph p = new Paragraph("Text to the left");
p.add(new Chunk(glue));
p.add("Text to the right");
document.add(p);

This way, you will have "Text to the left" on the left side and "Text to the right" on the right side.

Solution 2: use a PdfPTable

Suppose that some day, somebody asks you to put something in the middle too, then using PdfPTable is the most future-proof solution:

PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(100);
table.addCell(getCell("Text to the left", PdfPCell.ALIGN_LEFT));
table.addCell(getCell("Text in the middle", PdfPCell.ALIGN_CENTER));
table.addCell(getCell("Text to the right", PdfPCell.ALIGN_RIGHT));
document.add(table);

In your case, you only need something to the left and something to the right, so you need to create a table with only two columns: table = new PdfPTable(2).

In case you wander about the getCell() method, this is what it looks like:

public PdfPCell getCell(String text, int alignment) {
    PdfPCell cell = new PdfPCell(new Phrase(text));
    cell.setPadding(0);
    cell.setHorizontalAlignment(alignment);
    cell.setBorder(PdfPCell.NO_BORDER);
    return cell;
}

Solution 3: Justify text

This is explained in the answer to this question: How justify text using iTextSharp?

However, this will lead to strange results as soon as there are spaces in your strings. For instance: it will work if you have "Name:ABC". It won't work if you have "Name: Bruno Lowagie" as "Bruno" and "Lowagie" will move towards the middle if you justify the line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...