繁体   English   中英

如何在不先将图像保存到磁盘的情况下将图像打印到 pdf in python

[英]How to print image to a pdf in python without saving image to disk first

我正在制作一个供我个人使用的抓取器,用于截取屏幕截图并将它们保存到 pdf。我正在使用 pyscreenshot 截取屏幕截图,这将返回一个 PIL 图像(准确地说是 PIL.PngImagePlugin.PngImageFile)。 我正在使用 FPDF 制作 pdf 并且可以使用图像方法将图像添加到 pdf。

问题是,这需要一个文件路径或一个 URL。据我所知,将很多东西保存到磁盘会导致磨损,所以理想情况下我想将图像直接从 PIL object 保存到 pdf 而不是保存图像第一。 我将截取大约 1500 张屏幕截图,这是不必要的担心吗?

如果有任何变化,我正在使用 Ubuntu。 以下是图像方法的文档: https://pyfpdf.readthedocs.io/en/latest/reference/image/index.html

这是我的代码的相关部分。

import pyscreenshot as ImageGrab
from fpdf import FPDF

def get_page_image():
    page_image = ImageGrab.grab(bbox = half_page_bbox)
    page_image.save("Test image 1.png")
    return image

half_page_bbox = (249, 1, 1672, 1028)

pdf = FPDF("P", "mm", "A4")
pdf.add_page()
page_image = get_page_image()
pdf.image("Test image 1.png", 10, 10, 100)
pdf.output("My pdf.pdf")

我曾尝试使用 io 将其保存在 memory 中,但这不起作用。 这是我的代码,后面是错误。

import io
tmpFile = io.BytesIO()
image.save(tmpFile, format='png')
tmpFile.seek(0)
pdf.image(tmpFile, 10, 10, 100)
in <module>
    pdf.image(tmpFile, 10, 10, 100)
  File "/home/henry/.local/lib/python3.8/site-packages/fpdf/fpdf.py", line 150, in wrapper
    return fn(self, *args, **kwargs)
  File "/home/henry/.local/lib/python3.8/site-packages/fpdf/fpdf.py", line 963, in image
    pos=name.rfind('.')
AttributeError: '_io.BytesIO' object has no attribute 'rfind'

您可以执行以下操作,请注意我使用的是fpdf2而不是fpdf

pip install fpdf2

import pyscreenshot as ImageGrab
from fpdf import FPDF

img = ImageGrab.grab()

pdf = FPDF("P", "mm", "A4")

pdf.add_page()

pdf.image(img, 10, 10, 100)

pdf.output('My pdf.pdf')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM