def _from_pil_image(cls, *, pdf, page, name, image): # pragma: no cover """Insert a PIL image into a PDF (rudimentary) Args: pdf (pikepdf.Pdf): the PDF to attach the image to page (pikepdf.Object): the page to attach the image to name (str or pikepdf.Name): the name to set the image image (PIL.Image.Image): the image to insert """ data = image.tobytes() imstream = Stream(pdf, data) imstream.Type = Name('/XObject') imstream.Subtype = Name('/Image') if image.mode == 'RGB': imstream.ColorSpace = Name('/DeviceRGB') elif image.mode in ('1', 'L'): imstream.ColorSpace = Name('/DeviceGray') imstream.BitsPerComponent = 1 if image.mode == '1' else 8 imstream.Width = image.width imstream.Height = image.height page.Resources.XObject[name] = imstream return cls(imstream)
def test_image_roundtrip(outdir, w, h, pixeldata, cs, bpc): pdf = Pdf.new() image_data = pixeldata * (w * h) image = Stream(pdf, image_data) image.Type = Name('/XObject') image.Subtype = Name('/Image') image.ColorSpace = Name(cs) image.BitsPerComponent = bpc image.Width = w image.Height = h xobj = {'/Im1': image} resources = {'/XObject': xobj} mediabox = [0, 0, 100, 100] stream = b'q 100 0 0 100 0 0 cm /Im1 Do Q' contents = Stream(pdf, stream) page_dict = { '/Type': Name('/Page'), '/MediaBox': mediabox, '/Contents': contents, '/Resources': resources, } page = pdf.make_indirect(page_dict) pdf.pages.append(page) outfile = outdir / f'test{w}{h}{cs[1:]}{bpc}.pdf' pdf.save( outfile, compress_streams=False, stream_decode_level=StreamDecodeLevel.none ) with Pdf.open(outfile) as p2: pim = PdfImage(p2.pages[0].Resources.XObject['/Im1']) assert pim.bits_per_component == bpc assert pim.colorspace == cs assert pim.width == w assert pim.height == h if cs == '/DeviceRGB': assert pim.mode == 'RGB' elif cs == '/DeviceGray' and bpc == 8: assert pim.mode == 'L' elif cs == '/DeviceCMYK': assert pim.mode == 'CMYK' elif bpc == 1: assert pim.mode == '1' assert not pim.palette assert pim.filters == [] assert pim.read_bytes() == pixeldata outstream = BytesIO() pim.extract_to(stream=outstream) outstream.seek(0) im = Image.open(outstream) assert pim.mode == im.mode