简体   繁体   English

使用python替换pdf文件中的页脚文本

[英]Replace footer text in pdf file using python

I have a file similar to this .我有类似的文件, 这个

What I want to do is replace the footer of the page with my own footer.我想要做的是用我自己的页脚替换页面的页脚。 What would be the best way to do this?什么是最好的方法来做到这一点? Can I crop the footer part (fixed size from bottom) and merge my own created footer with every page?我可以裁剪页脚部分(从底部开始固定大小)并将我自己创建的页脚与每个页面合并吗? Or is there a library available that could automatically extract footer from the page?或者是否有可用的库可以自动从页面中提取页脚? I don't have much experience in this regard.我在这方面没有太多经验。 I have tried some libraries including pypdf2 and reportlab but I was not able to find any help regarding footer extraction.我尝试了一些库,包括 pypdf2 和 reportlab,但我找不到有关页脚提取的任何帮助。

Any help will be greatly appreciated.任何帮助将不胜感激。

This is a bit of hack solution, create an image with required footer text and then run this.这是一个黑客解决方案,创建一个带有所需页脚文本的图像,然后运行它。 Adjust the coordinates as required.根据需要调整坐标。

from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = io.BytesIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawImage('yourFooterImage.png', 0, 2, 800, 45)
can.save()

# move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(open("original.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = open("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()

Code taken from here: Add text to Existing PDF using Python取自此处的代码: 使用 Python 将文本添加到现有 PDF

My output:我的输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM