user3404729
user3404729

Reputation: 157

How to add .png images to pdf using Apache PDFBox

When I try to draw png images using pdfBox, the pages remain blank. Is there any way to insert png images using pdfBox?

public void createPDFFromImage( String inputFile, String image, String outputFile ) 
        throws IOException, COSVisitorException
{
    // the document
    PDDocument doc = null;
    try
    {
        doc = PDDocument.load( inputFile );

        //we will add the image to the first page.
        PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get( 0 );

        PDXObjectImage ximage = null;
        if( image.toLowerCase().endsWith( ".jpg" ) )
        {
            ximage = new PDJpeg(doc, new FileInputStream( image ) );
        }
        else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
        {
            ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
        }
        else
        {
            BufferedImage awtImage = ImageIO.read( new File( image ) );
            ximage = new PDPixelMap(doc, awtImage);
  //          throw new IOException( "Image type not supported:" + image );
        }
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
        contentStream.drawImage( ximage, 20, 20 );
        contentStream.close();
        doc.save( outputFile );
    }
    finally
    {
        if( doc != null )
        {
            doc.close();
        }
    }
}

Upvotes: 13

Views: 19377

Answers (2)

João Pedro Schmitt
João Pedro Schmitt

Reputation: 1488

This is how I have been doing:

final var imageBytes = getImageBytes();
final var outputStream = new ByteArrayOutputStream();

// Start a new PDF document
try (final var pdfDoc = new PDDocument()) {

    // Create a PDF image from my image byte array
    final var pdfImage = PDImageXObject.createFromByteArray(pdfDoc, imageBytes, "my-image");
    // Make sure the page resizes to the size of the image
    final var pdfPage = new PDPage(new PDRectangle(pdfImage.getWidth(), pdfImage.getHeight()));
    pdfDoc.addPage(pdfPage);
   
    // Start a image drawing stream
    try (final var contentStream = new PDPageContentStream(pdfDoc, pdfPage)) {
        // Draw image starting from position x=0, y=0 (top left corner)
        contentStream.drawImage(pdfImage, 0, 0);
    }
}
// Save PDF document into the output stream and return it
pdfDoc.save(outputStream);
return outputStream.toByteArray();

Upvotes: 0

Kai
Kai

Reputation: 891

There is a pretty nice utility class PDImageXObject to load Images from a java.io.File. As far as I know, it works well with jpg and png files.

PDImageXObject pdImage = PDImageXObject.createFromFileByContent(imageFile, doc);
contentStream.drawImage(pdImage, 20f, 20f); 

Upvotes: 6

Related Questions