I am creating a report in my R Shiny app that sends parameters to knit a html file and then runs chrome_print() on that to convert it to a PDF. The reason it is done this way is because I want to send my echarts4r widgets as parameters to save compute time and maintain SVG lossless quality.
The issue I am having is that when I set landscape = T it does not seem to adjust the widget to the width of the print area. It does print to the correct width when performing the operation manually through a non headless browser.
Here is a minimal example below:
R Markdown
```
---
title: "Untitled"
author: "fullera"
date: "r Sys.Date()
"
output: 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 Code ``` library(echarts4r) library(pagedown)
pagedown::chrome_print(input = 'untitled.html', output = 'foo.pdf', options =
list(landscape=T))
```
I ended up solving this by using the chromote package
More details at the URL: 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
)