我有一个 PDF 文档,我需要将页面向右移动几英寸。即喜欢在页面的左侧放置一个边距。
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;打印 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(-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