【问题标题】:How can I cut a pdf and create galleries of photo in python如何在 python 中剪切 pdf 并创建照片库
【发布时间】:2021-07-26 17:51:35
【问题描述】:

我有一个带有图像的 pdf,如下所示,我想创建一个带有画廊的 pdf,而不是带有数字的整张照片,因此只包括具有相同尺寸的图像。enter image description here

【问题讨论】:

  • 嗯,好的,所以您想从 PDF 中撕下图像,然后创建一个画廊?
  • @MrMatthewKevinHutchins 是的,这也可以。我不知道该怎么做,所以我可能无法提出正确的问题。我只想在 y 和 x 轴上没有比例的图像
  • 哦,所以你想撕下图像然后裁剪它们以隐藏我看到的 x 和 y 轴,这并不难。而且图片大小都一样?
  • @MrMatthewKevinHutchins 是的,完全正确
  • 好的,抱歉耽误了我一点时间,开了一天车,希望对您有所帮助,代码需要根据您的裁剪方式进行调整

标签: python pdf photo-gallery


【解决方案1】:

首先将它安装到你的python中

pip install PyMuPDF Pillow

pip 安装 fpdf

在此之后,我们使用以下代码提取图像。

import fitz # PyMuPDF
import io
from PIL import Image
# file path you want to extract images from
file = "1710.05006.pdf"
# open the file
pdf_file = fitz.open(file)
# iterate over PDF pages
for page_index in range(len(pdf_file)):
  # get the page itself
  page = pdf_file[page_index]
  image_list = page.getImageList()
  # printing number of images found in this page
  if image_list:
    print(f"[+] Found a total of {len(image_list)} images in page {page_index}")
  else:
      print("[!] No images found on page", page_index)
  for image_index, img in enumerate(page.getImageList(), start=1):
    # get the XREF of the image
    xref = img[0]
    # extract the image bytes
    base_image = pdf_file.extractImage(xref)
    image_bytes = base_image["image"]
    # get the image extension
    image_ext = base_image["ext"]
    # load it to PIL
    image = Image.open(io.BytesIO(image_bytes))
    # save it to local disk
    image.save(open(f"image{page_index+1}_{image_index}.{image_ext}", "wb"))

之后我们需要裁剪图像

from PIL import Image
import os.path, sys

path = "C:\\Users\\xie\\Desktop\\tiff\\Bmp"
dirs = os.listdir(path)

def crop():
    for item in dirs:
        fullpath = os.path.join(path,item)         #corrected
         if os.path.isfile(fullpath):
            im = Image.open(fullpath)
             f, e = os.path.splitext(fullpath)
             imCrop = im.crop((30, 10, 1024, 1004)) #corrected
             imCrop.save(f + 'Cropped.bmp', "BMP", quality=100)

crop()

在此之后编译回 PDF

from fpdf import FPDF
pdf = FPDF()
dims = [
    (x, y,w,h),
    (x, y,w,h),
    (x, y,w,h),
    (x, y,w,h)
]

for image_type in set([i[0] for i in image_list]):
    imgs = list(filter(lambda x:image_type in x,image_list))
    pdf.add_page()
    for i,j in zip(imgs,dims):
        pdf.image(i,j[0],j[1],j[2],j[3])
pdf.output("yourfile.pdf", "F")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2016-10-04
    相关资源
    最近更新 更多