R chrome_print() 横向 = T 在打印时不调整 HTML 大小?

问题描述 投票:0回答:1

我正在我的 R Shiny 应用程序中创建一个报告,该报告发送参数来编织 html 文件,然后对其运行 chrome_print() 将其转换为 PDF。这样做的原因是因为我想将我的 echarts4r 小部件作为参数发送,以节省计算时间并保持 SVG 无损质量。

我遇到的问题是,当我设置 Landscape = T 时,它似乎没有将小部件调整为打印区域的宽度。通过非无头浏览器手动执行操作时,它确实打印到正确的宽度。

下面是一个最小的例子:

R Markdown ```` --- 标题:《无题》 作者:“富莱拉” 日期:“

r Sys.Date()
” 输出:html_document ---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
Output the plot
mtcars |>
e_charts(cyl,renderer = 'svg') |>
e_line(mpg) |> e_animation(show = F)
```

R代码 ```` 库(echarts4r) 图书馆(向下翻页)

pagedown::chrome_print(input = 'untitled.html', output = 'foo.pdf', options = 
list(landscape=T))
```
r r-markdown knitr pagedown echarts4r
1个回答
0
投票

我最终使用

chromote package

解决了这个问题

更多详细信息请访问以下网址:https://nanx.me/blog/post/chromote-pdf-automation/

library("promises")
library("chromote")

#' Print HTML to PDF using chromote
#'
#' @param url Input URL
#' @param filename Output file name
#' @param wait_ If TRUE, run in synchronous mode,
#' otherwise, run in asynchronous mode.
#' @param ... Additional parameters for Page.printToPDF, see
#' <https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF>
#' for possible options.
print_to_pdf <- function(url, filename = NULL, wait_ = FALSE, ...) {
  if (is.null(filename)) {
    filename <- url |>
      gsub("^.*://", "", x = _) |>
      gsub("/$", "", x = _) |>
      fs::path_sanitize(replacement = "_") |>
      paste0(".pdf")
  }
  
  b <- ChromoteSession$new()
  
  p <-
    {
      b$Page$navigate(url, wait_ = FALSE)
    } %...>%
    {
      b$Page$loadEventFired(wait_ = FALSE, timeout_ = 2000)
    } %...>%
    {
      b$Page$printToPDF(..., wait_ = FALSE,landscape = T)
    } %...>%
    {
      .$data
    } %...>%
    {
      outfile <- file(filename, "wb")
      base64enc::base64decode(., output = outfile)
      close(outfile)
    } %...>%
    {
      message(filename)
    } %>%
    finally(~ b$close())
  
  if (wait_) {
    b$wait_for(p)
  } else {
    p
  }
  
  invisible(filename)
}





f <- "https://nanx.me/blog/post/r-readability-parser/example.html" |>
  curl::curl_download(destfile = 'downloaded.html')


print_to_pdf(
  paste0("file://", normalizePath(f, winslash = "/")),
  filename = "example.pdf",
  wait_ = TRUE
)
© www.soinside.com 2019 - 2024. All rights reserved.