栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

https://github.com/disflux/django-
mtr/blob/master/pdfgen/doc_overlay.py

要共享脚本,如下所示:

import timefrom pyPdf import PdfFileWriter, PdfFileReaderimport StringIOfrom reportlab.pdfgen import canvasfrom reportlab.lib.pagesizes import letterfrom xhtml2pdf import pisaimport 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 givenweb.load(QUrl(url))printer = QPrinter()#setting formatprinter.setPageSize(QPrinter.A4)printer.setOrientation(QPrinter.Landscape)printer.setOutputFormat(QPrinter.PdfFormat)#export file as c:tem_pdf.pdfprinter.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 generatedoutputPDF = PdfFileWriter()packet = StringIO.StringIO()# create a new PDF with Reportlabcan = canvas.Canvas(packet, pagesize=letter)can.setFont("Helvetica", 9)# Writting the new lineoknow = 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 bufferpacket.seek(0)new_pdf = PdfFileReader(packet)# read your existing PDFexisting_pdf = PdfFileReader(file(tem_pdf, "rb"))pages = existing_pdf.getNumPages()output = PdfFileWriter()# add the "watermark" (which is the new pdf) on the existing pagefor 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 fileoutputStream = file(final_file, "wb")output.write(outputStream)outputStream.close()print final_file, 'is ready.'


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/612069.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号