You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Syncfusion Flutter Pdf:如何让文本与表格显示在同一页面

解决Syncfusion Flutter Pdf中文本与表格分页问题

你当前的代码之所以会出现文本和表格分属不同页面的问题,核心原因是调用grid.draw()时,用document.pages.add()新建了一个页面,导致表格被绘制到了新页面上。只需要调整两处,就能让二者显示在同一页:

  1. 把表格绘制到已创建的同一个页面(即你一开始定义的page变量)
  2. 调整表格的绘制位置,避免和上方的文本重叠

修改后的完整代码

Future<void> printCustomersPdf(
    transactions,
    date,
    amountInSymbol,
  ) async {
    PdfDocument document = PdfDocument();
    final page = document.pages.add();
    /*First object*/
    final titleFont = PdfStandardFont(PdfFontFamily.courier, 30);
    // 绘制标题,同时计算标题高度,用于后续定位表格
    page.graphics.drawString("HitchRide", titleFont);
    final titleHeight = titleFont.measureString("HitchRide").height;

    /*Second object*/
    PdfGrid grid = PdfGrid();
    grid.columns.add(count: 2);
    grid.headers.add(1);

    PdfGridRow header = grid.headers[0];
    header.cells[0].value = date;
    header.cells[1].value = amountInSymbol;
    header.style = PdfGridCellStyle(
      backgroundBrush: PdfBrushes.lightGray,
      textBrush: PdfBrushes.black,
      font: PdfStandardFont(PdfFontFamily.timesRoman, 12),
    );

    for (final customer in transactions) {
      PdfGridRow row = grid.rows.add();
      row.cells[0].value = customer.date;
      row.cells[1].value = "${customer.amount}.00";
    }
    grid.style = PdfGridStyle(
      cellPadding: PdfPaddings(left: 10, right: 3, top: 4, bottom: 5),
      backgroundBrush: PdfBrushes.white,
      textBrush: PdfBrushes.black,
      font: PdfStandardFont(PdfFontFamily.timesRoman, 12),
    );
    // 关键改动:使用已有的page,同时设置表格在标题下方的位置
    grid.draw(
        page: page, 
        bounds: Rect.fromLTWH(0, titleHeight + 10, page.getClientSize().width, 0));
    List<int> bytes = await document.save();
    AnchorElement(
        href:
            "data:application/octet-stream;charset=utf-16le;base64,${base64.encode(bytes)}")
      ..setAttribute("download", "report.pdf")
      ..click();
    document.dispose();
  }

关键改动说明

  • 移除document.pages.add(),改用初始创建的page对象,确保文本和表格共享同一页面
  • 计算标题的高度,动态设置表格的Y轴起始位置(titleHeight + 10),让表格自动显示在标题下方,避免内容重叠
  • 将表格宽度设置为页面客户端宽度(page.getClientSize().width),让表格自适应页面宽度,布局更规整

内容的提问来源于stack exchange,提问作者EBENEZER OCANSEY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 07:42:40