# function written by Tom Wenseleers to export plots directly to powerpoint or word # https://github.com/tomwenseleers/export # copy this function to the R console and hit enter. # the active plot window can be exported as a pptx slide or docx file # the ReporteRs library should be installed. # to extort to powerpoint: # export2ppt(file=Òexample.pptxÓ) # this should create a powerpoint slide from the active plot window in the default directory # export2doc(file=Òexample.docsÓ) # this should create a word document of the active plot window in the default directory # you can also set the aspect ratio with aspectr= , scaling with scaling= , font with fontname= and size with pointsize= export2office = function(file = "plot", type="PPT", scaling = 90, aspectr=NULL, vector.graphic = TRUE, fontname = "Arial", pointsize=20) { file=sub("^(.*)[.].*", "\\1", file) if (type=="PPT"|type=="PPTX") {ext=".pptx";type="PPT"} else {ext=".docx";type="DOC"} require(ReporteRs) captureplot = function() {p = invisible(recordPlot()) return(p)} p = captureplot() plotsize = dev.size() plotaspectr = plotsize[[1]]/plotsize[[2]] if (!is.null(aspectr)) plotaspectr=aspectr myplot=function(pl=p) print(pl) if (type=="PPT") {doc = pptx();doc = addSlide(doc, slide.layout = "Blank");pagesize = dim(doc)$slide.dim} else {doc = docx();pagesize = dim(doc)$page-dim(doc)$margins[c(4,3)]} pageaspectr = pagesize["width"]/pagesize["height"] if (pageaspectr>plotaspectr) {xf=plotaspectr/pageaspectr;yf=1} else {xf=1;yf=pageaspectr/plotaspectr} w = (scaling/100)*pagesize["width"]*xf; h = (scaling/100)*pagesize["height"]*yf if (type=="PPT") {doc = addPlot( doc, myplot, vector.graphic = vector.graphic, fontname = fontname, pointsize = pointsize, offx = (pagesize["width"]-w)/2, offy = (pagesize["height"]-h)/2, width = w, height = h) } else {doc = addPlot( doc, myplot, vector.graphic = vector.graphic, fontname = fontname, pointsize = pointsize, width = w, height = h)} writeDoc( doc, paste0(file,ext) ) } export2ppt = function(type="PPT", ...) export2office(type=type,...) export2doc = function(type="DOC", ...) export2office(type=type,...)