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:

4
  • 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. Commented Jun 30, 2021 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. Commented Jul 1, 2021 at 2:19
  • I've got the free version and it seems to work, see my answer. Commented Jul 1, 2021 at 2: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. Commented Jul 1, 2021 at 3:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.