動的行を持つテーブルのグループがあります。テーブルがページ間で分割されるシナリオがいくつかあります。一部のシナリオでは、最後の行のみが次のページに分割されます。テーブルに 10 行ある場合、行 1 ~ 9 がページ 1 に表示され、行 10 がページ 2 に表示されるとします。
このシナリオでは、改ページ (document.newpage()) を使用してテーブル全体を次のページに移動するための解決策を探しています。以下のコードを試してみましたが、一部のシナリオでは機能していましたが、すべてではありませんでした。テーブルの最後の行がいつ分割されるかを知りたいので、改ページを追加してテーブル全体を次のページに移動し、最後の行の孤立を回避できます。
public class SplitItextLastRow {
final static private String BODY_FONT = FontFactory.getFont("Arial").getFamilyname();
public static void main(String[] args) {
try {
Document document = new Document();
document.setPageSize(PageSize.LETTER);
document.setMargins(16, 14, 14, 14);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/SplitItext.pdf"));
document.open();
document.setPageSize(PageSize.LETTER);
document.setMargins(16, 14, 14, 14);
int[] maxCountRows = new int[] { 3, 9, 2, 3, 7, 9, 2, 4, 5, 4, 9, 7, 6, 5, 4, 6, 8, 3 };
for (int k = 1; k <= maxCountRows.length; k++) {
PdfPTable table = new PdfPTable(1);
table.setSpacingAfter(0);
table.setSpacingBefore(0);
table.setTotalWidth(document.right() - document.left());
table.setLockedWidth(true);
table.setHeaderRows(1);
table.setSkipFirstHeader(true);
addHeader(table, "Header Row continued " + k, BaseColor.LIGHT_GRAY);
addHeader(table, "Header Row normal " + k, BaseColor.LIGHT_GRAY);
for (int i = 1; i < maxCountRows[k - 1]; i++) {
StringBuilder sb = new StringBuilder();
for (int p = 0; p < maxCountRows[k - 1] * 6; p++) {
sb.append("Text Row ");
}
add(table, sb.toString() + i, BaseColor.WHITE);
}
float verticalPosition = writer.getVerticalPosition(true);
System.out.println("------Table " + k);
if ((verticalPosition - table.getTotalHeight()) <= document.bottom()) {
System.out.println("........................................Last Row splitted");
}
document.add(table);
}
document.close();
} catch (Exception de) {
de.printStackTrace();
}
}
private static void addHeader(PdfPTable table, String text, BaseColor color) {
PdfPCell pdfCellHeader = new PdfPCell();
pdfCellHeader.setBackgroundColor(color);
pdfCellHeader.addElement(new Paragraph(new Phrase(text, FontFactory.getFont(BODY_FONT, 8f, BaseColor.BLUE))));
table.addCell(pdfCellHeader);
}
private static void add(PdfPTable table, String text, BaseColor color) {
PdfPCell pdfCellHeader = new PdfPCell();
pdfCellHeader.setBackgroundColor(color);
pdfCellHeader.addElement(new Paragraph(new Phrase(text, FontFactory.getFont(BODY_FONT, 5f, BaseColor.GREEN))));
table.addCell(pdfCellHeader);
}
}