Reportlabを使用してPDFを作成しています。作成後にマージしたい2つのPDFを作成しています。Reportlabは、pycanvas (ソース)(基本的にはメモリ内の私のpdfファイル)をpythonファイルとして保存する方法を提供し、そのpythonファイルでメソッドdoIt(filename)を呼び出すと、pdfファイルが再作成されます。ソースコードベースで2つのPDFを組み合わせて、1つのマージ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)
これは主に、ソースをディスクに保存する必要がないことと、スレッド保存ではないことです。実行時に作成したファイルに名前を付けることはできますが、何をインポートすればよいかわかりません!?ファイルの保存を防ぐ方法がない場合、実行時に定義されるファイルの名前に基づいてインポートを定義する方法はありますか?
なぜ事前に1つのPDFを作成しないのかと疑問に思われるかもしれませんが、それらは異なるアプリケーションからのものであるため、これは不可能です。