[英]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');
如果遇到内容截断的问题,则可能还需要获取并设置cropbox
, bleedbox
, trimbox
和artbox
一项或多项,但这在大多数情况下应该可行。
您也可以使用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
-o
:指定输出文件。 隐式还使用-dNOPAUSE -dBATCH -dSAFER
。 -sDEVICE=...
:要求Ghostscript输出PDF。 -c <<...
:在命令行上传递的PostScript代码段,以进行页面移位 -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.