📌  相关文章
📜  使用Python截取屏幕截图并将其转换为 PDF

📅  最后修改于: 2022-05-13 01:55:00.696000             🧑  作者: Mango

使用Python截取屏幕截图并将其转换为 PDF

为了将屏幕截图转换为 PDF,首先可以使用PyAutoGUI ,它是Python的一个自动化库,可以控制鼠标、键盘并可以处理许多 GUI 控制任务。其次,对于转换,可以使用Python的PIL( Python Imaging Library) ,它提供了图像处理功能,支持多种文件格式及其转换。可用于转换的第二个库是img2pdf ,顾名思义,它提供了图像到 pdf 的无损和更快的转换。

安装

要安装库,请使用以下命令:

  • PyAutoGUI:
pip install PyAutoGUI
  • PIL( Python成像库):
pip install Pillow
  • img2pdf
pip install img2pdf

方法#1

在这种方法中,我们使用Python的 PIL 库。首先,截图是使用screenshot() Python的PyAutoGUI库的函数。之后,屏幕截图的输出被保存。 PIL 库的open() 方法用于打开图像,然后convert() 方法将图像转换为 RGB,然后以 .pdf 扩展名保存在给定路径中。或者,您还可以通过在 open() 方法中提供路径来提供屏幕截图/图像。

注意:使用r'是为了将字符串视为原始字符串。

执行:



Python3
import pyautogui
from PIL import Image
 
# Taking Screenshot
takeScreenshot = pyautogui.screenshot()
 
# The path of Screenshot and r' is used for specifying raw string
screenshotPath = r'C:\Users\Pranjal\Desktop\gfgarticle\PDF\screenshot.png'
 
# Saving the screenshot in the given Path
takeScreenshot.save(screenshotPath)
 
# Opening image
open_image = Image.open(screenshotPath)
convert_image = open_image.convert('RGB')
 
# Output Pdf Path
outputpdfPath = r'C:\Users\Pranjal\Desktop\gfgarticle\PDF\output.pdf'
 
# Saving the pdf
open_image.save(outputpdfPath)


Python3
import pyautogui
import img2pdf
 
# Taking Screenshot
takeScreenshot = pyautogui.screenshot()
 
# The path of Screenshot and r' is used for specifying raw string
screenshotPath = r'C:\Users\Pranjal\Desktop\gfgarticle\PDF\screenshot.png'
 
# Saving the screenshot in the given Path
takeScreenshot.save(screenshotPath)
 
# Opening Img file obj
ImgFile = open(screenshotPath, "rb")
 
# Opening the Pdf file obj
PdfFile = open("output.pdf", "wb")
 
# Converting Image File to PDF
PdfFile.write(img2pdf.convert(ImgFile))
 
# Closing Image File Object
ImgFile.close()
 
# Closing PDF File Object
PdfFile.close()


输出:

方法#2

在这种方法中,使用 img2pdf 库进行转换。首先,使用Python的PyAutoGUI库的screenshot()方法截取屏幕截图。使用open() 方法打开屏幕截图后,传递“rb”作为参数以打开二进制格式的文件。之后,使用open() 方法bt 传递“wb”参数(用于以二进制形式写入)打开pdf 输出文件。调用 write()函数,并将 img2pdf 的 convert() 方法与屏幕截图对象一起传递。最后,两个对象都被关闭,以便它们刷新所有未写入的信息。

该方法的主要优点是与 PIL 相比速度快,而且它也是小尺寸的无损转换。或者,您还可以通过在 open() 方法中提供路径来提供屏幕截图/图像。

注意:屏幕截图/图像不包含 alpha 通道,因为在 img2pdf 中没有将 RGBA 转换为 RGB 的方法可用。

执行:

蟒蛇3

import pyautogui
import img2pdf
 
# Taking Screenshot
takeScreenshot = pyautogui.screenshot()
 
# The path of Screenshot and r' is used for specifying raw string
screenshotPath = r'C:\Users\Pranjal\Desktop\gfgarticle\PDF\screenshot.png'
 
# Saving the screenshot in the given Path
takeScreenshot.save(screenshotPath)
 
# Opening Img file obj
ImgFile = open(screenshotPath, "rb")
 
# Opening the Pdf file obj
PdfFile = open("output.pdf", "wb")
 
# Converting Image File to PDF
PdfFile.write(img2pdf.convert(ImgFile))
 
# Closing Image File Object
ImgFile.close()
 
# Closing PDF File Object
PdfFile.close()

输出: