我正在编写一个用于编辑PDF文本的Python脚本。
我有这段Python代码,它允许我将文本添加到PDF文件的特定位置。
我有这段Python代码,它允许我将文本添加到PDF文件的特定位置。
import PyPDF2
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
import sys
packet = io.BytesIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
# Insert code into specific position
can.drawString(300, 115, "Hello world")
can.save()
#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PyPDF2.PdfFileReader(packet)
# read your existing PDF
existing_pdf = PyPDF2.PdfFileReader(open("original.pdf", "rb"))
num_pages = existing_pdf.numPages
output = PyPDF2.PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(num_pages-1) # get the last page of the original pdf
page.mergePage(new_pdf.getPage(0)) # merges my created text with my PDF.
x = existing_pdf.getNumPages()
#add all pages from original pdf into output pdf
for n in range(x):
output.addPage(existing_pdf.getPage(n))
# finally, write "output" to a real file
outputStream = open("output.pdf", "wb")
output.write(outputStream)
outputStream.close()
我的问题:我想用自定义文本替换原始PDF文件中特定位置的文本。写入空白字符的方法可能行得通,但我没有找到任何可以实现这一点的东西。
注:必须使用Python代码,因为我稍后需要将其部署为.exe文件,并且我只知道如何使用Python代码完成此操作。