首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >iText PdfPTable的变化方向

iText PdfPTable的变化方向
EN

Stack Overflow用户
提问于 2017-09-10 11:45:50
回答 1查看 1.6K关注 0票数 0

这就是我要得到的。我怎样才能旋转表,而不仅仅是文件。如果表被旋转,列可能会更宽。

下面的代码只使用1列就可以在较小的范围内再现问题。

代码语言:javascript
运行
复制
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();
}

此代码块产生以下结果。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-11 09:47:37

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

代码语言:javascript
运行
复制
Document pdfDocument = new Document(PageSize.A4.rotate());

这样,表就可以使用额外的页面大小。

你会注意到,仍然有一些自由的空间,左和右。这有两个原因:

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

因此,你可以减少左边和右边的自由空间。

  • 减少页边距,例如使用另一个Document构造函数 Document pdfDocument =新文档(PageSize.A4.旋转(),marginLeft,marginRight,marginTop,marginBottom); 或者在创建页面之前使用pdfDocument.setMargins(marginLeft, marginRight, marginTop, marginBottom)
  • 增加表使用的可用宽度百分比 pdfPTable.setWidthPercentage(widthPercentage); 使用widthPercentage值例如100
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46140356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档