用 Python 生成扁平化的 PDF [英] Generate flattened PDF with Python

查看:95
本文介绍了用 Python 生成扁平化的 PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从我的任何源 PDF 打印 PDF 时,文件大小会下降并删除表单中显示的文本框.简而言之,它将文件展平.这是我想要实现的行为.

When I print a PDF from any of my source PDFs, the file size drops and removes the text boxes presents in form. In short, it flattens the file. This is behavior I want to achieve.

以下代码使用另一个 PDF 作为源(我想要展平的那个)创建一个 PDF,它也编写了文本框表单.

The following code to create a PDF using another PDF as a source (the one I want to flatten), it writes the text boxes form as well.

我可以得到一个没有文本框的 PDF 吗,把它展平?就像 Adob​​e 在我将 PDF 打印为 PDF 时所做的那样.

Can I get a PDF without the text boxes, flatten it? Just like Adobe does when I print a PDF as a PDF.

我的其他代码看起来像这样减去一些东西:

My other code looks something like this minus some things:

import os
import StringIO
from pyPdf import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

directory = os.path.join(os.getcwd(), "source")  # dir we are interested in
fif = [f for f in os.listdir(directory) if f[-3:] == 'pdf'] # get the PDFs
for i in fif:
    packet = StringIO.StringIO()
    can = canvas.Canvas(packet, pagesize=letter)
    can.rotate(-90)
    can.save()

    packet.seek(0)
    new_pdf = PdfFileReader(packet)
    fname = os.path.join('source', i)
    existing_pdf = PdfFileReader(file(fname, "rb"))
    output = PdfFileWriter()
    nump = existing_pdf.getNumPages()
    page = existing_pdf.getPage(0)
    for l in range(nump):
        output.addPage(existing_pdf.getPage(l))
    page.mergePage(new_pdf.getPage(0))
    outputStream = file("out-"+i, "wb")
    output.write(outputStream)
    outputStream.close()
    print fName + " written as", i

总结:我有一个 pdf,我向其中添加了一个文本框,覆盖了信息并添加了新信息,然后我从该 pdf 打印了一个 pdf.文本框不再可编辑或移动.我想自动化这个过程,但我尝试的一切仍然允许该文本框可编辑.

Summing up: I have a pdf, I add a text box to it, covering up info and adding new info, and then I print a pdf from that pdf. The text box becomes not editable or moveable any longer. I wanted to automate that process but everything I tried still allowed that text box to be editable.

推荐答案

如果安装操作系统包是一个选项,那么你可以使用 pdftk 及其 python 包装器 pypdftk像这样:

If installing an OS package is an option, then you could use pdftk with its python wrapper pypdftk like this:

import pypdftk
pypdftk.fill_form('filled.pdf', out_file='flattened.pdf', flatten=True)

您还需要安装 pdftk 包,在 Ubuntu 上可以这样完成:

You would also need to install the pdftk package, which on Ubuntu could be done like this:

sudo apt-get install pdftk

pypdftk 库可以从 PyPI 下载:

The pypdftk library can by downloaded from PyPI:

pip install pypdftk

这篇关于用 Python 生成扁平化的 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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