这就是我所得到的。如何旋转表格 - 而不仅仅是文档。如果桌子被旋转,列可以更宽。
下面的代码只用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();
}
答案 0 :(得分:2)
您找到的解决方案(使用页面事件侦听器)是针对另一个问题:它用于直接打印文档纸张大小,然后旋转包含内容的页面。对于您的问题(在旋转的纸张上直立打印),您只需要使用旋转的纸张尺寸初始化文档:
Document pdfDocument = new Document(PageSize.A4.rotate());
这样,表格可以使用额外的页面大小。
但是,您会注意到左右两侧仍有一些空闲空间。这有两个原因:
因此,您可以通过
左右减少可用空间减少页边距,例如通过使用另一个Document
构造函数
Document pdfDocument = new Document(PageSize.A4.rotate(),
marginLeft, marginRight, marginTop, marginBottom);
或在创建相关网页之前使用pdfDocument.setMargins(marginLeft, marginRight, marginTop, marginBottom)
;
增加表格所用宽度的百分比
pdfPTable.setWidthPercentage(widthPercentage);
使用例如widthPercentage
的值100
。