用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.