用Python合并奇偶页面的pdf文件 | merge odd and even pages pdf files using Python

最近入手了一打印机+扫描仪器,能双面打印确不能双面扫描。如果是两面打印的文档就只能分单双页面扫描。扫描完了需要合并。这个需要特殊的软件。网上找不到信得过的,干脆google一下用python自己写一个小工具来做这事。参考了这篇文章,改写后代码如下:

import itertools as itt
import sys

import PyPDF2 as PDF

import argparse


def main():

    parser = argparse.ArgumentParser(description='merge odd and even number pdf')
    parser.add_argument('--odd', '-o', dest='odd', required=True, type=str)
    parser.add_argument('--even', '-e', dest='even', required=True, type=str)
    parser.add_argument('--output', dest='output', required=True)
    parser.add_argument('--even-reversed', '-er', dest='even_reversed', type=bool, default=False)
    args = parser.parse_args()
    
    pdf_out = PDF.PdfFileWriter()

    with open(args.odd, 'rb') as f_odd:
        with open(args.even, 'rb')  as f_even:
            pdf_odd = PDF.PdfFileReader(f_odd)
            pdf_even = PDF.PdfFileReader(f_even)

            for p in itt.chain.from_iterable(
                itt.zip_longest(
                    pdf_odd.pages,
                    reversed(pdf_even.pages) if args.even_reversed else pdf_even.pages,
                )
            ):
                if p:
                    pdf_out.addPage(p)

            with open(args.output, 'wb') as f_out:
                pdf_out.write(f_out)

    return 0


if __name__ == "__main__":
    sys.exit(main())

需要安装PyPDF2这个package来处理pdf:

pip install PyPDF2

Leave a Comment

Your email address will not be published.