PdfImagePlugin.py 9.0 KB

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