【问题标题】:Change orientation of iText PdfPTable更改 iText PdfPTable 的方向
【发布时间】:2017-09-11 18:06:45
【问题描述】:

这就是我得到的。我如何也可以旋转表格 - 而不仅仅是文档。如果表格旋转,列可能会更宽。

下面的代码仅用 1 列在较小的范围内重现了该问题。

private void exportTableAsPDF(File outputFile) {

    // PDF document
    Document pdfDocument = new Document();
    try {
        PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(outputFile));

        // Used to rotate the page - iText recommended this approach in an answer to a question referenced below
        // https://developers.itextpdf.com/question/how-rotate-page-while-creating-pdf-document
        class RotateEvent extends PdfPageEventHelper {
            public void onStartPage(PdfWriter writer, Document document) {
                writer.addPageDictEntry(PdfName.ROTATE, PdfPage.SEASCAPE);
            }
        }

        // Rotates each page to landscape
        pdfWriter.setPageEvent(new RotateEvent());
    } catch (Exception e) {
        e.printStackTrace();
    }
    pdfDocument.open();

    // PDF table
    PdfPTable pdfPTable = new PdfPTable(1);

    // Add column header cell
    PdfPCell dateCell = new PdfPCell(new Phrase("Date"));
    pdfPTable.addCell(dateCell);

    // Gets cell data
    LogEntryMapper logEntryMapper = new LogEntryMapper();
    List<LogEntry> logEntries = logEntryMapper.readAll();

    // Adds a cell to the table with "date" data
    for (LogEntry logEntry : logEntries) {
        dateCell = new PdfPCell(new Phrase(logEntry.getLogEntryDate()));
        pdfPTable.addCell(dateCell);
    }

    // Adds the table to the pdf document
    try {
        pdfDocument.add(pdfPTable);
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    pdfDocument.close();
}

此代码块产生以下结果。

【问题讨论】:

  • 请向我们展示一个重现此问题的最小代码示例。
  • @JorisSchellekens 我已根据您的要求添加了代码。
  • 所以你本质上想要一个横向填充的页面?
  • @mkl 这听起来是对的,是的。表格应顺时针旋转 90°,以便用户可以在保持横向页面方向的同时从左到右阅读表格。
  • 我刚试了一下,拿了你的代码,用new Document(PageSize.A4.rotate())替换了new Document(),并删除了页面事件监听器,表格确实利用了额外的空间.你可能用你的多列表测试过吗?您是否可能在该代码中设置了绝对列宽?

标签: itext


【解决方案1】:

您找到的解决方案(使用页面事件侦听器)针对不同的问题:它用于在文档纸张大小上垂直打印,然后旋转包含内容的页面。对于您的问题(在旋转的纸张上垂直打印),您只需要使用旋转的纸张尺寸初始化文档:

Document pdfDocument = new Document(PageSize.A4.rotate());

这样表格可以利用额外的页面大小。

不过,您会注意到左右两侧仍有一些可用空间。有两个原因:

  • 表格尊重为文档配置的页边距;
  • 默认情况下,表格仅使用可用宽度的 80%。

因此,您可以将可用空间左右减少

  • 减少页边距,例如通过使用另一个Document 构造函数

    Document pdfDocument = new Document(PageSize.A4.rotate(),
                                        marginLeft, marginRight, marginTop, marginBottom);
    

    或在创建相关页面之前使用pdfDocument.setMargins(marginLeft, marginRight, marginTop, marginBottom)

  • 增加表格使用的可用宽度的百分比

    pdfPTable.setWidthPercentage(widthPercentage);
    

    使用 widthPercentage 值,例如100.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多