public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
            throws IOException
    {
        if (image.getType() != BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() != 1)
        {
            throw new IllegalArgumentException("Only 1-bit b/w images supported");
        }
        
        int height = image.getHeight();
        int width = image.getWidth();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try (MemoryCacheImageOutputStream mcios = new MemoryCacheImageOutputStream(bos))
        {
            for (int y = 0; y < height; ++y)
            {
                for (int x = 0; x < width; ++x)
                {
                    // flip bit to avoid having to set /BlackIs1
                    mcios.writeBits(~(image.getRGB(x, y) & 1), 1);
                }
                int bitOffset = mcios.getBitOffset();
                if (bitOffset != 0)
                {
                    mcios.writeBits(0, 8 - bitOffset);
                }
            }
            mcios.flush();
        }

        return prepareImageXObject(document, bos.toByteArray(), width, height, PDDeviceGray.INSTANCE);
    }
@Test
    void testCreateFromBufferedImage() throws IOException
    {
        String tiffG4Path = "src/test/resources/org/apache/pdfbox/pdmodel/graphics/image/ccittg4.tif";

        try (PDDocument document = new PDDocument())
        {
            BufferedImage bim = ImageIO.read(new File(tiffG4Path));
            PDImageXObject ximage3 = CCITTFactory.createFromImage(document, bim);
            validate(ximage3, 1, 344, 287, "tiff", PDDeviceGray.INSTANCE.getName());
            checkIdent(bim, ximage3.getOpaqueImage(null, 1));

            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);
            try (PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, false))
            {
                contentStream.drawImage(ximage3, 0, 0, ximage3.getWidth(), ximage3.getHeight());
            }

            document.save(TESTRESULTSDIR + "/singletifffrombi.pdf");
        }

        try (PDDocument document = Loader.loadPDF(new File(TESTRESULTSDIR, "singletifffrombi.pdf")))
        {
            assertEquals(1, document.getNumberOfPages());
        }  
    }