我在一个循环中使用officer (用于使用reporters)来创建150个独特的文档。我需要这些文件,但是,从R导出为word,docx和pdfs。
有没有办法将officer创建的文档导出为pdf?
发布于 2018-09-18 22:49:24
这是可能的,但我的解决方案依赖于libreoffice。这是我正在使用的代码。希望这能有所帮助。我已经对libreoffice path进行了硬编码,那么您可能需要调整或改进变量cmd_的代码。
代码将PPTX或DOCX文件转换为PDF。
library(pdftools)
office_shot <- function( file, wd = getwd() ){
cmd_ <- sprintf(
"/Applications/LibreOffice.app/Contents/MacOS/soffice --headless --convert-to pdf --outdir %s %s",
wd, file )
system(cmd_)
pdf_file <- gsub("\\.(docx|pptx)$", ".pdf", basename(file))
pdf_file
}
office_shot(file = "your_presentation.pptx")发布于 2018-12-19 12:24:35
我一直在使用RDCOMClient将我的OfficeR创建的文档转换为PDF。
library(RDCOMClient)
file <- "C:/path/to your/doc.docx"
wordApp <- COMCreate("Word.Application") #creates COM object
wordApp[["Documents"]]$Open(Filename=file) #opens your docx in wordApp
wordApp[["ActiveDocument"]]$SaveAs("C:/path/to your/doc.pdf"), FileFormat=17) #saves as PDF
wordApp$Quit() #quits the COM Word application我在这里找到了FileFormat=17代码https://docs.microsoft.com/en-us/office/vba/api/word.wdexportformat
我已经能够将上面的内容放在一个循环中,以便快速地将多个docx转换为PDF。
希望这能有所帮助!
发布于 2020-09-21 16:04:18
有一种方法可以将您的docx转换为pdf。docxtractr包中有一个函数convert_to_pdf。
请注意,此函数使用LibreOffice将docx转换为pdf。因此,您必须在安装LibreOffice之前安装并写入soffice.exe的路径。阅读有关不同操作系统here的路径的更多信息。
下面是一个简单的例子,如何在Windows机上将几个docx文档转换成pdf。我安装了Windows10和LibreOffice 6.4。假设您在data文件夹中存储了PDF文档,并且您希望在data/pdf文件夹中创建相同数量的X (您必须在此之前创建pdf文件夹)。
library(dplyr)
library(purrr)
library(docxtractr)
# You have to show the way to the LibreOffice before
set_libreoffice_path("C:/Program Files/LibreOffice/program/soffice.exe")
# 1) List of word documents
words <- list.files("data/",
pattern = "?.docx",
full.names = T)
# 2) Custom function
word2pdf <- function(path){
# Let's extract the name of the file
name <- str_remove(path, "data/") %>%
str_remove(".docx")
convert_to_pdf(path,
pdf_file = paste0("data/pdf/",
name,
".pdf"))
}
# 3) Convert
words %>%
map(~word2pdf(.x))https://stackoverflow.com/questions/52388945
复制相似问题