首页 > 解决方案 > 使用 Pillow 和 img2pdf 将图像转换为 pdf

问题描述

我有一项任务需要我从图像上传(jpg 或 png)中获取数据,根据要求调整大小,然后将其转换为 pdf,然后存储在 s3 中。

  1. 该文件以 ByteIO 的形式出现
  2. Pillow有空,所以我可以用它调整图像大小
  3. 现在文件类型是class 'PIL.Image.Image',我不知道如何继续。
  4. 我在https://gitlab.mister-muffin.de/josch/img2pdfimg2pdf上找到了库,但是当我有 PIL 格式时我不知道如何使用它(使用?)tobytes()
  5. s3 上传也看起来像一个类似文件的对象,所以我不想在再次加载之前将其保存到临时文件中。在这种情况下我什至需要 img2pdf 吗?

我如何实现这个目标?

编辑:我尝试使用tobytes()并直接上传到 s3。上传成功。但是,当下载查看内容时,它显示一个空白页面。好像文件数据没有写入pdf文件

编辑2:实际上去了s3并检查存储的文件。当我下载并打开它时,它显示cannot be opened

编辑 3:我并没有真正的工作代码,因为我仍在试验可行的方法,但这里有一个要点

data = request.FILES['file'].file  # where the data is
im = Image.open(data)
(width, height) = (im.width // 2, im.height // 2)  # example action I wanna take with Pillow
data = im_resized.tobytes()
# potential step for using img2pdf here but I don't know how
# img2pdf.convert(data)  # this fails because "ImageOpenError: cannot read input image (not jpeg2000). PIL: error reading image: cannot identify image file <_io.BytesIO..."
# img2pdf.convert(im_resized)  # this also fails because "TypeError: Neither implements read() nor is str or bytes"
upload_to_s3(data)  # some function that utilizes boto3 to upload to s3

标签: pythonpython-imaging-libraryimg2pdf

解决方案


推荐阅读