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

Mar*_*k K 69 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.

Nor*_*Cat 123

您还可以使用pdfkit:

用法

import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
Run Code Online (Sandbox Code Playgroud)

安装

苹果系统: brew install Caskroom/cask/wkhtmltopdf

于Debian/Ubuntu: apt-get install wkhtmltopdf

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

  • pdfkit 依赖于非 python 包 wkhtmltopdf,而后者又需要一个正在运行的 X 服务器。因此,虽然在某些环境中很好,但这并不是在 python 中通常有效的答案。 (13认同)
  • PDFKit 需要一个正在运行的 X 服务器(或“虚拟”X 服务器)。:( 请参见此处:https://github.com/JazzCore/python-pdfkit/wiki/Using-wkhtmltopdf-without-X-server (3认同)
  • 这个包似乎不再维护了...... https://github.com/JazzCore/python-pdfkit/issues/242 (3认同)
  • 这比使用reportlab或使用打印驱动器进行转换更容易,更容易.非常感谢. (2认同)
  • 完美的 !!即使下载嵌入的图像,也不要费心使用它!你必须`apt-get install wkhtmltopdf` (2认同)

Joh*_*udd 30

WeasyPrint

pip install weasyprint  # No longer supports Python 2.x.

python
>>> pdf = weasyprint.HTML('http://www.google.com').write_pdf()
>>> len(pdf)
92059
>>> file('google.pdf', 'wb').write(pdf)
Run Code Online (Sandbox Code Playgroud)

  • 我想我会更喜欢这个项目,因为它的依赖项是python包而不是系统包.截至2018年1月,它似乎有更频繁的更新和更好的文档. (6认同)
  • 安装的东西太多了.我在libpango停了下来,去了pdfkit.令人讨厌的系统范围wkhtmltopdf,但weasyprint也需要一些系统范围的安装. (3认同)
  • 这不会转换 html 文件中的 `javascripts`。为此,您需要使用“pdfkit” (3认同)
  • 我可以提供文件路径而不是网址吗? (2认同)
  • 我认为该选项应该是“wb”,而不是“w”,因为“pdf”是一个“bytes”对象。 (2认同)
  • WeasyPrint 在大型 HTML 页面上运行缓慢。在我的情况下,是 50 秒 vs 7 秒 (pdfkit) (2认同)

Mar*_*k K 18

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

使用Python将文本添加到现有PDF

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.'
Run Code Online (Sandbox Code Playgroud)

  • xhtml2pdf 使用的“html5lib”存在一些问题。此解决方案解决了问题:https://github.com/xhtml2pdf/xhtml2pdf/issues/318 (2认同)

Mar*_*k K 12

这是一个正常工作:

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_())
Run Code Online (Sandbox Code Playgroud)


Jim*_*aul 11

这是一个使用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!"
Run Code Online (Sandbox Code Playgroud)


Jar*_*rad 10

根据这个答案:如何使用 Python 将网页转换为 PDF,建议使用pdfkit。您还必须安装wkhtmltopdf

如果您有本地.html文件,则需要使用以下命令:

pdfkit.from_file('test.html', 'out.pdf')
Run Code Online (Sandbox Code Playgroud)

但是,如果您尚未将 wkhtmltopdf 可执行文件添加到系统路径中,则会引发错误。这是让我绊倒的部分,我想分享。

在 Windows 上,打开您的环境变量并将它们添加到您的System variables> 中,Path如下所示。就我而言,这些 . exe从 exe 安装 wkhtmltopdf 后,文件位于此处:

C:\Program Files\wkhtmltopdf\bin

环境变量


Y.k*_*.kh 7

该解决方案使用 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('/sf/ask/1635135841/'))
    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_())
Run Code Online (Sandbox Code Playgroud)

  • 您还需要“pip install PyQtWebEngine”才能正常工作 (3认同)

Mar*_*k K 5

我尝试使用 pdfkit 回答@NorthCat。

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

安装可执行文件。然后写一行来指示 wkhtmltopdf 的位置,如下所示。(引用自无法使用 python PDFKIT 创建 pdf 错误:“找不到 wkhtmltopdf 可执行文件:”

import pdfkit


path_wkthmltopdf = "C:\\Folder\\where\\wkhtmltopdf.exe"
config = pdfkit.configuration(wkhtmltopdf = path_wkthmltopdf)

pdfkit.from_url("http://google.com", "out.pdf", configuration=config)
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您使用selenium和chromium,则不需要自己管理cookie,并且可以从chromium的打印中将pdf页面生成为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
import shutil

# Check for the existence of the chromedriver executable
chromedriver = shutil.which("chromedriver")
assert chromedriver is not None, "chromedriver not on PATH"

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()
Run Code Online (Sandbox Code Playgroud)