您现在的位置是:首页 > 榴榴无忌

分享一段python语言,能实现Mac系统下将一个pdf文件批量导出所有图片

| 人围观 |

丰色2026-09-08 17:37:00

複製代码
  1. python3 << 'EOF'
  2. import Quartz, os
  3. path = os.path.abspath("1.pdf")
  4. url = Quartz.NSURL.fileURLWithPath_(path)
  5. doc = Quartz.PDFDocument.alloc().initWithURL_(url)
  6. doc.unlockWithPassword_("t66y.com")
  7. for i in range(doc.pageCount()):
  8.     page = doc.pageAtIndex_(i)
  9.     bounds = page.boundsForBox_(Quartz.kPDFDisplayBoxMediaBox)
  10.     w, h = int(bounds.size.width), int(bounds.size.height)
  11.    
  12.     cs = Quartz.CGColorSpaceCreateDeviceRGB()
  13.     ctx = Quartz.CGBitmapContextCreate(None, w, h, 8, 0, cs, Quartz.kCGImageAlphaNoneSkipLast)
  14.     Quartz.CGContextSetInterpolationQuality(ctx, Quartz.kCGInterpolationHigh)
  15.     page.drawWithBox_toContext_(Quartz.kPDFDisplayBoxMediaBox, ctx)
  16.     img = Quartz.CGBitmapContextCreateImage(ctx)
  17.    
  18.     out = os.path.abspath(f"_{i+1}.jpg")
  19.     dest = Quartz.CGImageDestinationCreateWithURL(
  20.         Quartz.NSURL.fileURLWithPath_(out), "public.jpeg", 1, None)
  21.     Quartz.CGImageDestinationAddImage(dest, img, None)
  22.     Quartz.CGImageDestinationFinalize(dest)
  23.     print(f"已导出: {out}")
  24. EOF
複製代码


使用说明:
1、1.pdf是文件名,可以带路径,默认就是当前目录下
2、doc.unlockWithPassword_("t66y.com"),如果文件有密码,修改t66y.com为文件加密密码
3、out = os.path.abspath(f"_{i+1}.jpg"),可以自定义导出文件名
4、必须安装了python3
5、将上面代码修改完整后,直接复制粘贴到当前目录的终端里执行即可
6、本代码仅支持Mac系统

随便看看