PdfImagePlugin.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. from __future__ import annotations
  22. import io
  23. import math
  24. import os
  25. import time
  26. from . import Image, ImageFile, ImageSequence, PdfParser, __version__, features
  27. #
  28. # --------------------------------------------------------------------
  29. # object ids:
  30. # 1. catalogue
  31. # 2. pages
  32. # 3. image
  33. # 4. page
  34. # 5. page contents
  35. def _save_all(im, fp, filename):
  36. _save(im, fp, filename, save_all=True)
  37. ##
  38. # (Internal) Image save plugin for the PDF format.
  39. def _write_image(im, filename, existing_pdf, image_refs):
  40. # FIXME: Should replace ASCIIHexDecode with RunLengthDecode
  41. # (packbits) or LZWDecode (tiff/lzw compression). Note that
  42. # PDF 1.2 also supports Flatedecode (zip compression).
  43. params = None
  44. decode = None
  45. #
  46. # Get image characteristics
  47. width, height = im.size
  48. dict_obj = {"BitsPerComponent": 8}
  49. if im.mode == "1":
  50. if features.check("libtiff"):
  51. filter = "CCITTFaxDecode"
  52. dict_obj["BitsPerComponent"] = 1
  53. params = PdfParser.PdfArray(
  54. [
  55. PdfParser.PdfDict(
  56. {
  57. "K": -1,
  58. "BlackIs1": True,
  59. "Columns": width,
  60. "Rows": height,
  61. }
  62. )
  63. ]
  64. )
  65. else:
  66. filter = "DCTDecode"
  67. dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray")
  68. procset = "ImageB" # grayscale
  69. elif im.mode == "L":
  70. filter = "DCTDecode"
  71. # params = f"<< /Predictor 15 /Columns {width-2} >>"
  72. dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray")
  73. procset = "ImageB" # grayscale
  74. elif im.mode == "LA":
  75. filter = "JPXDecode"
  76. # params = f"<< /Predictor 15 /Columns {width-2} >>"
  77. procset = "ImageB" # grayscale
  78. dict_obj["SMaskInData"] = 1
  79. elif im.mode == "P":
  80. filter = "ASCIIHexDecode"
  81. palette = im.getpalette()
  82. dict_obj["ColorSpace"] = [
  83. PdfParser.PdfName("Indexed"),
  84. PdfParser.PdfName("DeviceRGB"),
  85. len(palette) // 3 - 1,
  86. PdfParser.PdfBinary(palette),
  87. ]
  88. procset = "ImageI" # indexed color
  89. if "transparency" in im.info:
  90. smask = im.convert("LA").getchannel("A")
  91. smask.encoderinfo = {}
  92. image_ref = _write_image(smask, filename, existing_pdf, image_refs)[0]
  93. dict_obj["SMask"] = image_ref
  94. elif im.mode == "RGB":
  95. filter = "DCTDecode"
  96. dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceRGB")
  97. procset = "ImageC" # color images
  98. elif im.mode == "RGBA":
  99. filter = "JPXDecode"
  100. procset = "ImageC" # color images
  101. dict_obj["SMaskInData"] = 1
  102. elif im.mode == "CMYK":
  103. filter = "DCTDecode"
  104. dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceCMYK")
  105. procset = "ImageC" # color images
  106. decode = [1, 0, 1, 0, 1, 0, 1, 0]
  107. else:
  108. msg = f"cannot save mode {im.mode}"
  109. raise ValueError(msg)
  110. #
  111. # image
  112. op = io.BytesIO()
  113. if filter == "ASCIIHexDecode":
  114. ImageFile._save(im, op, [("hex", (0, 0) + im.size, 0, im.mode)])
  115. elif filter == "CCITTFaxDecode":
  116. im.save(
  117. op,
  118. "TIFF",
  119. compression="group4",
  120. # use a single strip
  121. strip_size=math.ceil(width / 8) * height,
  122. )
  123. elif filter == "DCTDecode":
  124. Image.SAVE["JPEG"](im, op, filename)
  125. elif filter == "JPXDecode":
  126. del dict_obj["BitsPerComponent"]
  127. Image.SAVE["JPEG2000"](im, op, filename)
  128. else:
  129. msg = f"unsupported PDF filter ({filter})"
  130. raise ValueError(msg)
  131. stream = op.getvalue()
  132. if filter == "CCITTFaxDecode":
  133. stream = stream[8:]
  134. filter = PdfParser.PdfArray([PdfParser.PdfName(filter)])
  135. else:
  136. filter = PdfParser.PdfName(filter)
  137. image_ref = image_refs.pop(0)
  138. existing_pdf.write_obj(
  139. image_ref,
  140. stream=stream,
  141. Type=PdfParser.PdfName("XObject"),
  142. Subtype=PdfParser.PdfName("Image"),
  143. Width=width, # * 72.0 / x_resolution,
  144. Height=height, # * 72.0 / y_resolution,
  145. Filter=filter,
  146. Decode=decode,
  147. DecodeParms=params,
  148. **dict_obj,
  149. )
  150. return image_ref, procset
  151. def _save(im, fp, filename, save_all=False):
  152. is_appending = im.encoderinfo.get("append", False)
  153. if is_appending:
  154. existing_pdf = PdfParser.PdfParser(f=fp, filename=filename, mode="r+b")
  155. else:
  156. existing_pdf = PdfParser.PdfParser(f=fp, filename=filename, mode="w+b")
  157. dpi = im.encoderinfo.get("dpi")
  158. if dpi:
  159. x_resolution = dpi[0]
  160. y_resolution = dpi[1]
  161. else:
  162. x_resolution = y_resolution = im.encoderinfo.get("resolution", 72.0)
  163. info = {
  164. "title": None
  165. if is_appending
  166. else os.path.splitext(os.path.basename(filename))[0],
  167. "author": None,
  168. "subject": None,
  169. "keywords": None,
  170. "creator": None,
  171. "producer": None,
  172. "creationDate": None if is_appending else time.gmtime(),
  173. "modDate": None if is_appending else time.gmtime(),
  174. }
  175. for k, default in info.items():
  176. v = im.encoderinfo.get(k) if k in im.encoderinfo else default
  177. if v:
  178. existing_pdf.info[k[0].upper() + k[1:]] = v
  179. #
  180. # make sure image data is available
  181. im.load()
  182. existing_pdf.start_writing()
  183. existing_pdf.write_header()
  184. existing_pdf.write_comment(f"created by Pillow {__version__} PDF driver")
  185. #
  186. # pages
  187. ims = [im]
  188. if save_all:
  189. append_images = im.encoderinfo.get("append_images", [])
  190. for append_im in append_images:
  191. append_im.encoderinfo = im.encoderinfo.copy()
  192. ims.append(append_im)
  193. number_of_pages = 0
  194. image_refs = []
  195. page_refs = []
  196. contents_refs = []
  197. for im in ims:
  198. im_number_of_pages = 1
  199. if save_all:
  200. try:
  201. im_number_of_pages = im.n_frames
  202. except AttributeError:
  203. # Image format does not have n_frames.
  204. # It is a single frame image
  205. pass
  206. number_of_pages += im_number_of_pages
  207. for i in range(im_number_of_pages):
  208. image_refs.append(existing_pdf.next_object_id(0))
  209. if im.mode == "P" and "transparency" in im.info:
  210. image_refs.append(existing_pdf.next_object_id(0))
  211. page_refs.append(existing_pdf.next_object_id(0))
  212. contents_refs.append(existing_pdf.next_object_id(0))
  213. existing_pdf.pages.append(page_refs[-1])
  214. #
  215. # catalog and list of pages
  216. existing_pdf.write_catalog()
  217. page_number = 0
  218. for im_sequence in ims:
  219. im_pages = ImageSequence.Iterator(im_sequence) if save_all else [im_sequence]
  220. for im in im_pages:
  221. image_ref, procset = _write_image(im, filename, existing_pdf, image_refs)
  222. #
  223. # page
  224. existing_pdf.write_page(
  225. page_refs[page_number],
  226. Resources=PdfParser.PdfDict(
  227. ProcSet=[PdfParser.PdfName("PDF"), PdfParser.PdfName(procset)],
  228. XObject=PdfParser.PdfDict(image=image_ref),
  229. ),
  230. MediaBox=[
  231. 0,
  232. 0,
  233. im.width * 72.0 / x_resolution,
  234. im.height * 72.0 / y_resolution,
  235. ],
  236. Contents=contents_refs[page_number],
  237. )
  238. #
  239. # page contents
  240. page_contents = b"q %f 0 0 %f 0 0 cm /image Do Q\n" % (
  241. im.width * 72.0 / x_resolution,
  242. im.height * 72.0 / y_resolution,
  243. )
  244. existing_pdf.write_obj(contents_refs[page_number], stream=page_contents)
  245. page_number += 1
  246. #
  247. # trailer
  248. existing_pdf.write_xref_and_trailer()
  249. if hasattr(fp, "flush"):
  250. fp.flush()
  251. existing_pdf.close()
  252. #
  253. # --------------------------------------------------------------------
  254. Image.register_save("PDF", _save)
  255. Image.register_save_all("PDF", _save_all)
  256. Image.register_extension("PDF", ".pdf")
  257. Image.register_mime("PDF", "application/pdf")