Mou*_*mii 3 pdf r package text-files shiny
我想问一下是否可以使用R将文本文件(例如word文档或文本文档)转换为PDF?我想使用此代码将其转换为 .rmd,然后转换为 PDF
require(rmarkdown)
my_text <- readLines("C:/.../track.txt")
cat(my_text, sep=" \n", file = "my_text.Rmd")
render("my_text.Rmd", pdf_document())
Run Code Online (Sandbox Code Playgroud)
但它不起作用显示此错误:
> Error: Failed to compile my_text.tex.
In addition: Warning message:
running command '"pdflatex" -halt-on-error -interaction=batchmode "my_text.tex"' had status 127
Run Code Online (Sandbox Code Playgroud)
还有其他解决方案吗?
安装wkhtmltopdf,然后从 R 运行以下命令。根据wkhtmltopdf系统上的位置以及输入和输出文件路径和名称,适当更改前三行。
wkhtmltopdf <- "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe"
input <- "in.txt"
output <- "out.pdf"
cmd <- sprintf('"%s" "%s" -o "%s"', wkhtmltopdf, input, output)
shell(cmd)
Run Code Online (Sandbox Code Playgroud)
安装pandoc,根据需要修改下面的前三行并运行。效果如何可能会因您的输入而异。
pandoc <- "C:\\Program Files (x86)\\Pandoc\\pandoc.exe"
input <- "in.docx"
output <- "out.pdf"
cmd <- sprintf('"%s" "%s" -o "%s"', pandoc, input, output)
shell(cmd)
Run Code Online (Sandbox Code Playgroud)
小智 5
我绝对无法让 Pandoc 方法为我工作。
不过,我确实找到了一种使用 RDCOMClient 将 docx 转换为 PDF 的方法。
library(RDCOMClient)
file <- "C:/path/to your/doc.docx"
wordApp <- COMCreate("Word.Application") # create COM object
wordApp[["Visible"]] <- TRUE #opens a Word application instance visibly
wordApp[["Documents"]]$Add() #adds new blank docx in your application
wordApp[["Documents"]]$Open(Filename=file) #opens your docx in wordApp
#THIS IS THE MAGIC
wordApp[["ActiveDocument"]]$SaveAs("C:/path/to your/new.pdf",
FileFormat=17) #FileFormat=17 saves as .PDF
wordApp$Quit() #quit wordApp
Run Code Online (Sandbox Code Playgroud)
我在这里发现 FileFormat=17 位https://learn.microsoft.com/en-us/office/vba/api/word.wdexportformat
希望这有帮助!