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

141 投票
10 回答
329886 浏览
提问于 2025-04-18 04:42

我在找用Python把网页打印成本地PDF文件的方法。其中一个不错的解决方案是使用Qt,具体可以在这里找到,https://bharatikunal.wordpress.com/2010/01/

一开始这个方法没能成功,因为我在安装PyQt4的时候遇到了问题,出现了像'ImportError: No module named 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

10 个回答

14

这里有一个运行得很好的代码:

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

根据这个回答:如何使用Python将网页转换为PDF,建议使用pdfkit。你还需要安装wkhtmltopdf

如果你有一个本地的.html文件,那么你需要使用这个命令:

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

但是如果你没有把wkhtmltopdf的可执行文件添加到你的系统路径中,这个命令会报错。这是我遇到的问题,所以想和大家分享一下。

在Windows上,你需要打开环境变量,把它们添加到你的系统变量 > Path,就像下面这样。在我的情况下,这些.exe文件在我从exe安装wkhtmltopdf后,位置是:

C:\Program Files\wkhtmltopdf\bin

环境变量

75

WeasyPrint 是一个可以把网页内容转换成PDF文件的工具。

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

你还可以使用 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

25

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

撰写回答