Search code examples
android-studiopdfbox

Pdfbox-Android shows empty page


I recently used pdfbox android library because iText is under AGPL. I tried running following code.

PDDocument document = new PDDocument();
PDPage page= new PDPage();
document.addPage(page);
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
Bitmap bitmap=BitmapFactory.decodeFile(imagesObject.get(0).image); //imagesobject is string path
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
PDImageXObject pdImage = PDImageXObject.createFromFile(imagesObject.get(0).image,document);
PDPageContentStream contentStream = new PDPageContentStream(document, page,true,true);
contentStream.drawImage(pdImage,70,70,pdImage.getWidth(), pdImage.getHeight());
contentStream.close();
document.save(file);
document.close();

PDF is saved with empty page no image is shown. I noticed size of pdf is 6mb, Which means the image has been drawn but can't see. Any Fix?

Also I am using ported library by TomRoush.

This is the link for pdf that was generated here

enter image description here


Solution

  • As discussed in the comments, the image had a .jpg extension in the name, but was a PNG image file. The PDImageXObject createFromFile(String imagePath, PDDocument doc) method assumes the file type by its extension, so it embedded the file 1:1 in the PDF and assigned a DCT filter. Both of these would have been correct for a jpeg file, but not for png.

    So the solution would be to either rename the file, or use the createFromFileByContent method.