PdfImagePlugin.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # PDF (Acrobat) file handling
  6. #
  7. # History:
  8. # 1996-07-16 fl Created
  9. # 1997-01-18 fl Fixed header
  10. # 2004-02-21 fl Fixes for 1/L/CMYK images, etc.
  11. # 2004-02-24 fl Fixes for 1 and P images.
  12. #
  13. # Copyright (c) 1997-2004 by Secret Labs AB. All rights reserved.
  14. # Copyright (c) 1996-1997 by Fredrik Lundh.
  15. #
  16. # See the README file for information on usage and redistribution.
  17. #
  18. ##
  19. # Image plugin for PDF images (output only).
  20. ##
  21. import io
  22. import os
  23. import time
  24. from . import Image, ImageFile, ImageSequence, PdfParser, __version__
  25. #
  26. # --------------------------------------------------------------------
  27. # object ids:
  28. # 1. catalogue
  29. # 2. pages
  30. # 3. image
  31. # 4. page
  32. # 5. page contents
  33. def _save_all(im, fp, filename):
  34. _save(im, fp, filename, save_all=True)
  35. ##
  36. # (Internal) Image save plugin for the PDF format.
  37. def _save(im, fp, filename, save_all=False):
  38. is_appending = im.encoderinfo.get("append", False)
  39. if is_appending:
  40. existing_pdf = PdfParser.PdfParser(f=fp, filename=filename, mode="r+b")
  41. else:
  42. existing_pdf = PdfParser.PdfParser(f=fp, filename=filename, mode="w+b")
  43. resolution = im.encoderinfo.get("resolution", 72.0)
  44. info = {
  45. "title": None
  46. if is_appending
  47. else os.path.splitext(os.path.basename(filename))[0],
  48. "author": None,
  49. "subject": None,
  50. "keywords": None,
  51. "creator": None,
  52. "producer": None,
  53. "creationDate": None if is_appending else time.gmtime(),
  54. "modDate": None if is_appending else time.gmtime(),
  55. }
  56. for k, default in info.items():
  57. v = im.encoderinfo.get(k) if k in im.encoderinfo else default
  58. if v:
  59. existing_pdf.info[k[0].upper() + k[1:]] = v
  60. #
  61. # make sure image data is available
  62. im.load()
  63. existing_pdf.start_writing()
  64. existing_pdf.write_header()
  65. existing_pdf.write_comment(f"created by Pillow {__version__} PDF driver")
  66. #
  67. # pages
  68. ims = [im]
  69. if save_all:
  70. append_images = im.encoderinfo.get("append_images", [])
  71. for append_im in append_images:
  72. append_im.encoderinfo = im.encoderinfo.copy()
  73. ims.append(append_im)
  74. numberOfPages = 0
  75. image_refs = []
  76. page_refs = []
  77. contents_refs = []
  78. for im in ims:
  79. im_numberOfPages = 1
  80. if save_all:
  81. try:
  82. im_numberOfPages = im.n_frames
  83. except AttributeError:
  84. # Image format does not have n_frames.
  85. # It is a single frame image
  86. pass
  87. numberOfPages += im_numberOfPages
  88. for i in range(im_numberOfPages):
  89. image_refs.append(existing_pdf.next_object_id(0))
  90. page_refs.append(existing_pdf.next_object_id(0))
  91. contents_refs.append(existing_pdf.next_object_id(0))
  92. existing_pdf.pages.append(page_refs[-1])
  93. #
  94. # catalog and list of pages
  95. existing_pdf.write_catalog()
  96. pageNumber = 0
  97. for imSequence in ims:
  98. im_pages = ImageSequence.Iterator(imSequence) if save_all else [imSequence]
  99. for im in im_pages:
  100. # FIXME: Should replace ASCIIHexDecode with RunLengthDecode
  101. # (packbits) or LZWDecode (tiff/lzw compression). Note that
  102. # PDF 1.2 also supports Flatedecode (zip compression).
  103. bits = 8
  104. params = None
  105. decode = None
  106. if im.mode == "1":
  107. filter = "DCTDecode"
  108. colorspace = PdfParser.PdfName("DeviceGray")
  109. procset = "ImageB" # grayscale
  110. bits = 1
  111. elif im.mode == "L":
  112. filter = "DCTDecode"
  113. # params = f"<< /Predictor 15 /Columns {width-2} >>"
  114. colorspace = PdfParser.PdfName("DeviceGray")
  115. procset = "ImageB" # grayscale
  116. elif im.mode == "P":
  117. filter = "ASCIIHexDecode"
  118. palette = im.im.getpalette("RGB")
  119. colorspace = [
  120. PdfParser.PdfName("Indexed"),
  121. PdfParser.PdfName("DeviceRGB"),
  122. 255,
  123. PdfParser.PdfBinary(palette),
  124. ]
  125. procset = "ImageI" # indexed color
  126. elif im.mode == "RGB":
  127. filter = "DCTDecode"
  128. colorspace = PdfParser.PdfName("DeviceRGB")
  129. procset = "ImageC" # color images
  130. elif im.mode == "CMYK":
  131. filter = "DCTDecode"
  132. colorspace = PdfParser.PdfName("DeviceCMYK")
  133. procset = "ImageC" # color images
  134. decode = [1, 0, 1, 0, 1, 0, 1, 0]
  135. else:
  136. raise ValueError(f"cannot save mode {im.mode}")
  137. #
  138. # image
  139. op = io.BytesIO()
  140. if filter == "ASCIIHexDecode":
  141. ImageFile._save(im, op, [("hex", (0, 0) + im.size, 0, im.mode)])
  142. elif filter == "DCTDecode":
  143. Image.SAVE["JPEG"](im, op, filename)
  144. elif filter == "FlateDecode":
  145. ImageFile._save(im, op, [("zip", (0, 0) + im.size, 0, im.mode)])
  146. elif filter == "RunLengthDecode":
  147. ImageFile._save(im, op, [("packbits", (0, 0) + im.size, 0, im.mode)])
  148. else:
  149. raise ValueError(f"unsupported PDF filter ({filter})")
  150. #
  151. # Get image characteristics
  152. width, height = im.size
  153. existing_pdf.write_obj(
  154. image_refs[pageNumber],
  155. stream=op.getvalue(),
  156. Type=PdfParser.PdfName("XObject"),
  157. Subtype=PdfParser.PdfName("Image"),
  158. Width=width, # * 72.0 / resolution,
  159. Height=height, # * 72.0 / resolution,
  160. Filter=PdfParser.PdfName(filter),
  161. BitsPerComponent=bits,
  162. Decode=decode,
  163. DecodeParams=params,
  164. ColorSpace=colorspace,
  165. )
  166. #
  167. # page
  168. existing_pdf.write_page(
  169. page_refs[pageNumber],
  170. Resources=PdfParser.PdfDict(
  171. ProcSet=[PdfParser.PdfName("PDF"), PdfParser.PdfName(procset)],
  172. XObject=PdfParser.PdfDict(image=image_refs[pageNumber]),
  173. ),
  174. MediaBox=[
  175. 0,
  176. 0,
  177. width * 72.0 / resolution,
  178. height * 72.0 / resolution,
  179. ],
  180. Contents=contents_refs[pageNumber],
  181. )
  182. #
  183. # page contents
  184. page_contents = b"q %f 0 0 %f 0 0 cm /image Do Q\n" % (
  185. width * 72.0 / resolution,
  186. height * 72.0 / resolution,
  187. )
  188. existing_pdf.write_obj(contents_refs[pageNumber], stream=page_contents)
  189. pageNumber += 1
  190. #
  191. # trailer
  192. existing_pdf.write_xref_and_trailer()
  193. if hasattr(fp, "flush"):
  194. fp.flush()
  195. existing_pdf.close()
  196. #
  197. # --------------------------------------------------------------------
  198. Image.register_save("PDF", _save)
  199. Image.register_save_all("PDF", _save_all)
  200. Image.register_extension("PDF", ".pdf")
  201. Image.register_mime("PDF", "application/pdf")