pdf 大小限制后无法查看其他表格

Not able to see other tables after pdf size limit

我已经使用 iTextSharp 生成了 PDF 文件。

我创建了 6 个 PdfPTable,但它只显示了 3 个。

// Create new PDF document 
Document document = new Document(PageSize.A4, 20f, 20f, 20f, 20f);
try {
    PdfWriter writer = PdfWriter.GetInstance(document,
        new FileStream(filename, FileMode.Create));

    document.Open();
    int spacing = 0;

    for (int i = 0; i <= 6; i++) {

        PdfPTable table = new PdfPTable(2);

        table.TotalWidth = 144f;
        table.LockedWidth = false;
        PdfPCell cell = new PdfPCell(new Phrase("This is table" + i));
        cell.Colspan = 3;
        cell.HorizontalAlignment = 1;
        table.AddCell(cell);

        table.WriteSelectedRows(0, -1,
            document.Left + spacing, document.Top,
            writer.DirectContent);

        spacing = spacing + 200;
    }
}

catch (Exception ex) {}

finally {
    document.Close();
    ShowPdf(filename);
}

这里我放了6次for循环但是只显示了3次table.

如何显示所有 6 个 table?我只想在换行后的 1 行中显示 3 table 并显示其他 3 tables.

我认为你的问题标题几乎概括了问题。

当您使用 WriteSelectedRows 时,您有责任提供要写入的 X 和 Y 位置,并且您正在页面边界之外绘图。 A4 有 595 个水平单位,只是空间不够。这是 100% 有效的,但大多数人不会看到它。我猜您想 "wrap" 您的 table 到下一行。有几种方法可以做到这一点:

更大的页面大小

切换到 PageSize.A0 这样的东西,你应该有更多的空间。页面大小只是一个提示,无论如何,打印软件会根据需要缩放。

MOD 签入循环

这是稍微复杂一点的,但是每 n table 秒您将 x 坐标重置到左边缘并将 y 增加最高的table 的前一行。

int spacing = 0;
//The current Y position
float curY = document.Top;

//Well ask iText how tall each table was and set the tallest to this variable
float lineHeight = 0;

//Maximum number of tables that go on a line
const int maxPerLine = 3;

for (int i = 0; i <= 6; i++) {

    PdfPTable table = new PdfPTable(2);

    table.TotalWidth = 144f;
    table.LockedWidth = false;
    PdfPCell cell = new PdfPCell(new Phrase("This is table" + i));
    cell.Colspan = 3;
    cell.HorizontalAlignment = 1;
    table.AddCell(cell);

    table.WriteSelectedRows(0, -1,
        document.Left + spacing, curY,
        writer.DirectContent);

    spacing = spacing + 200;

    //Set the height to whichever is taller, the last table or this table
    lineHeight = Math.Max(lineHeight, table.TotalHeight);

    //If we're at the "last" spot in the "row"
    if (0 == (i + 1) % maxPerLine) {
        //Offset our Y by the tallest table
        curY -= lineHeight;

        //Reset "row level" variables
        spacing = 0;
        lineHeight = 0;
    }
}

包装器table

这是我真正推荐的。如果你想 "wrap" tables 那么只需使用外部 table 来容纳你的内部 tables 并且你可以免费获得所有东西而且你不必弄乱DirectContent(尽管您可能想要更改 table 边框)。

var outerTable = new PdfPTable(3);
outerTable.DefaultCell.Border = PdfPCell.NO_BORDER;

for (int i = 0; i <= 6; i++) {

    PdfPTable innerTable = new PdfPTable(2);

    innerTable.TotalWidth = 144f;
    innerTable.LockedWidth = false;
    PdfPCell cell = new PdfPCell(new Phrase("This is table" + i));
    cell.Colspan = 3;
    cell.HorizontalAlignment = 1;
    innerTable.AddCell(cell);

    outerTable.AddCell(innerTable);

}

document.Add(outerTable);