使用Python将文本添加到现有PDF [英] Add text to Existing PDF using Python

查看:171
本文介绍了使用Python将文本添加到现有PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Python向现有的PDF添加一些额外的文本,最好的方法是什么,我需要安装哪些额外的模块.

I need to add some extra text to an existing PDF using Python, what is the best way to go about this and what extra modules will I need to install.

注意:理想情况下,我希望能够在Windows和Linux上都可以运行此程序,但是一键运行仅Linux即可.

Note: Ideally I would like to be able to run this on both Windows and Linux, but at a push Linux only will do.

pyPDF ReportLab 看起来不错,但是没人允许我编辑现有的PDF,还有其他选择吗?

pyPDF and ReportLab look good but neither one will allow me to edit an existing PDF, are there any other options?

推荐答案

我知道这是一篇较旧的文章,但是我花了很长时间尝试寻找解决方案.我遇到了一个仅使用ReportLab和PyPDF的不错的人,所以我想分享一下:

I know this is an older post, but I spent a long time trying to find a solution. I came across a decent one using only ReportLab and PyPDF so I thought I'd share:

  1. 使用PdfFileReader()阅读PDF,我们将其称为 input
  2. 创建一个包含要使用ReportLab添加的文本的新pdf文件,并将其另存为字符串对象
  3. 使用PdfFileReader()读取字符串对象,我们将其称为 text
  4. 使用PdfFileWriter()创建一个新的PDF对象,我们将其称为 output
  5. 通过 input 进行迭代,并对要添加文本的每个页面应用.mergePage(*text*.getPage(0)),然后使用output.addPage()将修改后的页面添加到新文档中
  1. read your PDF using PdfFileReader(), we'll call this input
  2. create a new pdf containing your text to add using ReportLab, save this as a string object
  3. read the string object using PdfFileReader(), we'll call this text
  4. create a new PDF object using PdfFileWriter(), we'll call this output
  5. iterate through input and apply .mergePage(*text*.getPage(0)) for each page you want the text added to, then use output.addPage() to add the modified pages to a new document

这对简单的文本添加效果很好.请参阅PyPDF的示例以对文档加水印.

This works well for simple text additions. See PyPDF's sample for watermarking a document.

下面是一些代码,可以回答以下问题:

Here is some code to answer the question below:

packet = StringIO.StringIO()
can = canvas.Canvas(packet, pagesize=letter)
<do something with canvas>
can.save()
packet.seek(0)
input = PdfFileReader(packet)

您可以在此处将输入文件的页面与另一个文档合并.

From here you can merge the pages of the input file with another document.

这篇关于使用Python将文本添加到现有PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆