繁体   English   中英

如何在python的比萨文件xhtml2pdf中包含html文件?

[英]How to include html file inside Pisa document xhtml2pdf with python?

我是使用python的xhtml2pdf的新手,用python以可读格式编写html代码有点麻烦。 我想知道如何在比萨文档中包含.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文件中,并包括在第三行中,例如:

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

我如何解决这个问题?

如果我对您的理解正确,那么您想要的可能是与上述代码名为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

但是,我相信如果将html放入一个名为myTemplate.html的html文件中会更好。 然后,您可以像这样读取文件:

template = open("myTemplate.html")
pdf = pisa.CreatePDF(template.read(), file(filename, "w"))
template.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM