0

我正在使用 Reportlab 创建 PDF。我正在创建两个要在创建后合并的 PDF。Reportlab 提供了一种将 pycanvas (源代码)(基本上是我在内存中的 pdf 文件)保存为 python 文件的方法,并在该 python 文件上调用方法 doIt(filename) 将重新创建 pdf 文件。这很棒,因为您可以在源代码的基础上合并两个 PDF 并创建一个合并 pdf。

这样做是这样的:

from reportlab.pdfgen import canvas, pycanvas
#create your canvas
p = pycanvas.Canvas(buffer,pagesize=PAGESIZE)
#...instantiate your pdf...

# after that, close the PDF object cleanly.
p.showPage()
p.save()

#now create the string equivalent of your canvas
source_code_equiv = str(p)
source_code_equiv2 = str(p)

#merge the two files on str. basis
#not shown how it is exactly done, to make it more easy to read the source
#actually one just have to take the middle part of source_code_equiv2 and add it into source_code_equiv
final_pdf = source_code_equiv_part1 + source_code_equiv2_center_part + source_code_equiv_part2

#write the source-code equivalent of the pdf
open("n2.py","w").write(final_pdf)
from myproject import n2
p = n2.doIt(buffer)

# Get the value of the StringIO buffer and write it to the response.
pdf = buffer.getvalue()
buffer.close()
response.write(pdf)
return response  

这工作正常,但我想跳过将 n2.py 保存到磁盘的步骤。因此,我正在寻找一种方法来从 final_pdf 字符串实例化相应的 python 类并直接在源代码中使用它。这可能吗?

它应该像这样工作..

n2 = instantiate_python_class_from_source(final_pdf)
p = n2.doIt(buffer)

这样做的原因主要是真的不需要将源保存到磁盘,其次绝对不是线程保存。我可以在运行时命名创建的文件,但是我不知道要导入什么!?如果没有办法阻止文件保存,有没有办法根据运行时定义的文件名来定义导入!?

有人可能会问我为什么不提前创建一个 pdf,但这是不可能的,因为它们来自不同的应用程序。

4

2 回答 2

1

对于您想要的东西,这似乎还有很长的路要走。Reportlab 没有可以从中提取 PDF 文档的 Canvas 类吗?我不明白为什么这里应该涉及生成的 Python 源代码。

但是如果由于某种原因有必要,那么您可以使用 StringIO 将源“写入”到字符串,然后 exec 执行它:

from cStringIO import StringIO

source_code = StringIO()
source_code.write(final_pdf)
exec(source_code)
p = doIt(buffer)
于 2010-08-28T11:54:47.197 回答
0

好的,我想你可以使用提供标准解释器交互模式的代码模块。以下将执行函数 doIt。

import code
import string
coded_data = """
def doIt():
    print "XXXXX"
"""
script = coded_data + "\ndoIt()\n" 
co = code.compile_command(script, "<stdin>", "exec")
if co:
    exec co

让我知道,如果这有帮助。

于 2010-08-28T09:44:41.277 回答