【问题标题】:Adding text over existing PDFs using reportlab使用 reportlab 在现有 PDF 上添加文本
【发布时间】:2011-02-12 06:10:18
【问题描述】:
我有兴趣以编程方式填写现有的 PDF 表单。我真正需要做的就是从用户输入中提取信息,然后将适当的文本放在适当位置的现有 PDF 上。我已经可以通过将同一张纸送入打印机两次来使用reportlab 做到这一点,但这真的让我很不爽。
在添加用户输入的文本之前,我很想亲自对每个现有 PDF 进行逆向工程并自己绘制每一行和每个字符,但我想看看是否有一种简单的方法来获取现有 PDF 并设置它作为一些额外文本的背景。我真的更喜欢使用 python,因为它是我唯一觉得舒服的语言。
我也意识到我可以只扫描文档本身并将生成的光栅图像用作背景,但我更喜欢矢量图的精度。
看起来像ReportLab has a commercial product with this functionality,而我正在寻找的特定功能就在其中(copyPages) - 但为非营利用途的单一、简单功能支付 4 位数产品似乎有点过头了。
【问题讨论】:
标签:
python
pdf
pdf-generation
reportlab
【解决方案1】:
如果 PDF 表单是真实的AcroForms,您可以使用iText 填写它们。我不知道除了iText(java,原始)和iTextSharp(c#)之外是否还有其他端口,但如果您不介意开源您的解决方案,它很容易使用和免费。你可以看看这个sample code或者(java sn-p):
String formFile = "/path/to/myform.pdf"
String newFile = "/path/to/output.pdf"
PdfReader reader = new PdfReader(formFile);
FileOutputStream outStream = new FileOutputStream(newFile);
PdfStamper stamper = new PdfStamper(reader, outStream);
AcroFields fields = stamper.getAcroFields();
// fill the form
fields.setField("name", "Shane");
fields.setField("url", "http://stackoverflow.com");
// PDF infos
HashMap<String, String> infoDoc = new HashMap<String, String>();
infoDoc.put("Title", "your title here");
infoDoc.put("Author", "JRE ;)");
stamper.setMoreInfo(infoDoc);
// Flatten the PDF & cleanup
stamper.setFormFlattening(true);
stamper.close();
reader.close();
outStream.close();
【解决方案3】:
如果您只想在预印纸上添加一些文本。
您可以将其扫描为 jpg,然后将此 jpg 作为背景。
请参考reportlab手册第15页,调用drawImage即可