rpdfexport-to-pdf

How to print or cat text into pdf() in R without markdown


I'm creating a PDF file with some plots, but I want to also include some text message at the bottom. For reasons beyond my control, I cannot install a latex distribution on this system, so I can't knit a markdown file, but have to use pdf().

When I just use print or cat nothing shows up in the pdf. I tried using sink() based on the answer from here, but that didn't work either:

pdf("filename.pdf")
sink("filename.pdf")
print("message")
sink()
dev.off()

No error message was received, but the file created has no pages.

Any ideas? I'm considering a workaround of just plotting a text only plot, but I'm hoping there's a more reasonable solution.


Solution

  • We simply could plot the text with text in pdf device. text only works after a plot call. That we don't have to deactivate everything, we call plot.new which is basically an empty plot. Look into ?pdf and ?text options for further customizing.

    txt <- "message"
    
    pdf("filename2.pdf", paper="a4")
    plot.new()
    text(x=.1, y=.1, txt)  # first 2 numbers are xy-coordinates within [0, 1]
    text(.5, .5, txt, font=2, cex=1.5)
    text(.9, .9, txt, font=4, cex=2, col="#F48024")
    dev.off()
    

    enter image description here

    For the sink solution rather use cat and add a carriage return \r at the very end of the text to obtain a valid last line for pdf processing of the .txt file.

    sink("filename.txt")  # to be found in dir `getwd()`
    cat("message\r")
    sink()
    
    pdf("filename.pdf")  # ditto
    plot.new()
    text(.5, .5, readLines("filename.txt"))
    dev.off()
    

    Customize with different x and y coordinates, font options, and paper formatting in pdf call.

    Result

    enter image description here