2

I have ~10,000 png images saved neatly in different files on my PC. I want to write a function that does something like go to a particular folder and iteratively copy-pastes all the png files in that folder to a word document. Is this possible in R?

I've looked at package R2wd but it sadly only has a function that takes RData and outputs its plot to a word document (function wdPlot).

I also have the RData saved for each and every plot, so reason would dictate that I should be able to simply load the RData associated with a particular plot and then use wdPlot . The problem is that when I generated my png's the plots were grobs and I did something as follows:

png("rp.png",width=w,height=h)
plot(rp)
#Increase size of title
grid.edit(gridTitle_Ref, gp=gpar(fontsize=20))
#Other grid.edit alterations
dev.off()
save(rp)

Now, when I try to get that rp onto a word document by first loading it into R I naively do the following and it does not output a plot to MS Word with the title enlarged or any of the other grid.editalterations.

load("rp.Rdata")    
png("rp.png",width=w,height=h)
wdPlot(rp) 
#Increase size of title 
grid.edit(gridTitle_Ref, gp=gpar(fontsize=20))
#Other grid.edit alterations
dev.off()

So, to reiterate: I have all these png files. At various times I have to copy-paste a subset of them into a word document. I'm too lazy to do that manually each time and want a program to do it for me.

EDIT 1

So, as per suggestions below, I've read up on Markdown. Following this post How to set size for local image using knitr for markdown? I wrote something along the lines of:

```{r,echo=FALSE,fig.width=100, fig.height=100}
# Generate word documents of reports
# Clear all
rm(list=ls())
library(png)
library(grid)
library(knitr)

dir<-"location\of\file"
setwd(dir)

# Output only directories:
folders<-dir()[file.info(dir())$isdir]

for(folder in folders){ 
  currentDir<-paste(dir,folder,"\\",sep="")
  setwd(currentDir)

  #All files in current folder
  files<-list.files()

  imgs<-[A list of all the png images in this particular file that I want in the word document - the png names]

  for(img in imgs){   
    imgRaster<-readPNG(img) 
    grid.raster(imgRaster)
    }
 } 

```

The following is a screenshot of what's in the resulting word document. How might I fix this? I want the images to appear one after the other in the document as the for loop above runs.

enter image description here

Do note that this is the first time I've ever used Markdown so any relevant tutorials linked in the comments could also be of great help.

EDIT 2 I followed the second answer's example below. Here is the output that I obtained enter image description here enter image description here

As you can see there are no images, only the html tags. How do I fix this?

Community
  • 1
  • 1
Frikster
  • 2,755
  • 5
  • 37
  • 71

2 Answers2

3

If you have the png's saved you can just use a little html and a for loop to save them to a .doc file.

edit 2 for windows

# Start empty word doc
cat("<body>", file="exOut.doc", sep="\n")

 # select all png files in working directory
for(i in list.files(pattern="*.png"))
         {
         temp <- paste('<img src=', i, '>')
         cat(temp, file="exOut.doc", sep="\n", append=TRUE)  
         }

cat("</body>", file="exOut.doc", sep="\n", append=TRUE)

# Some example plots
for(i in 1:5) 
      { 
      png(paste0("ex", i, ".png"))
      plot(1:5)
      title(paste("plot", i))
      dev.off()
      }


# Start empty word doc
cat(file="exOut.doc")

# select all png files in working directory
for(i in list.files(pattern="*.png")) 
             {
             temp <- paste('<img src=', i, '>')
             cat(temp, file="exOut.doc", sep="\n", append=TRUE)   
             }

You will then need to embed the figures, either using the drop down menus or by writing a small macro that you can call with system


EDIT : small update to show explicit paths to output and figures

cat("<body>", file="/home/daff/Desktop/exOut.doc", sep="\n")

for(i in list.files(pattern="*.png")) 
{
  temp <- paste0('<img src=/home/daff/', i, '>')
  cat(temp, file="/home/daff/Desktop/exOut.doc", sep="\n", append=TRUE)   
}

Note that i used paste0 to remove the space between the path /home/daff/ and ex*.png.

user20650
  • 24,654
  • 5
  • 56
  • 91
  • I understand what your example does. I now have a word document with a list of html tags for each image. Could you please link me to a tutorial showing me how to change the html tags to actual images? I've been googling for a while without much luck. Also, if you look at the update in my OP you'll see I have a new problem. – Frikster Nov 26 '14 at 22:52
  • Hi Dirk - sorry i can't point to a tutorial other than w3.org (although maybe this will give a bit of info http://www.w3.org/MarkUp/html3/img.html). What the above code does is create links to the png files, and the plots should show if the paths have been correctly defined including/excluding spaces. I have added a small update (without much change) to show how i create the links with explicit paths. BTW, did the small example in my answer work ok, as the plots and output file should just go to your working directory? To move the file (say to another PC) you need to embed the images. – user20650 Nov 27 '14 at 00:23
  • Actually, you are right in that you will get a list of paths to images if you open the file in a text editor (like ``) but if you open the file with word the plots should show. – user20650 Nov 27 '14 at 00:33
  • Okay so it looks like your small example isn't working then. I do have the exOut in my working directory, but when I open it with ms-word 2013 a screen pops up asking me for File Conversion. I pick the default option and then just get a .doc with: I'll attach a screenshot to my op – Frikster Nov 27 '14 at 01:01
  • I've included a screenshot of what your example is doing (It's under "EDIT 2"). I ran setwd("C:\Users\dirk\Downloads") and then ran your code exactly as you wrote it and the screenshot shows what I got – Frikster Nov 27 '14 at 01:11
  • Hi again Dirk - sorry, i was a bit lazy and didn't try on a windows PC - edit 2 is tried on W8 MSW2007 and works as expected. – user20650 Nov 27 '14 at 01:15
  • Well would you look at that. Your example works with OpenOffice but not with MS-word 2013. Score one for Open Source. Looks like switching over will get me what I need. – Frikster Nov 27 '14 at 02:35
  • Great , you got something that worked. So edit 2 didnt work with word-2013? – user20650 Nov 27 '14 at 03:42
  • omg yes it works, but I suddenly have a new problem. My png files have spaces in the names and I see this murders the connection. For instance, if you replace "ex" with "e x" in your example (so "ex1.png" becomes "e x1.png") then it no longer works! How can I account for this case? – Frikster Nov 27 '14 at 07:14
  • 1
    Spaces in the file name . What you need to do is put the path in quotes ie ``. This should do it, change to... `temp <- paste0('')`. (notice the escaped quotes `\"`) ` – user20650 Nov 27 '14 at 13:34
2

Have you tried Rstudio and Markdown? You could put your code into chunks that load the files and save as word document. http://rmarkdown.rstudio.com/word_document_format.html

Robert
  • 5,038
  • 1
  • 25
  • 43
  • R Markdown is the way to go. – Athos Nov 25 '14 at 01:26
  • Hi, thanx. I use RStudio but this is the first I hear of Markdown. By the look of things I managed to save all the images as you suggested, but when I save it to a word file all my images are on top of one another. How might I fix this? You can look at my OP which I updated which shows what I mean. – Frikster Nov 26 '14 at 21:38
  • 1
    Try using 'grid.newpage()' after 'grid.raster'. You do not need to set the fig.width, fig.height parameters. – Robert Nov 27 '14 at 18:22