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

如何在R Shiny导出的PDF报告中完整显示数据表

解决Shiny导出PDF报告时表格右侧截断的问题

表格在PDF中截断的核心原因是列数过多、内容宽度超出页面范围,以下是针对性的解决方案:

一、调整PDF页面基础设置

先修改Rmd的YAML配置,切换为横向页面并缩小页边距,给表格留出更多空间:

---
title: "Test"
output: 
  pdf_document:
    orientation: landscape
    toc: false
params:
  table0: NA
header-includes:
  - \usepackage{tabu}
  - \usepackage{geometry}
  - \geometry{margin=1in}
---

二、kableExtra表格适配方案

使用scale_down参数强制表格缩放到页面宽度,或开启自动换行处理长文本:

library(knitr)
library(kableExtra)

# 方案1:缩放表格至页面宽度
params$table0 %>%
  kable("latex", booktabs = TRUE) %>%
  kable_styling(full_width = TRUE, latex_options = c("scale_down"))

# 方案2:自动换行处理长内容(适合文本列较多的情况)
params$table0 %>%
  mutate(across(where(is.character), linebreak)) %>%
  kable("latex", booktabs = TRUE, escape = FALSE) %>%
  kable_styling(full_width = TRUE)

三、gt表格适配方案

通过调整字体大小、启用自动换行和设置表格宽度来适配页面:

library(gt)

params$table0 %>%
  gt() %>%
  tab_header(title = "Hello") %>%
  tab_options(
    table.font.size = 8, # 缩小字体
    table.width = pct(100), # 表格占满页面宽度
    data_row.padding = px(2) # 减小行内边距
  ) %>%
  text_transform(
    locations = cells_body(where(is.character)),
    fn = function(x) str_wrap(x, width = 15) # 文本自动换行
  )

四、Shiny代码的关键修正

原代码中downloadHandler的content部分需要确保生成的PDF正确传递给下载文件,修改如下:

server <- function(input, output) {
  table <- reactive ({
    data.frame(table1)
  })

  output$report_pdf <- downloadHandler(
    filename = "Test.pdf",
    content = function(file) {
      # 使用临时文件存储渲染结果
      temp_report <- file.path(tempdir(), "Test.Rmd")
      file.copy("Test.Rmd", temp_report, overwrite = TRUE)
      
      params <- list(table0 = table())
      
      # 直接将输出文件指定为下载的file路径
      rmarkdown::render(input = temp_report,
                        output_file = file,
                        params = params,
                        envir = new.env(parent = globalenv()))
    })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:35:21