Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added PDF read for macOS #1969

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions PIL/PdfImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@
from PIL import Image, ImageFile
from PIL._binary import i8
import io
import sys
if sys.platform == "darwin":
from PIL._util import isPath
import os
import tempfile
import subprocess

__version__ = "0.4"

Expand Down Expand Up @@ -247,9 +253,37 @@ def write(self, value):
if hasattr(fp, "flush"):
fp.flush()

def _accept(prefix):
return prefix[:5] == "%PDF-"

def _convertToPng(fp, filename):
fh, filepath = tempfile.mkstemp('.png')
os.close(fh)
if isPath(fp):
# filename
filename = fp
else:
# stream
fh, filename = tempfile.mkstemp('.pdf')
os.write(fh, fp.read())
os.close(fh)
with open(os.devnull, 'w') as fp:
subprocess.call(['sips', '-s', 'format', 'png', filename, '--out', filepath], stdout=fp)

if os.stat(filepath).st_size == 0:
raise SyntaxError("PDF file could not be converted")

im = Image.open(filepath)
im.load()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why we need this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, ok. Because we are deleting source file.

os.unlink(filepath)
return im

#
# --------------------------------------------------------------------

if sys.platform == "darwin":
Image.register_open("PDF", _convertToPng, _accept)

Image.register_save("PDF", _save)
Image.register_save_all("PDF", _save_all)

Expand Down