Membuat Aplikasi PDF Reader Sendiri untuk Android Menggunakan Library AndroidPdfViewer

Oktober 11, 2017 0 Comments

Assalamualikum Wr. Wb, Selamat Sore kali ini admin akan membahas library AndroidPdfViewer yang berguna untuk membuat aplikasi pembaca PDF. Library ini sangat lengkap bisa membuka file PDF lewat asset, lewat Uri untuk dokumentasi lengkap bisa dilihat di github



ok langsung saja untuk membuatnya, pertama-tama masukan despendency ini di modul.gradle:
compile 'com.github.barteksc:android-pdf-viewer:2.7.0'

Kemudian buatlah sebuah button dan PDFView untuk menampilkan pdf nya
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
tools:context="com.giviews.pdfviewer.MainActivity">

    <
Button
       
android:id="@+id/openpdf"
       
android:text="Browse PDF"
        
android:layout_width="match_parent"
       
android:layout_height="wrap_content" />

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

</
RelativeLayout>

Kemudian untuk java nya masukan kode dibawah:
package com.giviews.pdfviewer;



import android.content.ActivityNotFoundException;

import android.content.Intent;

import android.content.pm.PackageManager;

import android.database.Cursor;

import android.graphics.Color;

import android.net.Uri;

import android.os.Bundle;

import android.provider.OpenableColumns;

import android.support.annotation.NonNull;

import android.support.v4.app.ActivityCompat;

import android.support.v4.content.ContextCompat;

import android.support.v7.app.AppCompatActivity;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;



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 AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener {

    private static final String TAG = MainActivity.class.getSimpleName();



    private final static int REQUEST_CODE = 42;

    public static final int PERMISSION_CODE = 42042;



    public static final String SAMPLE_FILE = "sample.pdf";

    public static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE";



    private PDFView pdfView;

    private Button openPdf;

    private Uri uri;

    private Integer pageNumber = 0;

    private String pdfFileName;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        pdfView = (PDFView) findViewById(R.id.pdfView);

        openPdf = (Button) findViewById(R.id.openpdf);



        openPdf.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                Intent fileIntent = new Intent();

                fileIntent.setType("application/pdf")

                .setAction(Intent.ACTION_GET_CONTENT);



                int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this, READ_EXTERNAL_STORAGE);



                if (permissionCheck != PackageManager.PERMISSION_GRANTED) {

                    ActivityCompat.requestPermissions(

                            MainActivity.this,

                            new String[]{READ_EXTERNAL_STORAGE},

                            PERMISSION_CODE

                    );



                    return;

                }



                startActivityForResult(Intent.createChooser(fileIntent, "SELECT PDF"), REQUEST_CODE);

            }

        });



    }



    void afterViews() {

        pdfView.setBackgroundColor(Color.LTGRAY);

        if (uri != null) {

            displayFromUri(uri);

        } else {

            displayFromAsset(SAMPLE_FILE);

        }

        setTitle(pdfFileName);

    }



    private void displayFromAsset(String assetFileName) {

        pdfFileName = assetFileName;



        pdfView.fromAsset(SAMPLE_FILE)

                .defaultPage(pageNumber)

                .onPageChange(this)

                .enableAnnotationRendering(true)

                .onLoad(this)

                .scrollHandle(new DefaultScrollHandle(this))

                .spacing(10) // in dp

                .load();

    }



    private void displayFromUri(Uri uri) {

        pdfFileName = getFileName(uri);



        pdfView.fromUri(uri)

                .defaultPage(pageNumber)

                .onPageChange(this)

                .enableAnnotationRendering(true)

                .onLoad(this)

                .scrollHandle(new DefaultScrollHandle(this))

                .spacing(10) // in dp

                .load();

    }



    private String getFileName(Uri uri) {

        String result = null;

        if (uri.getScheme().equals("content")) {

            Cursor cursor = getContentResolver().query(uri, null, null, null, null);

            try {

                if (cursor != null && cursor.moveToFirst()) {

                    result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));

                }

            } finally {

                if (cursor != null) {

                    cursor.close();

                }

            }

        }

        if (result == null) {

            result = uri.getLastPathSegment();

        }

        return result;

    }





    @Override

    public void loadComplete(int nbPages) {

        PdfDocument.Meta meta = pdfView.getDocumentMeta();

        Log.e(TAG, "title = " + meta.getTitle());

        Log.e(TAG, "author = " + meta.getAuthor());

        Log.e(TAG, "subject = " + meta.getSubject());

        Log.e(TAG, "keywords = " + meta.getKeywords());

        Log.e(TAG, "creator = " + meta.getCreator());

        Log.e(TAG, "producer = " + meta.getProducer());

        Log.e(TAG, "creationDate = " + meta.getCreationDate());

        Log.e(TAG, "modDate = " + meta.getModDate());



        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }



    private 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 + "-");

            }

        }

    }



    @Override

    public void onPageChanged(int page, int pageCount) {

        pageNumber = page;

        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));

    }



    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {

            uri = data.getData();

            displayFromUri(uri);

        }

    }

}

terakhir tambahkan permission di manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


sekarang jalankan aplikasinya di smartphone anda / di emulator jika PDF nya terbaca maka anda telah berhasil membuat aplikasi PDF reader. ok sekianlah tutorial kali ini semoga bermanfaat kurang dan lebihnya mohon maaf, jangan lupa share artikel ini ke teman anda semoga bermanfaat.

Juanas Smith Shared

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard.

0 komentar :