我正在使用 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,但这是不可能的,因为它们来自不同的应用程序。