2
votes

I have a folder which contains around 400 .pdf files, each .pdf file is 2 pages total.

All .pdf file names are under the following format:

148-c16631-27-02-2018.pdf

What I would like is to merge under one pdf file, the pdf files that have a certain code in the file name in R. For instance:

148-c16631-27-02-2018.pdf
148-c14369-27-02-2018.pdf
148-c101593-27-02-2018.pdf

These have the code 148 which is unique, to be merged into 1 pdf file with 8 pages.

Thank you in advance for any input.

1
Try the staplr package. - hrbrmstr

1 Answers

3
votes

Install pdftk and ensure it is on your path (or if not on your path use the full pathname when referring to it in the system command below). Then run the code below. No packages are used.

setwd("...directory where pdf files are located...") ##
infiles <- Sys.glob("148-*.pdf") ##
outfile <- "148.pdf" ##
system(paste("pdftk", paste(infiles, collapse = " "), "cat output", outfile))

There are some packages that provide wrappers around pdftk:

  • the staplr package. Unfortunately, it is probably not too useful here because it does not allow specification of the files or their order in the output -- one can only specify the input and output directories. ** Update ** The current version of staplr now allows specification of the files as mentioned in the comments.

  • the animation package. The pdftk command that this package provides is a slightly simpler alternative than using system with pdftk directly. For concatenating it would be the following where we assume that the 3 lines marked ## above have already been run.

    library(animation)
    ani.options(pdftk = "/path/to/pdftk") # or if on path: ani.options(pdftk = "pdftk")
    pdftk(infiles, "cat", outfile, "")
    

    This link has an example of using the animation package with pdftk to burst pages.