R Compile png files into PDF

Let’s compile existing png files into one pdf, using a simple function, called merge.png.pdf():

 

merge.png.pdf <- function(pdfFile, pngFiles, deletePngFiles=FALSE) {

#### Package Install ####
pngPackageExists <- require ("png")

if ( !pngPackageExists ) {
install.packages ("png")
library ("png")

}
#########################

pdf(pdfFile)

n <- length(pngFiles)

for( i in 1:n) {

pngFile <- pngFiles[i]

pngRaster <- readPNG(pngFile)

grid.raster(pngRaster, width=unit(0.8, "npc"), height= unit(0.8, "npc"))

if (i < n) plot.new()

}

dev.off()

if (deletePngFiles) {

unlink(pngFiles)
}

}

 

To test this function, we need to make some test png files:

 


pngFiles <- c()

for (i in 1:5) {

x <- rnorm(n = 25000, mean = 0, sd = 5)
y <- rnorm(n = 25000, mean = 0, sd = 5)

pngFile <- paste0("~/test", i, ".png")
pngFiles[i] <- pngFile

png(filename = pngFile)
plot(x, y, main = paste0("test #", i))
dev.off()

}

Now, we have 5 new png files that we want to compile into one pdf file! These file names are saved in pngFiles.

post-compile-png
To read and compile png files, you need a package, called “png”. ┬ámerge.png.pdf () function will take care of installing this package if you do not have it installed.

 


merge.png.pdf (pdfFile = "~/test.pdf", pngFiles = pngFiles, deletePngFiles = F)

Now you will see a new pdf in the same directory!

 

post-compile-pdf

 

Let’s see if this pdf file has all the png files in it!

 

post-compile-pdf-howitlooks

 

Yay, it works!

ENJOY compile.png.pdf()!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s