Created
January 29, 2012 00:12
-
-
Save mohayonao/1696373 to your computer and use it in GitHub Desktop.
pdfをzipに変換する (mac)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import os, sys, tempfile, zipfile | |
from CoreGraphics import * | |
def pdf2zip(pdf_path, zip_path=None, size=640, verbose=True): | |
"""PDFをZIPに変換する""" | |
if not pdf_path.endswith(".pdf"): | |
raise IOError("'%s' is not PDF file." % pdf_path) | |
elif not os.path.exists(pdf_path): | |
raise IOError("'%s is not exists.'" % pdf_path) | |
tmp_path = tempfile.mkstemp()[1] | |
if zip_path is None: | |
zip_path = pdf_path[:-4] + ".zip" | |
zip = zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) | |
pdf = CGPDFDocumentCreateWithProvider(CGDataProviderCreateWithFilename(pdf_path)) | |
pages = pdf.getNumberOfPages() | |
colorspace = CGColorSpaceCreateDeviceRGB() | |
color = CGFloatArray(5) | |
pdf_rect = pdf.getPage(1).getBoxRect(kCGPDFMediaBox) | |
width, height = pdf_rect.getWidth(), pdf_rect.getHeight() | |
if width > height: | |
width, height = size, height * (size / width) | |
else: | |
width, height = width * (size / height), size | |
width, height = int(width), int(height) | |
jpg_rect = CGRectMake(0, 0, width, height) | |
for i in xrange(pages): | |
if verbose: | |
sys.stdout.write("\r%3d%%: %s" % (i*100/pages, zip_path)) | |
sys.stdout.flush() | |
context = CGBitmapContextCreateWithColor(width, height, colorspace, color) | |
context.saveGState() | |
context.setInterpolationQuality(kCGInterpolationHigh) | |
context.drawPDFDocument(jpg_rect, pdf, i+1) | |
context.restoreGState() | |
context.writeToFile(tmp_path, kCGImageFormatJPEG) | |
zip.write(tmp_path, "%04d.jpg" % i) | |
zip.close() | |
if verbose: | |
sys.stdout.write("\r100%%: %s\n" % zip_path) | |
os.remove(tmp_path) | |
if __name__ == "__main__": | |
import getopt | |
opts, args = getopt.getopt(sys.argv[1:], "s:") | |
size = int(opts[0][1]) if opts else 640 | |
for filepath in args: | |
pdf2zip(filepath, size=size) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment