5

I've an R program that outputs a booklet of graphics as a PDF file onto the local server. There's a separate PDF file, an introduction piece, not written in R, that I would like to join my output to.

I can complete this in Adobe and R-bloggers has the process here, both of which involve joining the files by hand, as it were:

http://www.r-bloggers.com/splitting-and-combining-r-pdf-graphics/

But what I'd really prefer to do is just run my code and have the files join. I wasn't able to find similar posts while searching for "[R] Pdf" and "join", "merge", "import pdf", etc..

My intent is to run the code for a different ID number ("Physician") each time. The report will save as a PDF titled by ID number on the server, and the same addendum would be joined to each document.

Here's the current code creating the R report.

Physician<- 1

#creates handle for file name and location using ID
Jumanji<- paste ("X:\\Feedback_ID_", Physician, ".pdf", sep="")

#PDF graphics device on, using file handle
pdf(file=Jumanji,8.5, 11) 

Several plots for this ID occur here and then the PDF is completed with dev.off().

dev.off()

I think I need to pull the outside document into R and reference it in between the opening and closing, but I haven't been successful here.

2 Answers2

7

To do this in R, follow @cbeleites' suggestion (who, I think, is rightly suggesting you move your whole workflow to knitr) to do just this bit in Sweave/knitr. knit the following to pdf, where "test.pdf" is your report that you're appending to, and you'll get the result you want:

\documentclass{article}
\usepackage{pdfpages}
\begin{document}
\includepdf{test.pdf} % your other document
<<echo=FALSE>>=
x <- rnorm(100)
hist(x)
# or whatever you need to do to get your plot
@
\end{document}

Also, the post you link to seems crazy because it's easy to combine plots into a single pdf in R (in fact it's the default option). Simply leave the pdf device open with its parameter onefile=TRUE (the default).

x <- rnorm(100)
y <- rnorm(100)
pdf("test.pdf")
hist(x)
hist(y)
dev.off()

Plots will automatically get paginated.

Thomas
  • 43,637
  • 12
  • 109
  • 140
1

You can also consider something like :

library(qpdf)
path_PDF1 <- "C:/1.pdf"
path_PDF2 <- "C:/2.pdf"
pdf_combine(input = c(path_PDF1, path_PDF2), output = "C:/merged.pdf")
Emmanuel Hamel
  • 1,769
  • 7
  • 19
  • I got [an error](https://stackoverflow.com/questions/76003176/combining-pdf-files-to-a-single-pdf-too-many-open-files) with that solution if I want to combine many PDFs. – captcoma Apr 13 '23 at 08:19
  • You could use it recursively, You merge the first two PDF into one document. After, you merge this document with the third PDF, etc. I will provide other solutions. – Emmanuel Hamel Apr 13 '23 at 13:17