Skip to content

Instantly share code, notes, and snippets.

@hute37
Created June 15, 2020 15:38
Show Gist options
  • Save hute37/7d1850bcbc51102b66934c10e48e2b47 to your computer and use it in GitHub Desktop.
Save hute37/7d1850bcbc51102b66934c10e48e2b47 to your computer and use it in GitHub Desktop.
How to preserve bookmarks when rearranging pages of a PDF file with tools like pdftk?
#!/bin/sh
##
# from: https://unix.stackexchange.com/questions/17045/how-to-preserve-bookmarks-when-rearranging-pages-of-a-pdf-file-with-tools-like-p
#
pdftk A=in.pdf cat A2-end output temp.pdf
pdftk in.pdf dump_data > in.info
cat > ins.php <<EOF
<?php
$file = "in.info";
$data = file_get_contents($file);
foreach (explode("\n", $data) as $row) {
$tmp = explode(": ", $row);
if ($tmp[0] == "BookmarkPageNumber") {
if ($tmp[1] != "1") $tmp[1]--;
echo $tmp[0].": ".$tmp[1]."\n";
} else {
echo $row."\n";
}
}
?>
EOF
php ins.php > in2.info
grep -B3 'BookmarkPageNumber: 1$' in2.info
pdftk temp.pdf update_info in2.info output out.pdf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment