Export and import pdf bookmarks

2023-04-24
1 min read

It is sometimes useful to export and import the bookmarks of an existing pdf file to a new pdf file with smaller size. This can be easily done using pdftk. pdftk is available as GUI and commandline tools. In MacOS, it is better to use it in the terminal. After installation of pdftk, the bookmarks of one pdf file can be extracted from an existing pdf file and imported to a new pdf file using the following lines.

# export dump_data from the original file
pdftk originalFile.pdf dump_data output bookmark.txt
# import dump_data to the new file
pdftk newFile.pdf update_info bookmark.txt output newFileWithBookmark.pdf

Of course, it is also possible to export the bookmark information as a text file:

pdftk originalFile.pdf dump_data_utf8 | grep '^Bookmark' > bookmark.txt

After that, the bookmark can be added to the new file alternatively by the LaTeX package bookmark. The following shows a minimal example (see more explanations in Michael H. Goerz’s post.

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{pdfpages}
\usepackage[
  pdfpagelabels=true,
  pdftitle={A test pdf file},
  pdfauthor={Chunyu Ge},
]{hyperref}
\usepackage{bookmark}

\begin{document}

\pagenumbering{arabic}
\setcounter{page}{1}
\includepdf[pages=1-2]{originalFile.pdf}

\pagenumbering{roman}
\setcounter{page}{1}
\includepdf[pages=3-8]{originalFile.pdf}

\pagenumbering{arabic}
\setcounter{page}{1}
\includepdf[pages=9-]{originalFile.pdf}

\bookmark[page=1,level=0]{Title Page}
\bookmark[page=17,level=1]{Contents}
\bookmark[page=31,level=1]{Chapter 1}
\bookmark[page=31,level=2]{Section 1}
\end{document}