1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
|
#!/usr/bin/perl -- # -*- Perl -*-
# this needs some cleanup...
my $PSTOTEXT = "pstotext";
my $pdf = shift @ARGV;
my $index = "";
my $inindex = 0;
open (F, "$PSTOTEXT $pdf |");
while (<F>) {
if (/^<\/index/) {
$index .= $_;
$inindex = 0;
}
$inindex = 1 if /^<index/;
if ($inindex) {
$index .= $_ if /^\s*</;
}
}
my $cindex = "";
while ($index =~ /^(.*?)((<phrase role=\"pageno\">.*?<\/phrase>\s*)+)/s) {
$cindex .= $1;
$_ = $2;
$index = $'; # '
my @pages = m/<phrase role=\"pageno\">.*?<\/phrase>\s*/sg;
# Expand ranges
if ($#pages >= 0) {
my @mpages = ();
foreach my $page (@pages) {
my $pageno = &pageno($page);
if ($pageno =~ /^([0-9]+)[^0-9]([0-9]+)$/) { # funky -
for (my $count = $1; $count <= $2; $count++) {
push (@mpages, "<phrase role=\"$pageno\">$count</phrase>");
}
} else {
push (@mpages, $page);
}
}
@pages = sort rangesort @mpages;
}
# Remove duplicates...
if ($#pages > 0) {
my @mpages = ();
my $current = "";
foreach my $page (@pages) {
my $pageno = &pageno($page);
if ($pageno ne $current) {
push (@mpages, $page);
$current = $pageno;
}
}
@pages = @mpages;
}
# Collapse ranges...
if ($#pages > 1) {
my @cpages = ();
while (@pages) {
my $count = 0;
my $len = &rangelen($count, @pages);
if ($len <= 2) {
my $page = shift @pages;
push (@cpages, $page);
} else {
my $fpage = shift @pages;
my $lpage = "";
while ($len > 1) {
$lpage = shift @pages;
$len--;
}
my $fpno = &pageno($fpage);
my $lpno = &pageno($lpage);
$fpage =~ s/>$fpno</>${fpno}-$lpno</s;
push (@cpages, $fpage);
}
}
@pages = @cpages;
}
my $page = shift @pages;
$page =~ s/\s*$//s;
$cindex .= $page;
while (@pages) {
$page = shift @pages;
$page =~ s/\s*$//s;
$cindex .= ", $page";
}
}
$cindex .= $index;
print "$cindex\n";
sub pageno {
my $page = shift;
$page =~ s/^<phrase.*?>//;
$page =~ s/^<link.*?>//;
return $1 if $page =~ /^([^<>]+)/;
return "?";
}
sub rangesort {
my $apno = &pageno($a);
my $bpno = &pageno($b);
# Make sure roman pages come before arabic ones, otherwise sort them in order
return -1 if ($apno !~ /^\d+/ && $bpno =~ /^\d+/);
return 1 if ($apno =~ /^\d+/ && $bpno !~ /^\d+/);
return $apno <=> $bpno;
}
sub rangelen {
my $count = shift;
my @pages = @_;
my $len = 1;
my $inrange = 1;
my $current = &pageno($pages[$count]);
while ($count < $#pages && $inrange) {
$count++;
my $next = &pageno($pages[$count]);
if ($current + 1 eq $next) {
$current = $next;
$inrange = 1;
$len++;
} else {
$inrange = 0;
}
}
return $len;
}
|