leoric666 发表于 2020-12-1 13:32:36

python pdf模块

import PyPDF2
minutesFile = open('meetingminutes.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(minutesFile)
minutesFirstPage = pdfReader.getPage(0)
pdfWatermarkReader = PyPDF2.PdfFileReader(open('watermark.pdf', 'rb'))
minutesFirstPage.mergePage(pdfWatermarkReader.getPage(0))
pdfWriter = PyPDF2.PdfFileWriter()
pdfWriter.addPage(minutesFirstPage)

for pageNum in range(1, pdfReader.numPages):
    pageObj = pdfReader.getPage(pageNum)
    pdfWriter.addPage(pageObj)
resultPdfFile = open('watermarkedCover.pdf', 'wb')
pdfWriter.write(resultPdfFile)
print(minutesFile.close())
print(resultPdfFile.close())

请问大佬,这个文档生成只会对第一页添加水印,如果我想将每个页面都添加我该添加什么代码呀

2012277033 发表于 2020-12-1 14:21:33

从你们的描述和代码看,应该在for循环里面补充一句pageObj.mergePage(pdfWatermarkReader.getPage(0))

也就是变成

import PyPDF2
minutesFile = open('meetingminutes.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(minutesFile)
minutesFirstPage = pdfReader.getPage(0)
pdfWatermarkReader = PyPDF2.PdfFileReader(open('watermark.pdf', 'rb'))
minutesFirstPage.mergePage(pdfWatermarkReader.getPage(0))
pdfWriter = PyPDF2.PdfFileWriter()
pdfWriter.addPage(minutesFirstPage)

for pageNum in range(1, pdfReader.numPages):
    pageObj = pdfReader.getPage(pageNum)
    pageObj.mergePage(pdfWatermarkReader.getPage(0))
    pdfWriter.addPage(pageObj)
resultPdfFile = open('watermarkedCover.pdf', 'wb')
pdfWriter.write(resultPdfFile)
print(minutesFile.close())
print(resultPdfFile.close())

leoric666 发表于 2020-12-1 15:18:21

2012277033 发表于 2020-12-1 14:21
从你们的描述和代码看,应该在for循环里面补充一句pageObj.mergePage(pdfWatermarkReader.getPage(0))

...

太厉害了哥!!
页: [1]
查看完整版本: python pdf模块