0

Im using these instructions to display a pdf file (the top answer).

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

I need to convert it to a bitmap as I want to be able to add a rectangle to it.

The activity seems to open okay, but I just get a blank screen with a very faint grey box where I suppose the pdf should display.

Thanks!

here is my code

//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());
        }
    }
}

and here is my xml

<?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>
Community
  • 1
  • 1
AesculusMaximus
  • 195
  • 3
  • 14

2 Answers2

1

It depends, if you want the user not to access the files via file managers or any other way besides through your app, then use internal storage assigned to your app.

File file = new File(context.getFilesDir(), filename);

If you like the files to be able to access by file managers or any other apps, then you can use external storage.

String filePath = Environment.getExternalStorageDirectory().getPath()+"/file_name.pdf";
File pdfFile = new File(filePath);
if (!pdfFile.getParentFile().exists()) {
     pdfFile.getParentFile().mkdirs();
  }

Before writing to the file, you need to check the parent directory exist or not. Then make if its not exist. Then you can write on the file.

Thilek
  • 676
  • 6
  • 18
  • So where do I need to put the file on my phone? Does it matter? At the moment it is in File file = new File(Environment.getExternalStorageDirectory().getPath() + "/storage/extSdCard/Download/myDoc.pdf"); but it doesnt show when I run the app – AesculusMaximus Nov 15 '15 at 19:30
  • @AesculusMaximus it depends on you where you like the file to be. If you don't want users to access the file from other apps or simply opening the sdcard then best to use internal. But if you want users to easily access your files and also your files sizes are huge and you have lots files then use external. – Thilek Nov 16 '15 at 12:19
  • @AesculusMaximus External storage also have two options. There is public location in which the files will be stored in the root folder of the sdcard. When you delete your app the files will still be in the root folder. As for getExternalStorageDirectory the files will be in /sdcard/Android/data/(your app package name)/files/(path you set) – Thilek Nov 16 '15 at 12:19
  • So what should I put here?..... File file = new File(Environment.getExternalStorageDirectory().getPath() + "/myDoc.pdf"); I am using external storage. – AesculusMaximus Nov 16 '15 at 20:26
  • @AesculusMaximus i edited my answer above. have a look. – Thilek Nov 17 '15 at 15:53
  • What should I replace with if I want to use public location? – AesculusMaximus Dec 30 '15 at 15:12
  • @AesculusMaximus this might help you understand more http://developer.android.com/guide/topics/data/data-storage.html#filesExternal – Thilek Jan 12 '16 at 15:27
0

Please have a look at google's page about file storage and the benefits for internal and external storage.

You can also make the user make this choice via settings.

online Thomas
  • 8,864
  • 6
  • 44
  • 85