Adding text string to existing pdf doc

Viewed 237

Is anyone aware of a way to add a text string to an existing pdf (or multiple pdfs) with R? For example, one might want to add a title in a specified position on the page or a watermark.

These similar-sounding questions aren't what I am looking for, as I would like to add text to an existing pdf - not one that I am knitting in Rmd, which would be more straightforward:

1 Answers

If (free command line) version of pdftk is an acceptable auxiliary tool, then you can automate the solution from this question in R (i.e., using the stamp operation in pdftk):

Generate PDF to experiment with:

pdf("test1.pdf")
plot(1:10,1:10)
dev.off()

Generate "watermark" overlay:

pdf("stamp.pdf")
par(fg="white")
## to match spacing etc - 'phantom' plot
plot(1:10,1:10, type="n", axes=FALSE, ann=FALSE)
par(fg="black")
text(5,5, "watermark", col=adjustcolor("gray", alpha.f=0.2), cex=5)
dev.off()

Call pdftk to do the overlay:

system("pdftk test1.pdf stamp stamp.pdf output test1S.pdf")

Results:

plot with added watermark

I think the fussy part will be getting the spacing in the overlay file the way you want it ... although you could use grid graphics, or create a zero-margin/zero-annotation plot so that the plotting area had bounds (0,1) x (0,1) ...

Related