Search code examples
javaimagepdfpngpdfbox

PDFBox v2 write PNG image to PDF file, getting empty file


I'm using PDFBox 2. Trying to write a PNG image file to new PDF file.

I saw there was already an answer that mention it was fixed on PDFBox2: How to add .png images to pdf using Apache PDFBox and https://issues.apache.org/jira/browse/PDFBOX-1990

This is my code:

package pdfProj;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

public class b {

    public static void main(String[] args) {
        PDDocument doc = null;
        doc = new PDDocument();        
        doc.addPage(new PDPage());
        try{
            BufferedImage awtImage = ImageIO.read( new File( "c://temp//line_chart.png" ) );
            PDImageXObject  pdImageXObject = LosslessFactory.createFromImage(doc, awtImage);
            PDPageContentStream contentStream = new PDPageContentStream(doc, new PDPage(), true, false);
            contentStream.drawImage(pdImageXObject, 200, 300, awtImage.getWidth() / 2, awtImage.getHeight() / 2);
                contentStream.close();
                doc.save( "c://temp//pdf//PDF_image.pdf" );
            doc.close();
        } catch (Exception io){
            System.out.println(" -- fail --" + io);
        }

    }
}

There is no exception. Just getting an empty PDF file created.


Solution

  • The issue is that you add a new page to the document

    doc.addPage(new PDPage());
    

    but then create a content stream for yet another new page which you don't add to the document:

    PDPageContentStream contentStream = new PDPageContentStream(doc, new PDPage(), true, false);
    

    You should create the content stream for the page you added to the document, e.g. like this:

    PDDocument doc = null;
    doc = new PDDocument();
    PDPage page = new PDPage();
    doc.addPage(page);
    try{
        BufferedImage awtImage = ImageIO.read( new File( "c://temp//line_chart.png" ) );
        PDImageXObject  pdImageXObject = LosslessFactory.createFromImage(doc, awtImage);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false);
        contentStream.drawImage(pdImageXObject, 200, 300, awtImage.getWidth() / 2, awtImage.getHeight() / 2);
        contentStream.close();
        doc.save( "c://temp//pdf//PDF_image.pdf" );
        doc.close();
    } catch (Exception io){
        System.out.println(" -- fail --" + io);
    }