将页面对齐在页面中央

我正在使用itext生成pdf文件。 我想在页面中间对齐我的标题。 目前我正在使用这样的

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

这是正确的还是有其他最好的方法来做到这一点。

使用Paragraph#setAlignment(int)

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

有关更多可能的值,请参阅Element接口中的ALIGN_*常量。

如果有人正在寻找.NET / C#版本,下面是我如何实现CENTER对齐。

我正在使用iText7库用于.NET / C#,我使用以下方法实现了这一点:

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

不确定这是否是旧版本,但对于PdfWriter,这些方法不存在。 相反,我用过:

 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(); }