首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用AndroidPDFViewer将pdf转换为图片并在android studio中显示。

使用AndroidPDFViewer将pdf转换为图片并在android studio中显示。
EN

Stack Overflow用户
提问于 2015-11-16 02:47:02
回答 2查看 2.6K关注 0票数 0

我正在使用这些说明来显示一个pdf文件(最上面的答案)。

Need help to convert a Pdf page into Bitmap in Android Java

我需要将其转换为位图,因为我希望能够添加一个矩形到它。

该活动似乎可以打开,但我只是得到一个空白屏幕上有一个非常暗淡的灰色框,我想pdf应该显示在那里。

谢谢!

以下是我的代码

代码语言:javascript
复制
//Imports:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.webkit.WebView;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFImage;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFPaint;
import net.sf.andpdf.nio.ByteBuffer;
import net.sf.andpdf.refs.HardReference;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;




public class imgviewpdf extends ActionBarActivity {

    //Globals:
    private WebView wv;
    private int ViewSize = 0;

    //OnCreate Method:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_imgviewpdf);
            //Settings
            PDFImage.sShowImages = true; // show images
            PDFPaint.s_doAntiAlias = true; // make text smooth
            HardReference.sKeepCaches = true; // save images in cache

            //Setup webview
            wv = (WebView) findViewById(R.id.webView1);
            wv.getSettings().setBuiltInZoomControls(true);//show zoom buttons
            wv.getSettings().setSupportZoom(true);//allow zoom
            //get the width of the webview
            wv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    ViewSize = wv.getWidth();
                    wv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            });

            pdfLoadImages();//load images
        }
    }

    //Load Images:
    private void pdfLoadImages() {
        try {
            // run async
            new AsyncTask<Void, Void, Void>() {
                // create and show a progress dialog
                ProgressDialog progressDialog = ProgressDialog.show(imgviewpdf.this, "", "Opening...");

                @Override
                protected void onPostExecute(Void result) {
                    //after async close progress dialog
                    progressDialog.dismiss();
                }

                @Override
                protected Void doInBackground(Void... params) {
                    try {
                        // select a document and get bytes
                        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/myDoc.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();
                        // create a pdf doc
                        PDFFile pdf = new PDFFile(bb);
                        //Get the first page from the pdf doc
                        PDFPage PDFpage = pdf.getPage(1, true);
                        //create a scaling value according to the WebView Width
                        final float scale = ViewSize / PDFpage.getWidth() * 0.95f;
                        //convert the page into a bitmap with a scaling value
                        Bitmap page = PDFpage.getImage((int) (PDFpage.getWidth() * scale), (int) (PDFpage.getHeight() * scale), null, true, true);
                        //save the bitmap to a byte array
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        page.compress(Bitmap.CompressFormat.PNG, 100, stream);
                        stream.close();
                        byte[] byteArray = stream.toByteArray();
                        //convert the byte array to a base64 string
                        String base64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
                        //create the html + add the first image to the html
                        String html = "<!DOCTYPE html><html><body bgcolor=\"#7f7f7f\"><img src=\"data:image/png;base64," + base64 + "\" hspace=10 vspace=10><br>";
                        //loop through the rest of the pages and repeat the above
                        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>";
                        //load the html in the webview
                        wv.loadDataWithBaseURL("", html, "text/html", "UTF-8", "");
                    } catch (Exception e) {
                        Log.d("CounterA", e.toString());
                    }
                    return null;
                }
            }.execute();
            System.gc();// run GC
        } catch (Exception e) {
            Log.d("error", e.toString());
        }
    }
}

下面是我的xml

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<WebView
    android:id="@+id/webView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</LinearLayout>
EN

回答 2

Stack Overflow用户

发布于 2015-11-16 02:59:30

这取决于,如果你希望用户不通过文件管理器或任何其他方式访问文件,而不是通过你的应用程序,那么使用分配给你的应用程序的内部存储。

代码语言:javascript
复制
File file = new File(context.getFilesDir(), filename);

如果您希望文件管理器或任何其他应用程序能够访问这些文件,那么您可以使用外部存储。

代码语言:javascript
复制
String filePath = Environment.getExternalStorageDirectory().getPath()+"/file_name.pdf";
File pdfFile = new File(filePath);
if (!pdfFile.getParentFile().exists()) {
     pdfFile.getParentFile().mkdirs();
  }

在写入文件之前,需要检查父目录是否存在。如果它不存在,那么就生成它。然后你就可以在文件上写东西了。

票数 1
EN

Stack Overflow用户

发布于 2015-11-16 02:52:10

请了解一下google's page about file storage以及内部和外部存储的优势。

您还可以通过设置让用户做出此选择。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33723521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档