How to render a PDF file in Android

后端 未结 9 943
猫巷女王i
猫巷女王i 2020-11-22 02:09

Android does not have PDF support in its libraries. Is there any way to render PDF files in the Android applications?

相关标签:
9条回答
  • 2020-11-22 02:21

    I finally was able to modify butelo's code to open any PDF file in the Android filesystem using pdf.js. The code can be found on my GitHub

    What I did was modified the pdffile.js to read HTML argument file like this:

    var url = getURLParameter('file');
    
    function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null}
    

    So what you need to do is just append the file path after the index.html like this:

    Uri path = Uri.parse(Environment.getExternalStorageDirectory().toString() + "/data/test.pdf");
    webView.loadUrl("file:///android_asset/pdfviewer/index.html?file=" + path);
    

    Update the path variable to point to a valid PDF in the Adroid filesystem.

    0 讨论(0)
  • 2020-11-22 02:24

    you can use a simple method by import

    implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
    

    and the XML code is

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

    and just declare and add a file to an asset folder and just assign the name

       PDFView  pdfView=findViewById(R.id.pdfv);       
        pdfView.fromAsset("agl.pdf").load();
    
    0 讨论(0)
  • 2020-11-22 02:30

    Taken from my blog:

    public class MyPdfViewActivity extends Activity {
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WebView mWebView=new WebView(MyPdfViewActivity.this);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setPluginsEnabled(true);
        mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo);
        setContentView(mWebView);
      }
    }
    
    0 讨论(0)
  • 2020-11-22 02:31

    Since API Level 21 (Lollipop) Android provides a PdfRenderer class:

    // create a new renderer
     PdfRenderer renderer = new PdfRenderer(getSeekableFileDescriptor());
    
     // let us just render all pages
     final int pageCount = renderer.getPageCount();
     for (int i = 0; i < pageCount; i++) {
         Page page = renderer.openPage(i);
    
         // say we render for showing on the screen
         page.render(mBitmap, null, null, Page.RENDER_MODE_FOR_DISPLAY);
    
         // do stuff with the bitmap
    
         // close the page
         page.close();
     }
    
     // close the renderer
     renderer.close();
    

    For more information see the sample app.

    For older APIs I recommend Android PdfViewer library, it is very fast and easy to use, licensed under Apache License 2.0:

    pdfView.fromAsset(String)
      .pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
      .enableSwipe(true)
      .swipeHorizontal(false)
      .enableDoubletap(true)
      .defaultPage(0)
      .onDraw(onDrawListener)
      .onLoad(onLoadCompleteListener)
      .onPageChange(onPageChangeListener)
      .onPageScroll(onPageScrollListener)
      .onError(onErrorListener)
      .enableAnnotationRendering(false)
      .password(null)
      .scrollHandle(null)
      .load();
    
    0 讨论(0)
  • 2020-11-22 02:35

    Download the source code here (Display PDF file inside my android application)

    Add this dependency in your Grade: 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

    import android.app.Activity;
    import android.database.Cursor;
    import android.net.Uri;
    import android.provider.OpenableColumns;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.RelativeLayout;
    
    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 + "-");
                }
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 02:42

    To add a little light to this, I would have to go with the pdf.js solution from Mozilla. Here is the link to an already well written implementation of this: https://bitbucket.org/butelo/pdfviewer/.

    Here are the edits that I added in my Android Activity:

    private String getInternalPDFURL(String interalPDFName){
        return "file:///android_asset/pdfviewer/index.html?pdf=" + interalPDFName + ".pdf";
    }
    

    Here are the edits I made in pdffile.js:

    var url = '../' + getPDFURL();
    
    function getPDFURL(){
        var query = window.location.search.substring(1);
        var vars = query.split("=");
        var pdfPage = vars[1];
        return pdfPage;
    }
    
    0 讨论(0)
提交回复
热议问题