#!/bin/perl # add bookmark to pdf, at most two levels use strict; use PDF::Reuse; use File::Basename; my ($oldfile, $toc, $gap) = @ARGV; my $newfile = basename($oldfile, '.pdf') . '_new.pdf'; our $lastpage = 0; sub insertbookmark(@){ my ($chapter, @section) = @_ or return; my %items = (text => $chapter->{text}, act => $chapter->{act} ); @items{'close', 'kids'} = (1, \@section) if @section; prBookmark(\%items); } sub valid($){ my $line = shift; my ($text, $page) = $line =~ /^(.+)\t(\d+)$/ or die $line, 'is ill formatted'; # ()have to escape $text =~ s/([()])/\\\1/g; warn $text, ' on page ', $page, ' must be wrong' if $page < $lastpage; $lastpage = $page; return ($text, $page); } prFile($newfile); prDoc($oldfile) or die; open my $fh, '<', $toc or die; my @section; while (<$fh>){ chomp; my $flag = s/^\t//;# at most one tab my ($text, $page) = valid $_; $page += ($gap - 1); my $bookmark = { text => $text, act => "$page, 40, 700"}; unless ($flag){ insertbookmark @section; @section = (); } push @section, $bookmark; } insertbookmark @section; prEnd();