朋友们,我已成功使用 webview 在我的应用程序中创建了一个 pdfview。但是有时,当我加载具有更多页面(例如超过 40 个)的 pdf 文件时,我会遇到崩溃,如果你们中的任何人能告诉我为什么会收到此消息以及我必须做些什么来避免收到此错误,这将是有帮助的。下面是我得到的 logcat 错误消息。
日志错误:
Out of memory on a 1322872-byte allocation.
FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.OutOfMemoryError
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:836)
at android.graphics.Bitmap.createBitmap(Bitmap.java:813)
at android.graphics.Bitmap.createBitmap(Bitmap.java:780)
at com.sun.pdfview.PDFPage.getImage(PDFPage.java:219)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
下面是我的代码:
RandomAccessFile f = new RandomAccessFile(file, "r");
data1 = new byte[(int)f.length()];
f.readFully(data1);
RandomAccessFile f = new RandomAccessFile(file, "r");
byte[] data1 = new byte[(int)f.length()];
f.readFully(data1)
ByteBuffer bb = ByteBuffer.NEW(data1);
PDFFile pdf = new PDFFile(bb);
PDFPage PDFpage = pdf.getPage(1, true);
final float scale = ViewSize / PDFpage.getWidth() * 0.95f;
float pdfWid = PDFpage.getWidth() * scale;
float pdfH = PDFpage.getHeight() * scale;
Bitmap page;
if(page != null){
page.recycle();
page = null;
}
page = PDFpage.getImage((int)pdfWid, (int)pdfH, null, true, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
page.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
stream.reset();
String base64 = Base64.encodeToString(byteArray, Base64.NO_WRAP);
String html = "<!DOCTYPE html><html><body bgcolor=\"#b4b4b4\"><img src=\"data:image/png;base64,"+base64+"\" hspace=10 vspace=10><br>";
int size = pdf.getNumPages();
try{
for(int i = 2; i <= size; i++)
{
PDFpage = pdf.getPage(i, true);
page = PDFpage.getImage((int)pdfWid, (int)pdfH, null, true, true);
page.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
stream.reset();
page.recycle();
base64 = Base64.encodeToString(byteArray, Base64.NO_WRAP);
html += "<img src=\"data:image/png;base64,"+base64+"\" hspace=10 vspace=10><br>";
}
}catch (Exception e){
Log.d("error", e.toString());
}
stream.close();
html += "</body></html>";
wv.loadDataWithBaseURL("", html, "text/html","UTF-8", "");