Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android PdfDocument file size

I want to generate a PDF File from a View using the PdfDocument android class introduced in KitKat. I managed to do it, and the file is so far generated ok, ending up having a correct PDF. The only problem is the file is huge, 12Mb for just one page. Is there a way to reduce the File size?

The code I am using to generate the PDF is:

public static File generateDocument(Activity activity, String fileName, ViewGroup container) throws IOException{
    File f = new File(activity.getExternalFilesDir(null), fileName);
    PdfDocument document = new PdfDocument();
    try{
        for(int i=0;i<container.getChildCount();i++){
            View v = container.getChildAt(i);
            PdfDocument.PageInfo.Builder pageBuilder = new PdfDocument.PageInfo.Builder(v.getWidth(), v.getHeight(), i);
            Page page = document.startPage(pageBuilder.create());
            v.draw(page.getCanvas());
            document.finishPage(page);
        }

        document.writeTo(new FileOutputStream(f));
    } finally{
        if(document!=null){
            document.close();
        }
    }
    return f;
}
like image 246
evaristokbza Avatar asked Apr 02 '14 08:04

evaristokbza


1 Answers

Using PDFDocument, be sure to downscale your images prior to drawing them in the canvas.

When drawing to the screen, this is enough to scale the bitmap :

canvas.drawBitmap(bmp, src, dst, paint);

However, when using the canvas from PdfDocument.Page.getCanvas, this canvas will not downscale the bitmap, it will just squeeze it into a smaller zone. Instead you should do something like this:

// Scale bitmap : filter = false since we are always downSampling
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight,
    false); // filter=false if downscaling, true if upscaling

canvas.drawBitmap(scaledBitmap, null, dst, paint);

scaledBitmap.recycle();

This is embedded in Android so it is much easier than using a third-party library. (The above was tested on a Marshmallow platform)

like image 170
JM Lord Avatar answered Oct 05 '22 22:10

JM Lord