PDF格式做为事实上的行业标准,常用于各种场合的商务往来和知识分享载体,因此许多时候需要将Office文档转化为PDF格式,MS Office2007及以上版本提供了将文件另存为PDF格式的功能,但是目前R还没有将Office文档转化为PDF格式的包,因此需要通过R调用VBA利用MS Office自带的功能将文件转化为PDF格式。
本人博客此前文章中曾涉及用openxlsx定制个性化报表后调用VBA自动打印成PDF格式,经过本人查阅StackOverflow和微软官网和不断地尝试,目前已实现将Word、Excel、PPT文件转为PDF格式。现将代码分享如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
###################################################################
# 调用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)
###################################################################
|
目前调用VBA将PPT文件转为PDF格式部分,生成PDF文档后PowerPoint没有自动退出,需要手动关闭,具体原因不详,待日后完善,但是不影响结果。
目前R从Excel和Word文档里提取表格数据都应相应的R包,但是目前还没有R从PowerPoint提取数据的R包,但是我们可以通过将PPT(X)格式的文件通过以上代码转化为PDF格式文件,然后从PDF文件中提取表格数据。