楚新元 | All in R

Welcome to R Square

用 R 将 MS Office 文件转为 PDF 文件

楚新元 / 2021-08-18


PDF 格式做为事实上的行业标准,常用于各种场合的商务往来和知识分享载体,因此许多时候需要将 MS Office 文档转化为 PDF 格式,MS Office2007 及以上版本提供了将文件另存为 PDF 格式的功能,但是目前 R 还没有将 MS Office 文档转化为 PDF 格式的包,因此需要通过R调用 MS Office自带的功能将文件转化为 PDF 格式。

经过本人查阅 StackOverflow 和微软官网和不断地尝试,目前已实现将 Word、Excel、PPT 文件转为 PDF 格式。现将代码分享如下:

# 调用VBA将Word文件转为PDF格式
library(RDCOMClient)
library(here)
wordFile = here("test1.docx")  # 这里使用绝对路径
wordApp = COMCreate("Word.Application")
wordApp[["Visible"]] = TRUE
wd = wordApp[["Documents"]]$Open(Filename = wordFile)

pdfFile = here("test1.pdf")  # 这里使用绝对路径
if (file.exists(pdfFile) == TRUE)  file.remove(pdfFile)
   
wd$SaveAs(
  Filename = pdfFile,
  FileFormat = 17
  )

wordApp$Quit() # 关闭Word文件
rm(wordApp)

# 调用VBA将Excel文件转为PDF格式
library(RDCOMClient)
library(here)
xlFile = here("test2.xlsx")  # 这里使用绝对路径
xlApp = COMCreate("Excel.Application")
xlApp[["Visible"]] = TRUE 
wb = xlApp[["Workbooks"]]$Open(Filename = xlFile)
sht = wb[["Worksheets"]]$Item(1)

pdfFile = here("test2.pdf")  # 这里使用绝对路径
if (file.exists(pdfFile) == TRUE)  file.remove(pdfFile)

sht$ExportAsFixedFormat(
  Filename = pdfFile,
  Type = 0,    # 导出为PDF
  IgnorePrintAreas = FALSE
)

xlApp$Quit() # 关闭Excel文件 
rm(xlApp)

# 调用VBA将PPT文件转为PDF格式
library(RDCOMClient)
library(here)
pptFile = here("test3.pptx")  # 这里使用绝对路径
pptApp = COMCreate("PowerPoint.Application")
pptApp[["Visible"]] = TRUE
ppt = pptApp[["Presentations"]]$Open(Filename = pptFile)

pdfFile = here("test3.pdf")  # 这里使用绝对路径
if (file.exists(pdfFile) == TRUE)  file.remove(pdfFile)

range = ppt$PrintOptions()$Ranges()$Add(1, 1)
ppt$ExportAsFixedFormat(
  pdfFile, 2, 1, 0, 1, 1, 0, range)

pptApp$Quit() # 关闭PPT文件
rm(pptApp)

目前调用 MS Office 将 PPT 文件转为 PDF 格式部分,生成 PDF 文档后 PowerPoint 没有自动退出,需要手动关闭,具体原因不详1,待日后完善,但是不影响结果。

目前 R 从 Excel 和 Word 文档里提取表格数据都应相应的 R 包,但是目前还没有 R 从 PowerPoint 提取数据的 R 包,但是我们可以通过将 PPT(X) 格式的文件通过以上代码转化为 PDF 格式文件,然后从 PDF 文件中提取表格数据。


  1. 初步查明是 MS Office 的 Bug,因为打开的 PPT 文件的文件名竟然不是本地文件的文件名,手动点击保存后才正常。 ↩︎