Align Paragraph at the center of the page

2019-02-11 17:05发布

问题:

I am using itext to generate pdf file. I want to align my title in the middle of the page. Presently i am using like this

Paragraph preface = new Paragraph();  
for (int i = 0; i < 10; i++) {
    preface.add(new Paragraph(" "));
}

Is it correct or is there any another best way to do this.

回答1:

Use Paragraph#setAlignment(int) :

Paragraph preface = new Paragraph(); 
preface.setAlignment(Element.ALIGN_CENTER);

See the ALIGN_* constants in the Element interface for more possible values.



回答2:

If any one is looking for .NET/C# version, below is how I achieved the CENTER alignment.

I am using iText7 library for .NET/C#, and I achieved this using :

Paragraph preface = new Paragraph();
preface.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);


回答3:

Not sure if this is an old version, but for PdfWriter these methods weren't there. Instead I used:

Paragraph p = new Paragraph("This too shall pass");
p.Alignment = Element.ALIGN_CENTER;


回答4:

 public static final String DEST = "results/tables/centered_text.pdf";


public static void main(String[] args) throws IOException, DocumentException {
    File file = new File(DEST);
    file.getParentFile().mkdirs();
    new CenteredTextInCell().createPdf(DEST);
}

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    Font font = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
    Paragraph para = new Paragraph("Test", font);
    para.setLeading(0, 1);
    PdfPTable table = new PdfPTable(1);
    table.setWidthPercentage(100);
    PdfPCell cell = new PdfPCell();
    cell.setMinimumHeight(50);
    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    cell.addElement(para);
    table.addCell(cell);
    document.add(table);
    document.close();
}


标签: java pdf itext