2010-04-09 97 views
2

我有一個PDF文檔,我需要將頁面右移幾英寸。即,在頁面的左側放置一個頁邊空白。如何使用perl(CAM :: PDF,PDF :: API2)來移動PDF頁面?

CAM :: PDF或PDF :: API2可以嗎? 或者有沒有人有過使用它的經驗?

謝謝。

+0

這聽起來像一個艱難的工作 – Mike 2010-04-09 04:41:36

+0

它可以通過設置邊距和HWMargin使用ghostscript來完成,但我想用Perl來完成,而不是通過系統調用外部命令。 – est 2010-04-10 00:59:44

回答

3

我是CAM::PDF的作者。下面的小程序將頁面內容右移100點。

use CAM::PDF; 
my $pdf = CAM::PDF->new('my.pdf'); 
my $page = $pdf->getPage(1); 
$page->{MediaBox}->{value}->[0]->{value} -= 100; 
$page->{MediaBox}->{value}->[2]->{value} -= 100; 
$pdf->cleanoutput('out.pdf'); 

我用「使用Data :: Dumper; print Dumper($ page);」提醒自己$ page數據結構。

1

您也可以使用Ghostscript。 (使用Unix的情況下,僅僅通過更換gsgswin32c.exe)我給你一些windows例子命令:

gswin32c.exe^
    -o input-shifted-pages-1-inch-to-left.pdf^
    -sDEVICE=pdfwrite^
    -c "<</PageOffset [-72 0]>> setpagedevice"^
    -f /path/to/input.pdf 
  1. -o:指定輸出文件。隱含地也使用-dNOPAUSE -dBATCH -dSAFER
  2. -sDEVICE=...:要求Ghostscript輸出PDF。
  3. -c <<...:在命令行上通過了PostScript代碼片段,使發生的頁面轉換
  4. -f ...:指定輸入PDF(-f使用-c後需要)。

/PageShift使用的單位是PostScript點。 72磅== 1英寸。值[-72 0]將72pt == 1in左移,並將0in移至上/下。現在你知道如何向右移動2英寸:

gswin32c^
    -o input-shifted-pages-2-inches-to-right.pdf^
    -sDEVICE=pdfwrite^
    -c "<</PageOffset [144 0]>> setpagedevice"^
    -f /path/to/input.pdf 

想要將0.5英寸移到底部,1英寸移到右邊?

gswin32c.exe^
    -o input-shifted-pages-1-inch-to-right-half-inch-down.pdf^
    -sDEVICE=pdfwrite^
    -c "<</PageOffset [72 -36]>> setpagedevice"^
    -f /path/to/input.pdf 
2

這是我會怎麼做它在PDF :: API2:

use PDF::API2; 

my $in = PDF::API2->open('/path/to/file.pdf'); 
my $out = PDF::API2->new(); 

# Choose your margin (72 = one inch) 
my $x_offset = 72; 
my $y_offset = 0; 

foreach my $page_num (1 .. $in->pages()) { 
    # Take the source page and import it as an XObject 
    my $xobject = $out->importPageIntoForm($in, $page_num); 

    # Add the XObject to the new PDF 
    my $page = $out->page(); 
    my $gfx = $page->gfx(); 
    $gfx->formimage($xobject, $x_offset, $y_offset); 
} 
$out->saveas('/path/to/new.pdf'); 

應該工作的另一種方法是調整對於媒體的座標(可能還有其他箱):

use PDF::API2; 

my $pdf = PDF::API2->open('/path/to/file.pdf'); 

# Choose your margin (72 = one inch) 
my $x_offset = 72; 
my $y_offset = 0; 

foreach my $page_num (1 .. $pdf->pages()) { 
    my $page = $pdf->openpage($page_num); 

    # Get the coordinates for the page corners 
    my ($llx, $lly, $urx, $ury) = $page->get_mediabox(); 

    # Add the margin by shifting the mediabox in the opposite direction 
    $llx -= $x_offset; 
    $lly -= $y_offset; 
    $urx -= $x_offset; 
    $ury -= $y_offset; 

    # Store the new coordinates for the page corners 
    $page->mediabox($llx, $lly, $urx, $ury); 
} 

$pdf->saveas('/path/to/new.pdf'); 

如果遇到內容切斷問題,您可能需要獲取並設置cropbox,bleedbox,trimboxartbox中的一個或多個爲好吧,但這應該在大多數情況下工作。

+0

我一直認爲PDF :: API2比我自己的模塊CAM :: PDF有更好的API。如果我有空閒的時間,我想將它們合併成一個超級PDF庫... – 2011-05-31 20:04:15

相關問題