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

如何调整DT表格PDF导出的标题大小与表格适配性?

解决DT表格PDF导出的列截断与标题大小调整问题

DT的PDF导出功能基于pdfMake库,要调整导出样式需通过按钮配置中的customize参数修改pdfMake的文档定义,以下是具体解决方案:

调整PDF导出的标题大小

在extend = 'pdf'的按钮配置中添加customize函数,直接修改导出文档中标题的字号:

customize = function(doc) {
  # 将标题字号设为12(默认约16),可按需调整
  doc.content[1].textSize = 12
}

解决列截断问题

提供两种实用方案,可根据需求选择:

方案1:自动适配列宽+缩小内容字体

通过设置表格自动布局并缩小内容字体,让列适配A4横向页面:

customize = function(doc) {
  # 缩小表格内容字号,减少横向占用空间
  doc.content[2].table.bodyStyle.fontSize = 8
  # 开启自动布局,让列宽自适应内容
  doc.content[2].table.layout = 'automatic'
}

方案2:手动固定列宽

如果需要精准控制列宽,先在DT的options中定义列宽,再配合固定布局:

# 在DT的options中添加列宽配置
options = list(
  dom = 'Bt',
  # 所有列设为8%宽度,可针对特定列(targets指定列索引)单独设置
  columnDefs = list(list(width = '8%', targets = "_all")),
  buttons = list(...)
)

然后在customize函数中启用固定布局:

customize = function(doc) {
  doc.content[2].table.layout = 'fixed'
}

完整示例代码

整合所有配置后的完整Shiny代码:

library("shiny")
library("DT")

data <- cbind(iris, iris, iris)
shinyApp(
  ui = fluidPage(DT::dataTableOutput('tbl')),
  server = function(input, output) {
    output$tbl = DT::renderDataTable(
      data,
      extensions = "Buttons",
      options = list(
        dom = 'Bt',
        columnDefs = list(list(width = '8%', targets = "_all")),
        buttons = list(
          list(
            extend = 'pdf',
            pageSize = 'A4',
            orientation = 'landscape',
            filename = 'tt',
            title = "A smaller title here",
            customize = function(doc) {
              # 调整标题字号
              doc.content[1].textSize = 12
              # 调整表格内容字号
              doc.content[2].table.bodyStyle.fontSize = 8
              # 使用固定布局适配手动设置的列宽
              doc.content[2].table.layout = 'fixed'
              # 可选:缩小页面边距,增加表格可用空间
              doc.pageMargins = [20, 20, 20, 20]
            }
          )
        )
      )
    )
  }
)

内容的提问来源于stack exchange,提问作者Sunny League

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 01:24:31