【问题标题】:Paragraph at the center of the remaining page (horizontally and vertically)剩余页面中心的段落(水平和垂直)
【发布时间】:2013-10-15 00:55:26
【问题描述】:

我需要使用 iText 创建 PDF 文件。在第一页,页面顶部应该有一个标题,然后是一个文档标题,正好位于剩余页面区域的中心(水平和垂直)。

谷歌了很多,我发现最好的解决方案是创建一个表格并使用它的单元格对齐方法。问题是:要正确使用垂直对齐,我需要设置单元格的最小高度(cell.setMinimumHeight(...);)但我不知道还剩下多少高度!使用带有一些硬编码偏移量的 document.getPageSize ().getHeight () 看起来不是一个好选择 - 我不想在更改字体大小等时更改此硬编码。

这是页面顶部“标题”的代码,如果它很重要:

Paragraph preface = new Paragraph();
Paragraph o = new Paragraph("test", headerFont);
o.add(new LineSeparator(1, 100, Color.BLACK, Element.ALIGN_CENTER, -5));
preface.add(o);
o.add(new Paragraph(" "));
document.add(preface);

【问题讨论】:

    标签: java alignment itext


    【解决方案1】:

    好的,这就是我目前所得到的......

    public static float getAvailableHeight(PdfDocument pdfDocument) {
        Float indentBottom = pdfDocument.bottomMargin();
        try {
            Method method = pdfDocument.getClass().getDeclaredMethod("indentBottom");
            method.setAccessible(true);
            indentBottom = (Float) method.invoke(pdfDocument);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        float offset = pdfDocument.top() - pdfDocument.getVerticalPosition(false);
        return pdfDocument.getPageSize().getHeight() - offset - pdfDocument.topMargin()  - indentBottom
                - pdfDocument.bottomMargin();
    }
    

    为我工作。希望这对其他人有帮助。

    您需要访问封装在 PdfWriter 中的 PdfDocument 对象。我刚刚制作了自己的 CustomPdfWriter,它扩展了 PdfWriter。

    由于方法 indentBottom() 是 PdfDocument 类中的本地包,因此需要带有反射的丑陋部分。

    【讨论】:

      猜你喜欢
      • 2020-01-19
      • 1970-01-01
      • 2012-04-01
      • 2014-01-22
      • 2011-02-13
      • 1970-01-01
      • 2014-02-11
      • 2018-06-23
      • 2020-05-28
      相关资源
      最近更新 更多