How to preserve bookmarks when rearranging pages of a PDF file with tools like pdftk

pdfpdftk

I am using pdftk to rearrange pages of a pdf file with bookmarks/outlines, but after that, the output file lost the bookmarks of the original.

My command is pdftk in.pdf cat 1-22 43 23-42 44-end output out.pdf.

I was wondering how I could keep the bookmarks while rearranging pages?

Best Answer

Here is a working solution. However you will need to adjust it to fit your needs.

In my example i removed the first page of a PDF, and then i needed to update the bookmarks to point to the correct locations.

  1. remove page 1 from in.pdf:

    pdftk A=in.pdf cat A2-end output temp.pdf
    
  2. create a in.info file from in.pdf:

    pdftk in.pdf dump_data > in.info
    
  3. in.info needs to be corrected in my case, since i will remove a page.

    Thus, i need to decrease BookmarkPageNumber by one for the bookmarks to lead to the correct pages.

    php code:

    $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";
        }
    }
    
  4. create final out.pdf:

    pdftk temp.pdf update_info in2.info output out.pdf
    

tested working on debian using pdftk 2.01

Related Question