这里提供一个打包好的剪切包,window环境打开即可运行

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

import os

import fitz

import glob

import requests

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'

#剪切pdf为图片

def CutPdf(pdfPath,savePath,pdfSavePath):

    try:

        doc = fitz.open(pdfPath) #pdf路径

        for pg in range(doc.pageCount):

            page = doc[pg]

            rotate = int(0)

            # 每个尺寸的缩放系数为2,这将为我们生成分辨率提高四倍的图像。

            zoom_x = 2.0

            zoom_y = 2.0

            trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)

            pm = page.getPixmap(matrix=trans, alpha=False)

            imagePath = savePath + '%s.png' % str(pg + 1)

            pm.writePNG(imagePath) #最终存储路径

            newpdfPath = pdfSavePath + '%s.pdf' % str(pg + 1)

            print("剪切一张图片:" + str(pg + 1))

            frompic2pdf(imagePath,pdfSavePath,newpdfPath)

            print("转换成功一张pdf:" + str(pg + 1))

    except Exception as e:

        print('CutPdf出现异常:' + str(e))

#图片转pdf

def frompic2pdf(img_path,pdfSavePath, pdf_path):

    # 使用glob读图

    for img in sorted(glob.glob(img_path)):

        if not os.path.exists(pdfSavePath):

             os.makedirs(pdfSavePath)

         

        # 打开空文档

        doc = fitz.open()

        # 打开指定图片

        imgdoc = fitz.open(img)

        # 使用图片创建单页的PDF

        pdfbytes = imgdoc.convertToPDF()

        imgpdf = fitz.open("pdf", pdfbytes)

        # 将当前页写入文档

        doc.insertPDF(imgpdf)

        # 保存为指定名称的PDF文件

        doc.save(pdf_path)

        # 关闭

        doc.close()

def main():

    pdfUrl = "cards"

    fileList = os.listdir(pdfUrl)

    index = 1

    for item in  fileList:

        print("开始裁剪" + item)

        url = pdfUrl + "/" + item

        foldStr = "images/" + item.split('.')[0]

        url2 = foldStr + "/" + item.split('.')[0]

        foldStr3 = "pdf/" + item.split('.')[0]

        url3 = foldStr3 + "/"

        if not os.path.exists(foldStr):

            os.makedirs(foldStr)

        CutPdf(url,url2,url3)

        print("完成裁剪")

        index+=1

if __name__ == "__main__":

    main()

知识补充

除了上文的方法,小编还为大家整理了其他Python裁剪pdf文件为图片的方法,希望对大家有所帮助

方法一:

剪裁PDF页面

在剪裁PDF页面之前,我们需要获取页面的尺寸,并计算剪裁区域的位置和大小。下面是剪裁PDF页面的代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

# 获取页面尺寸

page_width = page.mediaBox.getWidth()

page_height = page.mediaBox.getHeight()

# 定义剪裁区域的位置和大小

x = 100  # 起始点的x坐标

y = 100  # 起始点的y坐标

width = 200  # 剪裁区域的宽度

height = 300  # 剪裁区域的高度

# 剪裁PDF页面

page.trimBox.lowerLeft = (x, y)

page.trimBox.upperRight = (x + width, y + height)

page.cropBox.lowerLeft = (x, y)

page.cropBox.upperRight = (x + width, y + height)

代码解析:

  • 使用mediaBox属性获取页面的宽度和高度。
  • 定义剪裁区域的位置和大小,可以根据实际需求进行调整。
  • 使用trimBox属性设置剪裁后的页面的边界框。
  • 使用cropBox属性设置剪裁后的页面的裁剪框。

保存剪裁后的图片

最后,我们需要将剪裁后的页面保存为图片。这可以通过使用PyPDF2库和Pillow库来实现。下面是保存剪裁后的图片的代码:

1

2

3

4

5

6

7

from PIL import Image

# 将剪裁后的页面保存为图片

with open('output.jpg', 'wb') as image_file:

    page_data = page.extract_xobject().get('/Im0').getData()

    image = Image.open(io.BytesIO(page_data))

    image.save(image_file, 'JPEG')

首先,导入Pillow库中的Image模块,用于处理图像。

  • 使用extract_xobject()方法从剪裁后的页面中提取图像数据。
  • 使用get('/Im0')方法获取图像数据。
  • 使用getData()方法获取图像的二进制数据。
  • 使用Image.open()方法打开图像数据。
  • 使用save()方法保存图像数据为JPEG格式的图片。
  • 'output.jpg'为保存的图片路径,可以根据需要修改。

方法二:

python分割pdf

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

from PyPDF2 import PdfFileReader, PdfFileWriter

  

  

# PDF文件分割

def split_pdf(read_file, out_detail):

    try:

        fp_read_file = open(read_file, 'rb')

        pdf_input = PdfFileReader(fp_read_file)  # 将要分割的PDF内容格式话

        page_count = pdf_input.getNumPages()  # 获取PDF页数

        print(page_count)  # 打印页数

  

        with open(out_detail, 'r',True,'utf-8')as fp:

            # print(fp)

            txt = fp.readlines()

            # print(txt)

            for detail in txt:  # 打开分割标准文件

                # print(type(detail))

                pages, write_file = detail.split()  # 空格分组

               #  write_file, write_ext = os.path.splitext(write_file)  # 用于返回文件名和扩展名元组

                pdf_file = r'C:\Users\GZTSALFIEL\Desktop\excel问题文件\pdf\\'+f'{write_file}.pdf'

                # liststr=list(map(int, pages.split('-')))

                # print(type(liststr))

                start_page, end_page = list(map(int, pages.split('-')))  # 将字符串数组转换成整形数组

                start_page -= 1

                try:

                    print(f'开始分割{start_page}页-{end_page}页,保存为{pdf_file}......')

                    pdf_output = PdfFileWriter()  # 实例一个 PDF文件编写器

                    for i in range(start_page, end_page):

                        pdf_output.addPage(pdf_input.getPage(i))

                    with open(pdf_file, 'wb') as sub_fp:

                        pdf_output.write(sub_fp)

                    print(f'完成分割{start_page}页-{end_page}页,保存为{pdf_file}!')

                except IndexError:

                    print(f'分割页数超过了PDF的页数')

        # fp.close()

    except Exception as e:

        print(e)

    finally:

        fp_read_file.close()

  

  

  

# def main():

#     fire.Fire(split_pdf)

#

# if __name__ == '__main__':

#     main()

  

split_pdf(r'..\pdfdocement\myfile.pdf', 'consult.txt')

到此这篇关于Python实现快速将pdf文件剪切成多个图片的文章就介绍到这了

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐