根据坐标提取PDF页面区域

6 投票
2 回答
6544 浏览
提问于 2025-04-17 10:58

我在寻找一个工具,可以从一页的PDF文件中提取出指定的矩形区域(通过坐标),然后生成一个只包含这个区域的1页PDF文件:

# in.pdf is a 1-page pdf file
extract file.pdf 0 0 100 100 > out.pdf
# out.pdf is now a 1-page pdf file with a page of size 100x100
# it contains the region (0, 0) to (100, 100) of file.pdf

我可以把PDF转换成图片,然后使用convert命令,但这样生成的PDF就不再是矢量格式了,这样是不行的(我希望能够放大查看)。

我理想中是希望能通过命令行工具或者Python库来完成这个任务。

谢谢!

2 个回答

6

使用 pyPdf 这个库,你可以这样做:

import sys
import pyPdf

def extract(in_file, coords, out_file):
    with open(in_file, 'rb') as infp:
        reader = pyPdf.PdfFileReader(infp)
        page = reader.getPage(0)
        writer = pyPdf.PdfFileWriter()
        page.mediaBox.lowerLeft = coords[:2]
        page.mediaBox.upperRight = coords[2:]
        # you could do the same for page.trimBox and page.cropBox
        writer.addPage(page)
        with open(out_file, 'wb') as outfp:
            writer.write(outfp)

if __name__ == '__main__':
    in_file = sys.argv[1]
    coords = [int(i) for i in sys.argv[2:6]]
    out_file = sys.argv[6]

    extract(in_file, coords, out_file)
3

下面这个脚本可以把一个PDF文件的每一页分成两页。

#!/usr/bin/env perl
use strict; use warnings;
use PDF::API2;

my $filename = shift;
my $oldpdf = PDF::API2->open($filename);
my $newpdf = PDF::API2->new;

for my $page_nb (1..$oldpdf->pages) {
  my ($page, @cropdata);

  $page = $newpdf->importpage($oldpdf, $page_nb);
  @cropdata = $page->get_mediabox;
  $cropdata[2] /= 2;
  $page->cropbox(@cropdata);
  $page->trimbox(@cropdata);
  $page->mediabox(@cropdata);

  $page = $newpdf->importpage($oldpdf, $page_nb);
  @cropdata = $page->get_mediabox;
  $cropdata[0] = $cropdata[2] / 2;
  $page->cropbox(@cropdata);
  $page->trimbox(@cropdata);
  $page->mediabox(@cropdata);
}

(my $newfilename = $filename) =~ s/(.*)\.(\w+)$/$1.clean.$2/;
$newpdf->saveas('destination_path/myfile.pdf');

撰写回答