WebView android中的PDF文件

时间:2013-12-12 11:19:51

标签: android pdf webview

我正在尝试在webview中加载pdf文件。但pdf中的文字和图像显示不清楚。

----------------------------------------------- --------------------------------------------

代码:

File file = new File("/sdcard/downloadedfile.pdf");
                RandomAccessFile raf = new RandomAccessFile(file, "r");
                FileChannel channel = raf.getChannel();
                ByteBuffer bb = ByteBuffer.NEW(channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()));
                raf.close();

                PDFFile pdf = new PDFFile(bb);
                PDFPage PDFpage = pdf.getPage(1, true);
                final float scale = ViewSize / PDFpage.getWidth() * 0.95f;

                Bitmap page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                page.compress(Bitmap.CompressFormat.PNG, 100, stream);
                stream.close();

                byte[] byteArray = stream.toByteArray();

                String base64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
                String html = "<!DOCTYPE html><html><body bgcolor=\"#7f7f7f\"><img src=\"data:image/png;base64,"+base64+"\" hspace=10 vspace=10><br>";
                for(int i = 2; i <= pdf.getNumPages(); i++)
                {
                    PDFpage = pdf.getPage(i, true);
                    page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true);
                    stream = new ByteArrayOutputStream();
                    page.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    stream.close();

                    byteArray = stream.toByteArray();
                    base64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
                    html += "<img src=\"data:image/png;base64,"+base64+"\" hspace=10 vspace=10><br>";
                }
                html += "</body></html>";
                wv.loadDataWithBaseURL("", html, "text/html","UTF-8", "");

0 个答案:

没有答案