2017-07-21 26 views
2

我想將我創建的html文檔轉換爲使用報表實驗室的pdf。下面是html文檔。我不確定如何做到這一點,我已經在網上查找,似乎找不到解決方案。如何將html文檔轉換爲pdf使用報表實驗室python

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> 
+0

我很想聽聽關於ReportLab的嚴格解決方案,最有可能是使用轉換例程。 –

回答

1

正如你已經知道如何使用ReportLab的,我想這會做的工作: https://github.com/xhtml2pdf/xhtml2pdf

xhtml2pdf

一種用於將HTML成庫PDF使用ReportLab

示例代碼從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() 

或者你可以使用pdfkit

https://pypi.python.org/pypi/pdfkit

使用它之前,你需要安裝一些東西:

pip install pdfkit 
sudo apt-get install wkhtmltopdf 

示例代碼生成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') 
+0

雖然此鏈接可能回答問題,但最好在此處包含答案的基本部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/16784445) –

+0

你好, 我根據你的評論編輯了我的評論。 對不起,如果我犯了一些錯誤,我在這裏有點新。 你能再次讀我的芒並給我其他建議嗎? 謝謝 – CyborgForever

0

如果你使用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 %} 
 
    <style type="text/css"> 
 
     body { 
 
      font-family: "Helvetica", "sans-serif"; 
 
      color: #333333; 
 
     } 
 
    </style> 
 
{% endblock %} 
 

 
{% block content %} 
 
    <div id="content"> 
 
     <div class="main"> 
 
      <h1>PROFILE : {{ kucing.nama }}- ID:{{ kucing.id }}</h1> 
 
      <img src="/media/{{ kucing.foto }}"><br> 
 
      <p>Nama : {{ kucing.nama }}</p><br> 
 
      <p>Hp : {{ kucing.hp}}</p><br> 
 
      <p>Poin : {{ kucing.poin }}</p><br> 
 
      <a href="{% url 'kucing_makan' kucing.id %}">Makan</a> 
 
      <a href="{% url 'kucing_berburu' kucing.id %}">Berburu</a> 
 
      <hr> 
 
      <h5><a href="{% url 'kucing_home' %}">Back To Home</a></h5>| 
 
      <h5><a href="{% url 'kucing_list' %}">See Another Kucing</a></h5> 
 
     </div> 
 
    </div> 
 
{% endblock %}

您也可以通過覆蓋PDFTemplateViews使用基於類的意見。你可以在Docs上看到更多。