Search code examples
javaandroidpdfpdfboxpdfdocument

PDF size too large generating through Android PDFDocument. And while using pdfbox it is cutting image in output


I am using android pdf document library to convert image into pdf but it is generating very large size pdf.

PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo =new 
PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();                            
PdfDocument.Page  page = document.startPage(pageInfo);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), 
bitmap.getHeight(),false);                        

Canvas canvas = page.getCanvas();
canvas.drawBitmap(scaledBitmap, 0f, 0f, null);
document.finishPage(page);

document.writeTo(new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+"/"+newPDFNameSingle));
document.close();

here is the apache pdf box implementation but it is cutting image in output pdf

PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);

PDPageContentStream contentStream = new PDPageContentStream(document, page);
InputStream inputStream = new FileInputStream(tempFile);
PDImageXObject ximage = JPEGFactory.createFromStream(document,inputStream);

contentStream.drawImage(ximage, 20, 20);
contentStream.close();

document.save(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+"/"+newPDFNameSingle);
                            document.close();

How can I achieve regular size pdf generation? My image in 100 kb in size but pdf generating 1 mb file.


Solution

  • In your android pdf document library code you set the page size to the image height and width values

    PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();                            
    

    and draw the image at the origin:

    canvas.drawBitmap(scaledBitmap, 0f, 0f, null);
    

    You can do the same in your PDFBox code:

    PDDocument document = new PDDocument();
    
    PDImageXObject ximage = JPEGFactory.createFromStream(document,imageResource);
    
    PDPage page = new PDPage(new PDRectangle(ximage.getWidth(), ximage.getHeight()));
    document.addPage(page);
    
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.drawImage(ximage, 0, 0);
    contentStream.close();
    

    (DrawImage test testDrawImageToFitPage)

    Alternatively, as discussed in comments, you can set the current transformation matrix before drawing the image to scale it down to fit the page.