如何使用Python将网页转换为PDF

时间:2014-04-29 08:10:41

标签: python pdf webpage qprinter

我正在寻找使用Python将网页打印成本地文件PDF的解决方案。一个好的解决方案是使用Qt,在这里找到https://bharatikunal.wordpress.com/2010/01/

由于我在安装PyQt4时出现问题,因此它没有起作用,因为它提供了错误消息,例如' ImportError:没有名为PyQt4.QtCore的模块'和' ImportError:没有名为PyQt4.QtCore的模块'。

这是因为PyQt4没有正确安装。 我以前的库位于C:\ Python27 \ Lib,但它不适用于PyQt4。

事实上,它只需要从http://www.riverbankcomputing.com/software/pyqt/download下载(请注意您正在使用的正确Python版本),并将其安装到C:\ Python27(我的情况)。那就是它。

现在脚本运行正常,所以我想分享它。有关使用Qprinter的更多选项,请参阅http://qt-project.org/doc/qt-4.8/qprinter.html#Orientation-enum

8 个答案:

答案 0 :(得分:110)

您也可以使用pdfkit

用法

import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')

安装

MacOS:brew install Caskroom/cask/wkhtmltopdf

Debian / Ubuntu:apt-get install wkhtmltopdf

请参阅MacOS / Ubuntu /其他操作系统的官方文档:https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf

答案 1 :(得分:22)

WeasyPrint

export PYTHONPATH=/test
python /test/b/b.py

答案 2 :(得分:17)

感谢以下帖子,我可以添加要打印的网页链接地址,并在生成的PDF上显示时间,无论它有多少页面。

Add text to Existing PDF using Python

https://github.com/disflux/django-mtr/blob/master/pdfgen/doc_overlay.py

分享脚本如下:

import time
from pyPdf import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from xhtml2pdf import pisa
import sys 
from PyQt4.QtCore import *
from PyQt4.QtGui import * 
from PyQt4.QtWebKit import * 

url = 'http://www.yahoo.com'
tem_pdf = "c:\\tem_pdf.pdf"
final_file = "c:\\younameit.pdf"

app = QApplication(sys.argv)
web = QWebView()
#Read the URL given
web.load(QUrl(url))
printer = QPrinter()
#setting format
printer.setPageSize(QPrinter.A4)
printer.setOrientation(QPrinter.Landscape)
printer.setOutputFormat(QPrinter.PdfFormat)
#export file as c:\tem_pdf.pdf
printer.setOutputFileName(tem_pdf)

def convertIt():
    web.print_(printer)
    QApplication.exit()

QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)

app.exec_()
sys.exit

# Below is to add on the weblink as text and present date&time on PDF generated

outputPDF = PdfFileWriter()
packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.setFont("Helvetica", 9)
# Writting the new line
oknow = time.strftime("%a, %d %b %Y %H:%M")
can.drawString(5, 2, url)
can.drawString(605, 2, oknow)
can.save()

#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file(tem_pdf, "rb"))
pages = existing_pdf.getNumPages()
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
for x in range(0,pages):
    page = existing_pdf.getPage(x)
    page.mergePage(new_pdf.getPage(0))
    output.addPage(page)
# finally, write "output" to a real file
outputStream = file(final_file, "wb")
output.write(outputStream)
outputStream.close()

print final_file, 'is ready.'

答案 3 :(得分:8)

这是一个正常的工作:

import sys 
from PyQt4.QtCore import *
from PyQt4.QtGui import * 
from PyQt4.QtWebKit import * 

app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://www.yahoo.com"))
printer = QPrinter()
printer.setPageSize(QPrinter.A4)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("fileOK.pdf")

def convertIt():
    web.print_(printer)
    print "Pdf generated"
    QApplication.exit()

QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)
sys.exit(app.exec_())

答案 4 :(得分:7)

这是使用QT的简单解决方案。我发现这是对StackOverFlow上另一个问题的答案的一部分。我在Windows上测试过它。

from PyQt4.QtGui import QTextDocument, QPrinter, QApplication

import sys
app = QApplication(sys.argv)

doc = QTextDocument()
location = "c://apython//Jim//html//notes.html"
html = open(location).read()
doc.setHtml(html)

printer = QPrinter()
printer.setOutputFileName("foo.pdf")
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setPageSize(QPrinter.A4);
printer.setPageMargins (15,15,15,15,QPrinter.Millimeter);

doc.print_(printer)
print "done!"

答案 5 :(得分:2)

此解决方案使用PyQt5 5.15.0版对我有效

import sys
from PyQt5 import QtWidgets, QtWebEngineWidgets
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QPageLayout, QPageSize
from PyQt5.QtWidgets import QApplication

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    loader = QtWebEngineWidgets.QWebEngineView()
    loader.setZoomFactor(1)
    layout = QPageLayout()
    layout.setPageSize(QPageSize(QPageSize.A4Extra))
    layout.setOrientation(QPageLayout.Portrait)
    loader.load(QUrl('https://stackoverflow.com/questions/23359083/how-to-convert-webpage-into-pdf-by-using-python'))
    loader.page().pdfPrintingFinished.connect(lambda *args: QApplication.exit())

    def emit_pdf(finished):
        loader.page().printToPdf("test.pdf", pageLayout=layout)

    loader.loadFinished.connect(emit_pdf)
    sys.exit(app.exec_())

答案 6 :(得分:1)

如果您使用硒和铬,则不需要自己管理cookie,并且可以从铬的印刷品生成pdf页面。 您可以参考这个项目来实现它。 https://github.com/maxvst/python-selenium-chrome-html-to-pdf-converter

修改后的基数> https://github.com/maxvst/python-selenium-chrome-html-to-pdf-converter/blob/master/sample/html_to_pdf_converter.py

import sys
import json, base64


def send_devtools(driver, cmd, params={}):
    resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
    url = driver.command_executor._url + resource
    body = json.dumps({'cmd': cmd, 'params': params})
    response = driver.command_executor._request('POST', url, body)
    return response.get('value')


def get_pdf_from_html(driver, url, print_options={}, output_file_path="example.pdf"):
    driver.get(url)

    calculated_print_options = {
        'landscape': False,
        'displayHeaderFooter': False,
        'printBackground': True,
        'preferCSSPageSize': True,
    }
    calculated_print_options.update(print_options)
    result = send_devtools(driver, "Page.printToPDF", calculated_print_options)
    data = base64.b64decode(result['data'])
    with open(output_file_path, "wb") as f:
        f.write(data)



# example
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

url = "https://stackoverflow.com/questions/23359083/how-to-convert-webpage-into-pdf-by-using-python#"
webdriver_options = Options()
webdriver_options.add_argument("--no-sandbox")
webdriver_options.add_argument('--headless')
webdriver_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(chromedriver, options=webdriver_options)
get_pdf_from_html(driver, url)
driver.quit()

答案 7 :(得分:0)

我使用pdfkit尝试了@NorthCat答案。

它需要安装wkhtmltopdf。可以从这里下载安装。 https://wkhtmltopdf.org/downloads.html

安装可执行文件。然后写一行以表明wkhtmltopdf的位置,如下所示。 (引用自Can't create pdf using python PDFKIT Error : " No wkhtmltopdf executable found:"

# some object with the class "tbl_impala"
query_object <- query %>% 
              collapse() %>% 
              .[2]

# actual query which can be passed to hive via R. 
sql_query <- query_object[[1]]$x %>% 
           as.character()

# create new table
new_query <- paste0("CREATE TABLE table2 AS ",sql_query) %>% 
           str_replace_all(pattern = "'",replacement = '"') # this cleans up the code so it works

# if you want text without characters like \n in there.
cat(sql_query)