10

I have a document scan functionality built into a client app. The app stores documents as image archives – and a document can have 1 to n pages. A menu item is exposed to allow the user to export the document as a PDF.

The problem is that the resulting PDF is too large (13.5 Mb for a document of 6 pages). This causes problems with lots of email services that do not allow the PDF to be emailed.

So I have worked on compressing and resizing the bitmaps before drawing them to the PDF. But no matter what I do to the bitmaps (changing JPEG compression to 2 vs 25 vs 100 or the scale of the Matrix) the file size for the generated PDF is always the same.

How do I properly compress the bitmaps to actually affect the resulting PDF file size?

File[] images = getImages();
PdfDocument doc = new PdfDocument();

for (int i = 0; i < images.length; i++) {
    // Get bitmap from file
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap original = BitmapFactory.decodeFile(images[i].getAbsolutePath(), options);

    // Compress bitmap
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    original.compress(Bitmap.CompressFormat.JPEG, 25, stream);
    byte[] bitmapData = stream.toByteArray();
    Bitmap compressed = BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length);

    // Calculate page size and bitmap scale
    int width = 768;
    int height = (int) (((float) width / (float) original.getWidth()) * (float) original.getHeight());
    float scaleWidth = ((float) width) / original.getWidth();
    float scaleHeight = ((float) height) / original.getHeight();

    // Create a scale matrix for the bitmap
    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);

    // Draw scaled and compressed bitmap to page
    PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(width, height, i + 1).create();
    PdfDocument.Page page = doc.startPage(pageInfo);
    page.getCanvas().drawBitmap(compressed, matrix, null);
    doc.finishPage(page);
}

0 Answers0