如何用Python自动实现网页打印页转PDF下载?
乐谱打印页转PDF的Python实现与替代方案
一、用Selenium自动化Firefox生成PDF
既然Firefox能直接把这个打印页导出成PDF,用Selenium控制Firefox是最贴合需求的方案,还能轻松嵌入GUI的按钮点击逻辑里。
步骤与代码
- 先安装依赖:
pip install selenium,再下载对应系统版本的geckodriver,放到系统PATH或者指定路径。 - 核心代码:
from selenium import webdriver from selenium.webdriver.firefox.options import Options import time def save_print_page_to_pdf(url, save_path): # 配置Firefox的打印参数 options = Options() options.headless = True # 后台运行,不弹出浏览器窗口 firefox_profile = webdriver.FirefoxProfile() # 设置默认打印到文件,指定输出路径 firefox_profile.set_preference("print.print_to_file", True) firefox_profile.set_preference("print.print_to_filename", save_path) firefox_profile.set_preference("print.printer_Mozilla_Save_to_PDF.print_to_file", True) firefox_profile.set_preference("print.printer_Mozilla_Save_to_PDF.print_to_filename", save_path) firefox_profile.set_preference("print.always_print_silent", True) driver = webdriver.Firefox(firefox_profile=firefox_profile, options=options) driver.get(url) # 等待页面加载完成(根据页面复杂度调整时间) time.sleep(2) # 触发浏览器打印 driver.execute_script("window.print();") # 等待PDF生成完毕 time.sleep(3) driver.quit() # 调用示例 save_print_page_to_pdf("https://thesession.org/tunes/12124/12124?print=true", "my_sheet_music.pdf")
把这段代码绑定到GUI按钮的点击事件里即可,比如用Tkinter或PyQt的按钮,点击后触发函数执行。
二、HTML转PDF替代方案(无需浏览器自动化)
如果觉得浏览器自动化资源占用高,直接转HTML到PDF更轻量,以下两种方案适合嵌入GUI:
1. pdfkit + wkhtmltopdf
这是轻量的第三方工具组合,对常规打印页面支持不错。
- 先下载wkhtmltopdf(对应系统版本),放到PATH里或者指定路径;然后安装依赖:
pip install pdfkit - 代码示例:
import pdfkit def html_url_to_pdf(url, save_path): # 配置wkhtmltopdf路径(如果没在PATH里) config = pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe') # Windows示例 # 启用打印媒体类型,匹配页面的打印样式 pdfkit.from_url(url, save_path, configuration=config, options={ 'quiet': '', 'print-media-type': '' }) # 调用示例 html_url_to_pdf("https://thesession.org/tunes/12124/12124?print=true", "sheet_music.pdf")
优点:无需启动浏览器,资源占用低;缺点:对复杂CSS的支持不如原生浏览器,需测试页面样式是否正常。
2. PyQt QWebEngineView(适配PyQt GUI)
如果你的乐谱查看应用基于PyQt开发,这个方案最无缝,直接在Qt框架内完成加载和导出:
- 安装依赖:
pip install PyQt6 - 可嵌入GUI的代码示例:
from PyQt6.QtWidgets import QApplication from PyQt6.QtWebEngineWidgets import QWebEngineView from PyQt6.QtCore import QUrl import sys class PdfExporter(QWebEngineView): def __init__(self, target_url, output_path): super().__init__() self.output_path = output_path self.load(QUrl(target_url)) self.loadFinished.connect(self.export_pdf) def export_pdf(self, is_loaded): if not is_loaded: print("页面加载失败") QApplication.quit() return # 配置PDF打印参数 print_settings = self.page().printSettings() print_settings.setOutputFormat(self.page().PrintOutputFormat.PdfFormat) print_settings.setOutputFileName(self.output_path) # 执行打印导出 self.page().print(print_settings, self.on_export_done) def on_export_done(self, success): print(f"PDF导出{'成功' if success else '失败'}: {self.output_path}") QApplication.quit() def pyqt_export_pdf(url, save_path): app = QApplication(sys.argv) exporter = PdfExporter(url, save_path) sys.exit(app.exec()) # 调用示例 pyqt_export_pdf("https://thesession.org/tunes/12124/12124?print=true", "sheet_music.pdf")
优点:完全集成PyQt生态,无需额外工具,对现代CSS支持和浏览器一致;缺点:仅适用于PyQt框架开发的GUI。
内容的提问来源于stack exchange,提问作者Willem van Houten
相关产品推荐
相关产品推荐

