html - 使用 wkhtmltopdf 或 Markdown 将 data.frames 中的 html 保存为 pdf

标签 html r pdf r-markdown wkhtmltopdf

我有一个 df,其中有一列 htmltext 包含 html 文本,我想打印(如果可能的话作为一个批处理)作为单个 PDF,文件名是 doc_id

我可以直接在 R 中这样做吗?

我想过类似的事情

> system("wkhtmltopdf --javascript-delay 1 in.html out.pdf") 

我如何在 R 中实现它? 或者是否有另一种简单的方法来使用 markdown 例如。

# df
doc_id <- c("doc1","doc2","doc3")
htmltext <- c("<b>good morning</b>","<b>This text is bold</b>","<b>good evening</b>")
df <- data.frame(doc_id,htmltext, stringsAsFactors = FALSE)

# save htmltext single pdfs with doc_id as filename
filenames = filenames = df$doc_id
...?

最佳答案

看看其中一个是否可以接受:

library(rmarkdown)
library(decapitated) # devtools::install_github("hrbrmstr/decapitated") # requires Chrome

data.frame(
  doc_id = c("doc1", "doc2", "doc3"),
  htmltext = c("<b>good morning</b>", "<b>This text is bold</b>", "<b>good evening</b>"), 
  stringsAsFactors = FALSE
) -> xdf

# hackish pandoc way
for(i in 1:nrow(xdf)) {
  message(sprintf("Processing %s", xdf$doc_id[i]))
  tf <- tempfile(fileext=".html")
  writeLines(xdf$htmltext[i], tf)
  pandoc_convert(
    input = tf, 
    to = "latex", 
    output = sprintf("%s.pdf", xdf$doc_id[i]),
    wd = getwd()
  )
  unlink(tf)
}

# using headless chrome
for(i in 1:nrow(xdf)) {
  message(sprintf("Processing %s", xdf$doc_id[i]))
  tf <- tempfile(fileext=".html")
  writeLines(xdf$htmltext[i], tf)
  chrome_dump_pdf(sprintf("file://%s", tf), path=sprintf("%s.pdf", xdf$doc[i]))
  unlink(tf)
}

关于html - 使用 wkhtmltopdf 或 Markdown 将 data.frames 中的 html 保存为 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48178725/

相关文章:

asp.net - 文件不以 '%PDF-' 开头

php - 从 TCPDF 在 Chrome 中下载 PDF

css - 如何在 Logo 旁边的标题菜单中插入搜索栏。请告诉我我做错了什么?

html - Paypal 自定义付款链接

php - 我可以从 Google 获取搜索短语吗?

r - 为什么 as.factor 在 apply 内部使用时会返回一个字符?

r - 将因子转换为多列的日期类

c# - 将 HTML 转换为 PDF dink 到 pdf 时 CSS 转换和写入模式属性的问题

javascript - 导航栏上的 Bootstrap 词缀,属性始终打开(类始终处于事件状态)

python - Python 中的分位数回归给出与 R 中不同的结果