0

I am using RTF package, and have a JPEG file that I would like to add to the RTF document that I'm creating. While, I know that I can use "addPlot()" function of RTF package, but I can't seem to make it work. Perhaps, I need to convert the JPEG into a "Plot?". If so, I'm not sure how.

Thank you for your help in advance!

Below is my code and the error message:

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)

Error in .rtf.plot(plot.fun = plot.fun, tmp.file = tmp.file, width = width, : could not find function "plot.fun" done(rtf)

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
Soly
  • 155
  • 1
  • 2
  • 9

1 Answers1

1

addPlot needs a function to be passed in plot.fun, not a jpeg file name, as described in the documentation (see help(addPlot.RTF)).

Problem is, you need to plot a jpeg first, and this is not the simplest thing to do.
Anyway, thanks to this answer, we can do that :

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)

Anyway, if you have a jpeg image, I suggest to simply convert it in png and then use the convenient function addPNG, e.g. :

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)
Community
  • 1
  • 1
digEmAll
  • 56,430
  • 9
  • 115
  • 140