mybin

my ~/bin
git clone https://a3nm.net/git/mybin/
Log | Files | Refs | README

pdf-rect.pl (1299B)


      1 #!/usr/bin/env perl
      2 
      3 # TODO: use instead, e.g.:
      4 #   pdftocairo -pdf -x 50 -y 50 -W 640 -H 950 -paperw 640 -paperh 950 test.pdf test2.pdf
      5 
      6 # crop pdf pages to a rectangle
      7 # requires libpdf-api2-perl
      8 # see http://stackoverflow.com/a/8986981
      9 # usage: ./pdf-rect.pl INFILE OUTFILE X1 X2 Y1 Y2 NUMPAGES
     10 # crop to [X1,X2] times [Y1,Y2] of original page dimensions
     11 # process up to NUMPAGES (all pages if =0)
     12 
     13 use strict; use warnings;
     14 use PDF::API2;
     15 use POSIX;
     16 
     17 my $filename = shift;
     18 my $ofilename = shift;
     19 my $x1 = 1.*(shift);
     20 my $y1 = 1.*(shift);
     21 my $x2 = 1.*(shift);
     22 my $y2 = 1.*(shift);
     23 my $mypage = int(shift);
     24 my $oldpdf = PDF::API2->open($filename);
     25 my $newpdf = PDF::API2->new;
     26 my $limit;
     27 $limit = $oldpdf->pages if $mypage < 1;
     28 $limit = $mypage if $mypage > 0;
     29 for my $page_nb (1..($limit)) {
     30   my ($page, @cropdata);
     31   $page = $newpdf->importpage($oldpdf, $page_nb);
     32   @cropdata = $page->get_mediabox;
     33   print "$page_nb\n";
     34   print "$cropdata[0] $cropdata[1] $cropdata[2] $cropdata[3]\n";
     35   $cropdata[0] += $cropdata[2] * $x1;
     36   $cropdata[1] += $cropdata[3] * $y1;
     37   $cropdata[2] *= $x2;
     38   $cropdata[3] *= $y2;
     39   print "$cropdata[0] $cropdata[1] $cropdata[2] $cropdata[3]\n";
     40   $page->cropbox(@cropdata);
     41   $page->trimbox(@cropdata);
     42   $page->mediabox(@cropdata);
     43 }
     44 $newpdf->saveas($ofilename);
     45