R语言:使用RTF软件包将JPEG写入RTF文档



我正在使用RTF软件包,并具有我想将其添加到我正在创建的RTF文档中的JPEG文件。虽然我知道我可以使用RTF软件包的" AddPlot()"功能,但我似乎无法使其正常工作。也许,我需要将JPEG转换为"情节?"。如果是这样,我不确定如何。

感谢您提前的帮助!

以下是我的代码和错误消息:

output <- "DownloadImage_proof_of_concept.doc"
rtf <- RTF(output,width=8.5,height=11,font.size=10,omi=c(1,1,1,1))
addPlot(rtf, plot.fun="y.jpg", width = 4, height = 5, res=300)

.rtf.plot中的错误(plot.fun = plot.fun,tmp.file = tmp.file,width = width,:: 找不到函数" plot.fun" 完成(RTF)

addPlot需要在plot.fun中传递一个函数,而不是文档中所述的JPEG文件名(请参阅help(addPlot.RTF))。

问题是,您需要先绘制JPEG,这不是最简单的事情。
无论如何,由于这个答案,我们可以做到这一点:

library(rtf)
# function defined in the linked answer
# Note: you need to install jpeg package first
plot_jpeg = function(path, add=FALSE){
  require('jpeg')
  jpg = readJPEG(path, native=T) # read the file
  res = dim(jpg)[1:2] # get the resolution
  if (!add) # initialize an empty plot area if add==FALSE
    plot(1,1,xlim=c(1,res[1]),ylim=c(1,res[2]),asp=1,type='n',xaxs='i',
         yaxs='i',xaxt='n',yaxt='n',xlab='',ylab='',bty='n')
  rasterImage(jpg,1,1,res[1],res[2])
}
output<-"test.rtf" 
rtf <- RTF(output,width=8.5,height=11,font.size=10,omi=c(1,1,1,1))
addPlot(rtf, plot.fun=function(){plot_jpeg('myfile.jpg')}, width = 4, height = 5, res=300) 
# ...
done(rtf)

无论如何,如果您有JPEG映像,我建议简单地将其转换为PNG,然后使用方便的函数addPNG,例如。:

output<-"test2.rtf" 
rtf <- RTF(output,width=8.5,height=11,font.size=10,omi=c(1,1,1,1))
addPng.RTF(rtf,file = "myfile.png", width = 4, height = 5) 
# ...
done(rtf)