Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pdf to png in R

Tags:

r

pdf

I'm trying to convert a pdf plot to a png or jpeg file. The reason is that I want to use the images for presentations and I need both formats, having exactly the same dimensions/scaling.

I tried the function im.convert() in the animation package, but the output looks really bad, in both png and jpeg.

To be able to run the following code you need the "animation" package and the ImageMagick software (http://www.imagemagick.org/script/convert.php)

library("animation")
ani.options(outdir = getwd())

pdf("bm.pdf")
plot(1:10)
dev.off()

im.convert("bm.pdf", output = "bm.jpeg")
im.convert("bm.pdf", output = "bm.png")
like image 507
aymer Avatar asked Sep 04 '13 14:09

aymer


1 Answers

The result of im.convert is probably not satisfactory because it uses the default resolution, which is 74 dpi. You can increase the resolution by passing an extra parameter:

im.convert("bm.pdf", output = "bm.png", extra.opts="-density 150")

-density 150 will double the resolution and your PNGs and JPEGs will look nicer.

But in general it is probably better to use png() and jpeg() to generate the plots and use appropiate parameters to get the same results as with pdf(). For example:

pdf(width=5, height=5)
plot(1:10)
dev.off() 

png(width=5, height=5, units="in", res=150) 
plot(1:10)
dev.off()
like image 158
f3lix Avatar answered Sep 19 '22 17:09

f3lix