Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用带有python的report lab将html文档转换为pdf_Python_Html_Pdf_Reportlab - Fatal编程技术网

如何使用带有python的report lab将html文档转换为pdf

如何使用带有python的report lab将html文档转换为pdf,python,html,pdf,reportlab,Python,Html,Pdf,Reportlab,我正在尝试使用report lab将我创建的html文档转换为pdf。html文档如下。我不确定如何做到这一点,我已经上网,似乎无法找到一个解决办法 html文档 <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Convert to Pdf</title> </head> <body> <

我正在尝试使用report lab将我创建的html文档转换为pdf。html文档如下。我不确定如何做到这一点,我已经上网,似乎无法找到一个解决办法

html文档

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Convert to Pdf</title>
</head>

<body>
 <h2>Convert to pdf</h2>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec at tempus massa. Quisque congue dui venenatis rutrum imperdiet. Nulla congue magna sit amet magna posuere, in elementum felis dapibus. Mauris maximus feugiat lorem, a bibendum orci fringilla a. Pellentesque rhoncus dignissim tempus. Aliquam semper convallis odio ut pharetra. Nunc bibendum neque at bibendum ornare. Curabitur lobortis odio ac turpis tincidunt, at venenatis nibh blandit. Integer id arcu maximus, blandit urna ut, tempor odio. Pellentesque tempus, mi a finibus pellentesque, ex magna lacinia elit, a semper nibh orci non nulla. Nunc felis metus, congue a odio vitae, porttitor pellentesque sem. Fusce vehicula tincidunt dolor at dictum. Integer cursus, risus quis finibus dapibus, nulla dolor dapibus massa, et luctus enim dui a nunc. Sed facilisis sapien at risus commodo, eget sollicitudin ex eleifend. Proin ipsum ipsum, condimentum in mauris vel, rutrum aliquam magna.

Aenean ac odio ante. Proin eget urna est. Fusce at dui dignissim, tincidunt magna eget, dictum nisl. Donec enim ipsum, feugiat a tristique vitae, suscipit non risus. Pellentesque libero leo, pellentesque ut neque ut, pharetra volutpat ex. Pellentesque purus neque, varius eu dolor eu, placerat ullamcorper velit. Etiam volutpat blandit tortor non pellentesque. Donec ac risus lacus. Pellentesque sagittis vitae odio quis vulputate. Praesent efficitur urna mollis, cursus tellus euismod, pulvinar sem. Morbi maximus orci nisi. Fusce tempor condimentum lacus nec pulvinar. Aenean tristique eu nibh vitae facilisis.

</p>
</body>
</html>

转换为Pdf
转换为pdf
Lorem ipsum dolor sit amet,是一位杰出的献身者。坦普斯马萨的多尼克。奎斯克·康格酒后酒。在《猫的元素》中,大团圆坐着大团圆。毛里斯·马克西莫斯·费吉亚特·洛雷姆,一只比本杜姆虎鲸。佩朗茨克罗恩卡斯显贵坦普斯。阿利奎姆·森佩尔·康瓦利斯·奥迪奥·乌特·法雷特拉。比本杜姆奥纳雷的比本杜姆内克修道院。维尼纳提斯尼布朗迪特的奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥迪奥。整数id arcu maximus,blandit urna ut,临时odio。佩伦茨克时代,我是佩伦茨克终点站,前拉齐尼亚精英,一个半尼半兽人。马蒂斯·梅特斯、奥迪奥·维塔、佩伦特斯·波特。这句话的意思是说,这是一个很好的解释。整数游标、整数游标、整数游标、整数游标、整数游标和整数游标。在risus commodo的sapien设施,eget sollicitudin ex eleifend。益普生益普生,莫里斯维尔调味品,大茴香。
埃尼安·奥迪奥·安特。这是我的最爱。酒后驾车、酒后驾车、酒后驾车、酒后驾车。Donec enim ipsum,一个三重生命的封建者,无风险的继承者。佩朗茨克自由利奥,佩朗茨克,佩朗茨克,佩朗茨克,佩朗茨克,佩朗茨克,佩朗茨克。艾蒂安·帕特·布朗迪特·托托(Etiam Pat blandit tortor non-pellentesque)。Donec ac risus lacus。阳痿。本品有效成分为乌尔纳莫利斯、乌斯莫德、枕叶扫描电镜。莫比·马克西姆·奥西·尼西。这是一种临时调味品。这是一种健康的生活方式。


由于您已经知道如何使用ReportLab,我想这可以完成以下任务:

xhtml2pdf

使用ReportLab将HTML转换为PDF的库

示例代码取自Github:

# -*- coding: utf-8 -*-
# Copyright 2010 Dirk Holtwick, holtwick.it
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__version__ = "$Revision: 194 $"
__author__  = "$Author: holtwick $"
__date__    = "$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008) $"

import os
import sys
import cgi
import cStringIO
import logging

import xhtml2pdf.pisa as pisa

# Shortcut for dumping all logs to the screen
pisa.showLogging()

def dumpErrors(pdf, showLog=True):
    #if showLog and pdf.log:
    #    for mode, line, msg, code in pdf.log:
    #        print "%s in line %d: %s" % (mode, line, msg)
    #if pdf.warn:
    #    print "*** %d WARNINGS OCCURED" % pdf.warn
    if pdf.err:
        print "*** %d ERRORS OCCURED" % pdf.err

def testSimple(
    data="""Hello <b>World</b><br/><img src="img/test.jpg"/>""",
    dest="test.pdf"):

"""
Simple test showing how to create a PDF file from
PML Source String. Also shows errors and tries to start
the resulting PDF
"""

    pdf = pisa.CreatePDF(
        cStringIO.StringIO(data),
        file(dest, "wb")
        )

    if pdf.err:
        dumpErrors(pdf)
    else:
        pisa.startViewer(dest)

def testCGI(data="Hello <b>World</b>"):

    """
    This one shows, how to get the resulting PDF as a
    file object and then send it to STDOUT
    """

    result = cStringIO.StringIO()

    pdf = pisa.CreatePDF(
        cStringIO.StringIO(data),
        result
        )

    if pdf.err:
        print "Content-Type: text/plain"
        print
        dumpErrors(pdf)
    else:
        print "Content-Type: application/octet-stream"
        print
        sys.stdout.write(result.getvalue())

def testBackgroundAndImage(
    src="test-background.html",
    dest="test-background.pdf"):

    """
    Simple test showing how to create a PDF file from
    PML Source String. Also shows errors and tries to start
    the resulting PDF
    """

    pdf = pisa.CreatePDF(
        file(src, "r"),
        file(dest, "wb"),
        log_warn = 1,
        log_err = 1,
        path = os.path.join(os.getcwd(), src)
        )

    dumpErrors(pdf)
    if not pdf.err:
        pisa.startViewer(dest)

def testURL(
    url="http://www.htmltopdf.org",
    dest="test-website.pdf"):

    """
    Loading from an URL. We open a file like object for the URL by
    using 'urllib'. If there have to be loaded more data from the web,
    the pisaLinkLoader helper is passed as 'link_callback'. The
    pisaLinkLoader creates temporary files for everything it loads, because
    the Reportlab Toolkit needs real filenames for images and stuff. Then
    we also pass the url as 'path' for relative path calculations.
    """
    import urllib

    pdf = pisa.CreatePDF(
        urllib.urlopen(url),
        file(dest, "wb"),
        log_warn = 1,
        log_err = 1,
        path = url,
        link_callback = pisa.pisaLinkLoader(url).getFileName
        )

    dumpErrors(pdf)
    if not pdf.err:
        pisa.startViewer(dest)

if __name__=="__main__":

    testSimple()
    # testCGI()
    #testBackgroundAndImage()
    #testURL()
生成pdf的示例代码:

import pdfkit

pdfkit.from_url('http://stackoverflow.com', 'out.pdf')
pdfkit.from_file('test.html', 'out2.pdf')
pdfkit.from_string('Thanks for reading!', 'out3.pdf')

如果您使用django框架,您可以使用django easy pdf。我认为这是从Html生成PDF最省力的方法。以下是我的项目的模板和视图:

#Import the easy_pdf rendering
from easy_pdf.rendering import render_to_pdf_response

#Here's the detail view function
def detail_to_pdf(request,id):
    template = 'renderdetail.html'
    kucing = Kucing.objects.get(id = id)
    context = {'kucing' : kucing}
    return render_to_pdf_response(request,template,context)
模板为:

{%extends“base.html”%}
{%block extra_style%}
身体{
字体系列:“Helvetica”、“无衬线”;
颜色:#333333;
}
{%endblock%}
{%block content%}
配置文件:{{kucing.nama}}-ID:{{kucing.ID}

纳玛:{{kucing.Nama}}


Hp:{{kucing.Hp}


点:{{kucing.Poin}



|
{%endblock%}
虽然此链接可以回答问题,但最好在此处包含答案的基本部分,并提供链接供参考。如果链接页面发生更改,仅链接的答案可能无效。-你好,我根据你说的编辑了我的评论。对不起,如果我犯了一些错误,我是新来的。你能再读一遍我的awnser并给我其他建议吗?谢谢,我很想听听Strighted ReportLab的解决方案,很可能是通过转换例程。@fatih_dur:我不确定使用Strighted ReportLab是否可行。他们确实有一个例子,但RML是商业软件包的一部分。来自:“免费的ReportLab core API允许您直接使用Python脚本语言创建PDF文件;我们的商业RML2PDF报告标记语言产品允许您使用易于理解的XML指定打印文档并将其转换为PDF。”相关:,我在github上冲浪,发现了一些与PDF相关的内容。有一个名为txt2pdf的模块,如果您想要我的答案的完整web项目,您可以查看它。请与我联系,我会将其发送给您。警告:django easy pdf 0.1.1不支持django 3.0+,因为它删除了
django.util.six
#Import the easy_pdf rendering
from easy_pdf.rendering import render_to_pdf_response

#Here's the detail view function
def detail_to_pdf(request,id):
    template = 'renderdetail.html'
    kucing = Kucing.objects.get(id = id)
    context = {'kucing' : kucing}
    return render_to_pdf_response(request,template,context)