原文链接:https://www.zhangshengrong.com/p/8AaYmpoGa2/
PyPDF2模块主要的功能是分割或合并PDF文件,裁剪或转换PDF文件中的页面。
0、安装PyPDF2的模块
1、常用的函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
import PyPDF2
reader = PyPDF2.PdfFileReader(open('linux.pdf', 'rb')) print(reader.getNumPages()) print(reader.isEncrypted) page = reader.getPage(4) print(page.extractText()) print(reader.getDocumentInfo())
|
2、读取PDF文件,取指定页数,写入到硬盘上的示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #!/usr/bin/env python # -*- coding: utf-8 -*-
import PyPDF2
reader = PyPDF2.PdfFileReader(open('linux.pdf', 'rb'))
output = PyPDF2.PdfFileWriter()
output.addPage(reader.getPage(1)) output.addPage(reader.getPage(4)) output.addPage(reader.getPage(5)) print(output.getNumPages()) # 获取写入页的总页数
output.encrypt('123456') outputStream = open('PyPDF2-output.pdf', 'wb') output.write(outputStream) outputStream.close()
|
3、读取PDF某一页,旋转180度后,写入到新的PDF文件的示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
import PyPDF2
reader = PyPDF2.PdfFileReader(open('linux.pdf', 'rb'))
page = reader.getPage(0) page.rotateClockwise(180)
writer = PyPDF2.PdfFileWriter() writer.addPage(page)
outputStream = open('rotate-page-test.pdf', 'wb') writer.write(outputStream) outputStream.close()
|
4、PDF增加水印的示例
注意:水印模板可以利用WORD文档写好文字,转为PDF即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
import PyPDF2
reader = PyPDF2.PdfFileReader(open('linux.pdf', 'rb'))
watermark = PyPDF2.PdfFileReader(open('水印模板.pdf', 'rb'))
writer = PyPDF2.PdfFileWriter()
for i in range(reader.getNumPages()): page = reader.getPage(i) page.mergePage(watermark.getPage(0)) writer.addPage(page)
outputStream = open('watermark-test-linux.pdf', 'wb') writer.write(outputStream) outputStream.close()
|
测试效果
5、合并多个指定的PDF文件的示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
from PyPDF2 import PdfFileMerger
merger = PdfFileMerger()
input1 = open('01PDF.pdf', 'rb') input2 = open('02PDF.pdf', 'rb') input3 = open('03PDF.pdf', 'rb')
merger.append(fileobj=input1, pages=(0, 3)) merger.merge(position=2, fileobj=input2, pages=(0, 1)) merger.append(fileobj=input3)
output = open('document-output.pdf', 'wb') merger.write(output) output.close()
|
6、批量合并指定目录的PDF文件的示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
import PyPDF2 import os import glob
def get_all_pdf_files(path): """获取指定目录的所有pdf文件名""" all_pdfs = glob.glob('{0}/*.pdf'.format(path)) all_pdfs.sort(key=str.lower) return all_pdfs
def main(): path = os.getcwd() all_pdfs = get_all_pdf_files(path) if not all_pdfs: raise SystemExit('没有可用的PDF类型文件')
merger = PyPDF2.PdfFileMerger()
first_obj = open(all_pdfs[0], 'rb') merger.append(first_obj)
file_objs = [] for pdf in all_pdfs[1:]: file_objs.append(open(pdf, 'rb'))
for file_obj in file_objs: reader = PyPDF2.PdfFileReader(file_obj) merger.append(fileobj=file_obj, pages=(1, reader.getNumPages()))
outputStream = open('merge-pdfs.pdf', 'wb') merger.write(outputStream) outputStream.close() for file_obj in file_objs: file_obj.close()
if __name__ == '__main__': main()
|