Align Paragraph at the center of the page
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.
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;
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();
}