【问题标题】:Extract a region of a PDF page by coordinates通过坐标提取 PDF 页面的一个区域
【发布时间】:2012-02-17 16:51:15
【问题描述】:

我正在寻找一种工具来提取 1 页 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 库来执行此任务。

谢谢!

【问题讨论】:

    标签: python pdf command-line extract crop


    【解决方案1】:

    使用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)
    

    【讨论】:

      【解决方案2】:

      以下脚本在 http://snipplr.com/view.php?codeview&id=18924 将 pdf 的每一页拆分为 2。

      #!/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');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-16
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多