27

I cannot figure out how to show a PDF file inside an Android application. So far I've found out that it is possible to launch an Intent and open the PDF using the Android default app. But I want to view PDF file directly inside my application without exiting. I have an header and a footer in my layout - I'd like to open the PDF in between. I have also found a PdfReader.jar file from github.com, but it opens the PDF in a new activity.

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
Adil Bhatty
  • 17,190
  • 34
  • 81
  • 118

8 Answers8

31

You can download the source from here(Display PDF file inside my android application)

Add this dependency in your gradle file:

compile 'com.github.barteksc:android-pdf-viewer:2.0.3'

activity_main.xml

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="@color/colorPrimaryDark"
        android:text="View PDF"
        android:textColor="#ffffff"
        android:id="@+id/tv_header"
        android:textSize="18dp"
        android:gravity="center"></TextView>

    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_below="@+id/tv_header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


    </RelativeLayout>

MainActivity.java

package pdfviewer.pdfviewer;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import java.util.List;

public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{
    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String SAMPLE_FILE = "android_tutorial.pdf";
    PDFView pdfView;
    Integer pageNumber = 0;
    String pdfFileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        pdfView= (PDFView)findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)

                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .load();
    }


    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }


    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }

}
Deepshikha Puri
  • 2,104
  • 22
  • 23
  • 6
    As someone said @ your blog: works like a charm. +1 you. Thanks for that. Just to put clear: pdf have to be inside **assets** folder, which have to be inside **main** folder (and not **res**). Thank you. – statosdotcom Mar 05 '17 at 07:59
  • 1
    Save your pdf file in your Assest folder (UNDER MAIN FOLDER) – Deepshikha Puri Mar 06 '17 at 10:14
  • What about show height-small pdf file on top of the current view? android:layout_height="wrap_content" is not work as expected. – Tapa Save Apr 07 '17 at 08:49
  • Nad how can I use pdfview inside RelativeLayout? I try but pdfview not visible. – Tapa Save Apr 07 '17 at 08:57
  • @TapaSave Can you please share your source code so that I can check it once. In demo I am also showing the pdf in Relative layout. – Deepshikha Puri Apr 07 '17 at 10:01
  • @Puri, My XML: – Tapa Save Apr 07 '17 at 10:21
  • And PDF shown in vertical_center of LinearLayout, but I need shown on top – Tapa Save Apr 07 '17 at 10:22
  • I think you have added the android:layout_weight="1" just remove it. then you can set the height of pdfview according to your requirement – Deepshikha Puri Apr 07 '17 at 13:24
  • if you are still getting this issue then let me know and if not then please upvote my answer :) – Deepshikha Puri Apr 07 '17 at 13:29
  • @Puri, don't work for me. I don't know height of pdfview. This is dynamic value. I need load pdf file with dynamic height and gravity pdfview to top of parent view. I use android_height='wrap_content' but layout still on center_vertical in parent. – Tapa Save Apr 10 '17 at 07:23
  • 14
    you guys do realize that adding this library increases you apk size by 16MB. Right ? – legalimpurity Jun 21 '17 at 12:05
  • 2
    I'm surprised no-one raised the issue of the library's size yet as @legalimpurity mentioned. – sHOLE Aug 12 '17 at 04:31
  • 3
    @sHOLE it took me a while to figure it out as well. And the solution to it is splitting you APK, but again even after splitting the average size increased is 5MB and thats not so good. – legalimpurity Aug 12 '17 at 07:48
  • i'm using that library but i want to be able to select texts or detect a text when someone taps a word in the pdf and store it in a variable and perform some operations. do you know how i can do it? – perpetualdarkness Apr 05 '21 at 18:59
  • This library is not currently being supported and there are quite a few open issues. As of API 30, links no longer work in PDFs with this library's latest version (3.2.0-beta.1) and the last update was over 2 years ago as of July 2021. – Stonz2 Jul 19 '21 at 20:57
8

Maybe you can integrate MuPdf in your application. Here is I've described how to do this: Integrate MuPDF Reader in an app

Community
  • 1
  • 1
Yury
  • 20,618
  • 7
  • 58
  • 86
  • I am not able to understand not not able to integrate MuPdf, I have downloaded both things, as mentioned, but don't have VS :( – Adil Bhatty Mar 12 '12 at 12:43
  • You need VS if you develop your application using Windows. If you use Linux you do not need it. – Yury Mar 12 '12 at 12:46
  • 1
    What is VS that you mentioned? – Parthi May 05 '15 at 10:02
  • This is an acronym of Visual Studio. – Yury May 05 '15 at 10:55
  • @Yury, when I try to call DocumentActivity with pdf url instead of pdf the empty popup with dissmiss button is opened...any idea ? – DespeiL Oct 08 '19 at 15:14
  • @DespeiL, I provided the answer more than 6 years ago. Since then, I did not use MuPDF in my projects more. So, I cannot answer your question. – Yury Oct 10 '19 at 16:38
6

Highly recommend you check out PDF.js which is able to render PDF documents in a standard a WebView component.

Also see https://github.com/loosemoose/androidpdf for a sample implementation of this.

Jay Sidri
  • 6,271
  • 3
  • 43
  • 62
3

I do not think that you can do this easily. you should consider this answer here:

How can I display a pdf document into a Webview?

basically you'll be able to see a pdf if it is hosted online via google documents, but not if you have it in your device (you'll need a standalone reader for that)

Community
  • 1
  • 1
STT LCU
  • 4,348
  • 4
  • 29
  • 47
2
 public class MainActivity extends AppCompatActivity {
   WebView webview;
   ProgressBar progressbar;

  @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webview = (WebView)findViewById(R.id.webview);
    progressbar = (ProgressBar) findViewById(R.id.progressbar);
    webview.getSettings().setJavaScriptEnabled(true);
    String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
    webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);

    webview.setWebViewClient(new WebViewClient() {

        public void onPageFinished(WebView view, String url) {
            // do your stuff here
            progressbar.setVisibility(View.GONE);
        }
    });

}

}

nithin joseph
  • 461
  • 3
  • 7
0

This is the perfect solution that worked for me without any 3rd party library.

Rendering a PDF Document in Android Activity/Fragment (Using PdfRenderer)

Murli
  • 524
  • 6
  • 11
-1
Uri path = Uri.fromFile(file );
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path , "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
    startActivity(pdfIntent ); 
    }
catch (ActivityNotFoundException e) {
    Toast.makeText(EmptyBlindDocumentShow.this,
            "No Application available to viewPDF",
            Toast.LENGTH_SHORT).show();
    }  
}  
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Dhina k
  • 1,481
  • 18
  • 24