August 31, 2026

R programming lesson #2: merging pdf files

Use R package "pdftools" to merge separate pdf into one pdf file. You will never need to use sketchy websites or pay for software to do this ever again! It's free and easy with R package pdftools.

1: Install R and RStudio Desktop software

See lesson #0 (how to get started) for details, but briefly this is what you want:

2: Create or download pdf files to use for this tutorial

2.1: Create a pdf file from Microsoft Office Word or Google Doc 

For example, convert "Additional file 1" from Gonzalez et al 2018 into a 3 page pdf file. 

You can use my examples or supply your own pdf files. You will need at least two pdf files. 

From Word:  File: Export: Create PDF/XPS Document: Create PDF/XPS

From Google Doc:  File: Download: PDF Document (.pdf)


2.2: Download a pdf file

For example, download "Additional file 2" from Gonzalez et al. 2024.

 

3: Install and load R package pdftools

In RStudio console window, type and run:

install.packages(c("utils", "pdftools"))

Your results may look like this:

R didn't re-install package utils because I already had it, but it did install package pdftools. This is fine.

 

Don't worry if you have a different R version or pdftools package version than me.


4: Merge specific pdf files (when you know the filenames)

Begin an R script so you know what you did. In RStudio, select File: New File: R Script

Save your R script, select File: Save As and save your code somewhere.

Script:

## Set your working directory. This is where R will place your final merged file:

setwd("C:/Drobox/data") 

## Make a character vector of file paths including file extensions 
## for the pdf files that you want to merge. 
## All file paths need FORWARD-facing slashes, not backwards slashes. 
## Replace example below with your own file paths inside the quotation marks:

all.files = c("C:/Dropbox/data/to-merge/example_title_page.pdf",
                                "C:/Dropbox/data/to-merge/13293_2018_165_MOESM1_ESM.pdf"
)
 

## Check that R can find your files. If any file returns FALSE, check the path above and try again until all paths return TRUE:

file.exists(all.files)

## Merge step

print("Merging...")
pdftools::pdf_combine(input = all.files, 
                      output = "merged_pdf_filename.pdf")

print("Done!")

Script notes:

You can add as many pdf files as you want. For example:

all.files = c("file1.pdf", "file2.pdf",
             "file3.pdf", "file4.pdf", "file5.pdf", 
             "otherfile.pdf", "lastfile.pdf", 
             "lastfile2FINAL.pdf"
)
 

Make sure that each file path ends in .pdf file extension and that the file path is complete enough that R can identify your files.

The file path can be relative to your working directory, for example just "filename.pdf" if "filename.pdf" is located inside your working directory, or "to-merge/filename.pdf" if your working directory contains a folder labeled "to-merge" and "filename.pdf" is inside that folder. If you are having problems and file.exists(all.files) is returning FALSE for some or all files, then try the full file paths.

All file paths should be inside quotation marks. 

No comma after the last file path in all.files=c(...) 

If you leave an extra comma, then R expects another item in the list and will give you an error.


5: Merge all pdf files in a specific directory (identify filenames automatically)

If you want to always merge the pdf files in a specific folder, number the filenames in the order that you want (add 1, 2, 3, etc in front of their filename) and run this script. [Download pre-written .R script file]

Script to copy/paste for Windows:

## Check you have the required tools, or install them
if (!require("utils")) install.packages("utils")
if (!require("pdftools")) install.packages("pdftools")

## Load the required tools
library(utils)
library(pdftools)



## Select directory manually with a popup window
cat("\n\nOpen popup and pick the folder where your files are located (ONLY the ones you want to merge). ",
    "\nMake sure they are listed in sortable alphanumerical order. For example: ",
    "\n'1_file.pdf', \n'2_whatevername.pdf', \n'3_othername.pdf'\n",
    "\nChoose folder with your files... (Check for popup window!)\n")
my_directory <- utils::choose.dir(
  caption = "Select folder containing pdf files to merge..."
)



## Apply directory change
setwd(my_directory)


## Get list of all files in the directory
all.files <- dir(my_directory)
all.files


## Now list just the pdf files (match ".pdf" at end of filename)
pdf.files <- grep("[.]pdf$", all.files, value=TRUE, ignore.case=TRUE)


## Exclude  file "merged_pdf.pdf"
pdf.files <- setdiff(pdf.files, "merged_pdf.pdf")


## List remaining pdf files
cat("\nThese are the pdf files found in this folder:\n")
print(pdf.files)



## Merge step
cat("\nMerging...")
pdftools::pdf_combine(input = pdf.files, 
                      output = "merged_pdf.pdf")


cat("\nYour merged file name is: merged_pdf.pdf")

 

Script notes:

  • If you are not on a Windows computer and the script above causes errors with choose.dir function, then replace that code block and manually type your directory. For example:
    my_directory = "C:/Dropbox/data/to-merge"  
  • When you copy/paste file paths from Windows, they usually give you backwards slashes like this:
     "C:\Dropbox\data\to-merge" 
    ...But R doesn't understand the backwards slashes. Change them all to forward slashes manually.
  • This code skips the file.exists step of Section 4 because we are automatically getting all file paths from the directory, so R will only identify files that exist. You can add file.exists but it's not necessary.
  • Function grep uses text matching to identify specific filename patterns. In future updates, I'll add more explanation and examples.
  • Function setdiff takes two character vectors and returns whatever is in vector1 that isn't found in vector2. Here, pdf.files is the first vector (multiple filepaths) and "merged_pdf.pdf" is the second vector (just one file path).
  • Function cat is like print with two main differences: you need to specify line breaks with \n and you can combine multiple parts, for example cat("\nYour merged file name is:", output.file) if you want to define output.file as a separate variable with the output filename, instead of just using "merged_pdf.pdf" everywhere.

 

 ---------------------------------------------------------------------------------------------------------

 ----- End tutorial first draft here.

----- Below are my notes for expanding the tutorial to split section 5 into two sections.  

---------------------------------------------------------------------------------------------------------

6: Merge only pdf files with a specific filename text pattern (identify filenames automatically) 

6.1: Introduction to the grep function

6.2: Combine dir and grep functions

6.3: Regular expressions to improve text matching

The term "regular expressions", or "regex" for short, refers to the programming language syntax used for matching text patterns. R uses regex syntax that comes from the perl programming language.

Read more about R and perl regex syntax:

For now, the most useful regex for you to know is:

^mypattern means that mypattern must match at the beginning.

mypattern$ means that mypattern must match at the end.

 

Read more about pdftools

  

No comments:

Post a Comment

R programming lesson #2: merging pdf files

Use R package "pdftools" to merge separate pdf into one pdf file. You will never need to use sketchy websites or pay for software ...