简体   繁体   中英

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

I am making a scraper for my personal use that takes screenshots and saves them to a pdf. I am using pyscreenshot to take the screenshot and this returns a PIL image (PIL.PngImagePlugin.PngImageFile to be precise). I am using FPDF to make the pdf and can use the image method to add an image to the pdf.

The trouble is, this takes in either a file path or a URL. It is my understanding that saving many things to the disk will cause wear, so ideally I would like to save the image to the pdf straight from the PIL object instead of saving the image first. I'll be taking around 1500 screenshots, is this an unnecessary worry?

I am using Ubuntu if that changes anything. Here are the docs for the image method: https://pyfpdf.readthedocs.io/en/latest/reference/image/index.html

Here are the relevant parts of my code.

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")

I have tried using io to save it in memory, but this isn't working. Here is my code followed by the error.

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'

You can do the following, note that I'm using fpdf2 instead of 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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