Search code examples
androidpdf-generationfilesize

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;
}

Solution

  • There are a few main things that increases the size of a PDF file:

    hi-resolution pictures (where lo-res would suffice)
    embedded fonts (where content would still be readable "good enough" without them)
    PDF content not required any more for the current version/view (older version of certain objects)
    embedded ICC profiles
    embedded third-party files (using the PDF as a container)
    embedded job tickets (for printing)
    embedded Javascript
    and a few more
    

    Try using iText. Following links give a basice idea for iText in android.

    http://technotransit.wordpress.com/2011/06/17/using-itext-in-android/

    http://www.mysamplecode.com/2013/05/android-itext-pdf-bluetooth-printer.html

    https://stackoverflow.com/a/21025162/3110609