簡體   English   中英

如何使用 Python 將網頁轉換為 PDF

[英]How to convert webpage into PDF by using Python

我正在尋找使用 Python 將網頁打印到本地文件 PDF 的解決方案。 一個好的解決方案是使用 Qt,在這里找到, https://bharatikunal.wordpress.com/2010/01/

一開始它不起作用,因為我在安裝 PyQt4 時遇到問題,因為它給出了錯誤消息,例如“ ImportError: No module named PyQt4.QtCore ”和“ ImportError: No module named PyQt4.QtCore ”。

這是因為 PyQt4 沒有正確安裝。 我曾經擁有位於 C:\Python27\Lib 的庫,但它不適用於 PyQt4。

In fact, it simply needs to download from http://www.riverbankcomputing.com/software/pyqt/download (mind the correct Python version you are using), and install it to C:\Python27 (my case). 而已。

現在腳本運行良好,所以我想分享它。 有關使用 Qprinter 的更多選項,請參閱http://qt-project.org/doc/qt-4.8/qprinter.html#Orientation-enum

您也可以使用pdfkit

用法

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

安裝

MacOS: brew install Caskroom/cask/wkhtmltopdf

Debian/Ubuntu: apt-get install wkhtmltopdf

Windows: choco install wkhtmltopdf

參見 MacOS/Ubuntu/其他操作系統的官方文檔: https : //github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf

打印

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

python
>>> import weasyprint
>>> pdf = weasyprint.HTML('http://www.google.com').write_pdf()
>>> len(pdf)
92059
>>> open('google.pdf', 'wb').write(pdf)

感謝以下帖子,我可以在生成的 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.'

這是一個工作正常的:

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_())

這是一個使用 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!"

根據這個答案:如何使用 Python 將網頁轉換為 PDF ,建議使用pdfkit 您還必須安裝wkhtmltopdf

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

pdfkit.from_file('test.html', 'out.pdf')

但是,如果您尚未將 wkhtmltopdf 可執行文件添加到系統路徑中,則會引發錯誤。 這是讓我絆倒的部分,我想分享。

在 Windows 上,打開您的環境變量並將它們添加到您的System variables > Path如下所示。 就我而言,這些 . 從 exe 安裝 wkhtmltopdf 后, exe文件位於此處:

C:\\Program Files\\wkhtmltopdf\\bin

環境變量

我嘗試使用 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)

此解決方案使用 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_())

如果你使用selenium和chromium,你不需要自己管理cookies,你可以從chrome的print生成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

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()

正如另一個答案所解釋的那樣; 如果您在本地有 .html 文件,則可以使用以下內容:

pdfkit.from_file('abc.html', 'abc.pdf')

此外,如果您的源 html 文件具有 img 標簽,則 src 應該是相對路徑,並且您必須包含此選項以允許本地文件訪問。

pdfkit.from_file('abc.html', 'abc.pdf',options={"enable-local-file-access": ""})

否則你可能會遇到以下錯誤

OSError: wkhtmltopdf 報錯: Exit with code 1 due to network error: ProtocolUnknownError

來源: https://github.com/wkhtmltopdf/wkhtmltopdf/issues/2660#issuecomment-663063752

pdfkit 錯誤:由於網絡錯誤,退出代碼 1:ProtocolUnknownError

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM