I am working with a PDF that is a map of the subway system. The PDF itself is <1 MB. I am trying to get the Android phone to convert to Bitmap when launching the app, so that when the mapfragment is accessed by the user, I can load a cached bitmap that a user can then interact with
I am having an issue where my converted Bitmap is 84 MB and thus (I believe) too big for the cache
My question is what can I do to mitigate this issue. I had a couple of approaches in mind
convert the PDF to a PNG outside of the app, and store the PNG as an asset and simply load from that. I am avoiding this approach since the map gets updated frequently and I'd rather quickly drop in a PDF into the project each time that happens
convert the PDF to bitmap upon tapping the map fragment but that causes a 1 second or so delay as the PDF gets converted each time the map fragment is accessed
convert the PDF to bitmap and save to disk cache, but I am hesitant about frequent writes to the user's disk and negative implications of that
Below is my PDF conversion code
private Bitmap convertPdfToBitmap() {
Bitmap bitmap = null;
PdfiumCore pdfiumCore = new PdfiumCore(this);
try {
File f = FileUtils.fileFromAsset(this, "mappdf.pdf");
ParcelFileDescriptor fd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
pdfiumCore.openPage(pdfDocument, 0); // open the first page
// Create a Bitmap object to hold the content of the page
int width = pdfiumCore.getPageWidthPoint(pdfDocument, 0) * 3; // I found less than 3 too blurry of an output
int height = pdfiumCore.getPageHeightPoint(pdfDocument, 0) * 3;
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int bitmapByteCount = bitmap.getByteCount();
Log.i("RootActivity", "Bitmap byte count: " + bitmapByteCount);
// Render the page content on the Bitmap object
pdfiumCore.renderPageBitmap(pdfDocument, bitmap, 0, 0, 0, width, height);
pdfiumCore.closeDocument(pdfDocument); // remember to close the document
Log.d("RootActivity", "PDF conversion completed");
} catch(Exception e) {
Log.e("RootActivity", e.toString());
}
return bitmap;
}
And the cache code
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount() / 1024;
}
};
// Convert PDF to bitmap and add it to cache
Bitmap bitmap = convertPdfToBitmap();
addBitmapToMemoryCache("mappdf", bitmap);