PyPdf:将每一页分成两部分,用空白填充 [英] PyPdf: split each page in two, pad with blank space

查看:120
本文介绍了PyPdf:将每一页分成两部分,用空白填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PDF文件(A4,纵向布局),我想将其每一页拆分成一半的高度.输出文档也应为A4和纵向布局,但是每页的下半部分必须为空白.

I have a PDF file (A4, portrait layout), each page of which I want to split in a half of height. The output document should also be A4 and portrait layout, but lower half of each page needs to be blank.

我看到了 https://stackoverflow.com/a/15743413/822789 ,但是不知道如何添加空白与mediaBox的空间.

I saw https://stackoverflow.com/a/15743413/822789 but did not understand how to add blank space with mediaBox.

推荐答案

我不太了解PyPDF2,但我是 unspread.py 示例,该示例将页面左右左右分开将小报页面下放到原始页面中.这是该示例的修改版本.此版本将顶部和底部拆分页面,并更改输出页面的大小,使其与输入页面匹配:

I don't really know PyPDF2 all that well, but I am the author of pdfrw and if I understand your question, pdfrw can certainly do what you want quite easily. I need to document it a bit better, but I had a preexisting unspread.py example that splits pages left and right, to chop down tabloid pages into the original pages. Here is a modified version of that example. This version will split pages top and bottom, and also change the size of the output page so that it matches the input page:

#!/usr/bin/env python

'''
usage:   splitv.py my.pdf

Creates splitv.my.pdf

This is similar to unspread.py, in that it creates
a new file that has twice the pages of the old file.

It is different in two ways:

1) It splits pages top and bottom rather than left and right
2) The destination pages are the same size as the source pages,
   and the output is placed at the top.
'''

import sys
import os

from pdfrw import PdfReader, PdfWriter, PageMerge


def splitpage(src):
    ''' Split a page into two (top and bottom)
    '''
    # Yield a result for each half of the page
    for y_pos in (0, 0.5):

        # Create a blank, unsized destination page.
        page = PageMerge()

        # add a portion of the source page to it as
        # a Form XObject.
        page.add(src, viewrect=(0, y_pos, 1, 0.5))

        # By default, the object we created will be
        # at coordinates (0, 0), which is the lower
        # left corner.  To move it up on the page
        # to the top, we simply use its height
        # (which is half the source page height) as
        # its y value.
        page[0].y = page[0].h

        # When we render the page, the media box will
        # encompass (0, 0) and all the objects we have
        # placed on the page, which means the output
        # page will be the same size as the input page.
        yield page.render()


inpfn, = sys.argv[1:]
outfn = 'splitv.' + os.path.basename(inpfn)
writer = PdfWriter()
for page in PdfReader(inpfn).pages:
    writer.addpages(splitpage(page))
writer.write(outfn)

这篇关于PyPdf:将每一页分成两部分,用空白填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆