1

私は python を使用した xhtml2pdf の初心者です。python を使用して html コードを読み取り可能な形式で記述するのは、なんとなく面倒です。pisaドキュメントに.htmlファイルを含める方法を知りたいです.pdfファイルを作成する簡単なコードは次のとおりです。

from xhtml2pdf import pisa   
def main():
    filename = "simplePrint.pdf"    
    # generate content
    xhtml = "<h1 align='center'>Test print</h1>\n"
    xhtml += "<h2>This is printed from within a Python application</h2>\n"
    xhtml += "<p style=\"color:red;\">Coloured red using css</p>\n"          
    pdf = pisa.CreatePDF(xhtml, file(filename, "w"))
if __name__ == "__main__":
    main()

html のコードが大きすぎる場合は、別のモジュールを作成し、それを myHtml.html ファイルに配置して、最後の 3 行目に次のように含めます。

pdf = pisa.CreatePDF(myHtml.html, file(filename, "w"))

どうすればこの問題に到達できますか?

4

1 に答える 1

1

私があなたを正しく理解していれば、あなたが望むのはおそらく、上記のコードと同じディレクトリにある別のファイルで、次のmyHtml.pyように呼び出されます。

html = "<h1 align='center'>Test print</h1>\n"
html += "<h2>This is printed from within a Python application</h2>\n"
html += "<p style=\"color:red;\">Coloured red using css</p>\n"

そしてimport myHtml、最初に上記のコードで。

myTemplate.htmlただし、たとえば、htmlをhtmlファイルに入れると、より良いと思います。次に、次のようにファイルを読み取ることができます。

template = open("myTemplate.html")
pdf = pisa.CreatePDF(template.read(), file(filename, "w"))
template.close()
于 2014-02-23T17:21:21.387 に答える