2

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:

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Dylan_Gomes
  • 2,066
  • 14
  • 29
  • Not sure/aware whether you can "tweak" a pdf file. Conceptually, you can read in the pdf file with `{pdftools}`. Then you can manipulate the "payload" to your liking (e.g. inserting a title programmatically). You can then render the new "payload" to pdf again. – Ray Jun 30 '21 at 21:37
  • @BenBolker I did see this question at superuser, but it appeared to me from the pdftk webpage that the watermark is no longer a part of the free toolkit, but the pro tool kit - but perhaps this is incorrect. It is only currently $3.99, but was hoping for a free solution. – Dylan_Gomes Jul 01 '21 at 02:19
  • I've got the free version and it seems to work, see my answer. – Ben Bolker Jul 01 '21 at 02:46
  • Your answer works great. I find the bolded text underneath pdftk free and pdftk pro on the pdftk webpage to be misleading, where stamp is only mentioned after pdftk pro, but appears to work with the free version just fine. – Dylan_Gomes Jul 01 '21 at 03:22

1 Answers1

1

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) ...

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453