簡體   English   中英

如何使用perl(CAM :: PDF,PDF :: API2)轉換PDF頁面?

[英]How to shift PDF page using perl (CAM::PDF, PDF::API2)?

我有一個PDF文檔,需要將頁面右移幾英寸。 即喜歡在頁面的左側放置邊距。

CAM :: PDF或PDF :: API2都可以嗎? 還是有經驗的人?

謝謝。

我是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數據結構。

這是我在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');

如果遇到內容截斷的問題,則可能還需要獲取並設置cropboxbleedboxtrimboxartbox一項或多項,但這在大多數情況下應該可行。

您也可以使用Ghostscript做到這一點。 我將為您提供一些適用於Windows的示例命令(使用Unix時,只需將gswin32c.exe替換為gs ):

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(使用-c后需要-f )。

/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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM