使用Python,Phantomjs/PyQt/Ghost将URL转换为PDF
问题描述:
我在从链接生成PDF时遇到了一个问题。我有一个https://example.com/export_html?parameter1=abc¶meter2=def,这个链接将生成所有内容的HTML文件,包括图表,表格&等使用Python,Phantomjs/PyQt/Ghost将URL转换为PDF
我试图提取从上面的URL,这些内容,并将其保存为PDF文件。但问题是,上面的链接需要至少5-7秒来加载其所有内容,加载所有内容后,我只能将它保存为PDF。
我试图time.sleep()函数加载PDF的所有内容,但没有与PyQt4的工作尝试一些东西与PyQt4的,但对我没有工作。
即使试图与Ghost.py,下面是我试过的代码:
from ghost import Ghost
from PySide.QtGui import QApplication, QImage, QPainter, QPrinter
#from Pyside import *
#import PySide
#from PyQt4.QtWebKitWidgets import *
class MyGhost(Ghost):
def capture_pdf(self):
printer = QPrinter(QPrinter.HighResolution)
printer.setResolution(300)
printer.setOutputFileName("QtPrinter.pdf")
printer.setPaperSize(QPrinter.A4)
printer.setOrientation(QPrinter.Landscape)
printer.setOutputFormat(QPrinter.PdfFormat)
painter = QPainter(printer)
self.main_frame.render(painter)
painter.end()
ghost = Ghost(viewport_size=(1280,960))
page, resources = ghost.open('https://www.google.co.in/search?q=ghost+py+save+as+pdf&oq=ghost&aqs=chrome.1.69i57j69i59j69i60l4.5364j0j1&sourceid=chrome&ie=UTF-8')
ghost.capture_pdf()
但上面的代码是不工作,因为属性的错误。有人能提出更好的解决方案/方法吗?
我完全停留在这个生成PDF的东西,我必须等待该链接加载5-7秒,然后将其另存为PDF文件。任何帮助深表感谢。
在此先感谢。
答
您可以使用pdfkit。这比使用幽灵简单得多。用pip install pdfkit
从pypi安装它。用法如下:
import pdfkit
pdfkit.from_url('https://www.google.co.in/search?q=ghost+py+save+as+pdf&oq=ghost&aqs=chrome.1.69i57j69i59j69i60l4.5364j0j1&sourceid=chrome&ie=UTF-8', 'out.pdf')
欲了解更多信息,检查出this。您还需要下载wkhtmltopdf可执行文件。
我也试过这个,但正如我在问题中所说的,该链接需要某个时间来加载其所有内容,否则如果我使用pdfkit将会生成一个空白PDF! –
哦。那么,你可以使用pyautogui来打开一个页面并点击另存为。 –
http://pyautogui.readthedocs.io/en/latest/ –