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

在Grails框架中如何从GSP页面生成并导出PDF文件?

需要将GSP中的表格导出为PDF

GSP页面表格导出PDF实操方案

以下是两种常用可落地的实现路径,直接提供可复用的代码示例:

路径1:后端导出(适配大数据量、格式要求高的场景)

基于Grails生态的Export插件实现,和现有后端逻辑适配性高:

  • 第一步:引入插件依赖,在build.gradle的dependencies块中添加:
    compile "org.grails.plugins:export:3.0.0"
  • 第二步:Controller中新增导出接口,可直接复用GSP页面表格的查询逻辑,示例代码:
def exportPdf() {
    // 复用GSP页面渲染表格的查询逻辑获取数据
    def reportData = BusinessReport.findAllByYear(params.year)
    // 配置导出参数
    def exportCfg = new ExportConfig(
        fileName: "业务报表_${new Date().format('yyyyMMdd')}.pdf",
        header: "年度业务报表",
        columnNames: [
            "deptName": "部门名称",
            "income": "年度营收",
            "cost": "运营成本",
            "profit": "净利润",
            "rate": "同比增长率"
        ]
    )
    // 执行导出
    exportService.export("pdf", response.outputStream, reportData, exportCfg)
    response.contentType = "application/pdf"
    response.setHeader("Content-disposition", "attachment; filename=${exportCfg.fileName}")
}
  • 第三步:GSP页面添加导出入口:
    <g:link action="exportPdf" params="${params}" class="btn btn-info">导出PDF报表</g:link>

路径2:前端导出(适配轻量场景、无需修改后端逻辑)

基于jsPDF + html2canvas组合实现,直接读取页面上渲染完成的表格导出,样式和页面完全一致:

  • 第一步:GSP页面引入前端依赖:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
  • 第二步:给需要导出的表格添加id标识,比如:
    <table class="report-table" id="toExportTable"> <!-- 原有表格内容 --> </table>
  • 第三步:添加导出按钮和点击逻辑:
<button id="exportBtn">导出PDF</button>
<script>
document.getElementById('exportBtn').addEventListener('click', async () => {
    const { jsPDF } = window.jspdf
    // 初始化A4尺寸PDF
    const pdfDoc = new jsPDF('p', 'pt', 'a4')
    const tableDom = document.getElementById('toExportTable')
    // 渲染表格为高清canvas
    const canvas = await html2canvas(tableDom, { scale: 2, useCORS: true })
    const imgData = canvas.toDataURL('image/png')
    // 适配A4纸尺寸
    const pageWidth = 555
    const pageHeight = (canvas.height * pageWidth) / canvas.width
    pdfDoc.addImage(imgData, 'PNG', 30, 30, pageWidth, pageHeight)
    pdfDoc.save('业务报表.pdf')
})
</script>

优化提示

  • 如果表格内容过长需要分页,前端方案可以替换为jsPDF的autoTable插件,直接读取表格DOM生成可复制的结构化文本PDF,自动处理分页逻辑。
  • 后端导出需要完全匹配GSP页面样式的话,可以集成wkhtmltopdf工具直接渲染GSP页面输出PDF,样式还原度100%。

内容的提问来源于stack exchange,提问作者Sparsh Gahlot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:57:04