ads_header

How To Open Pdf in Android Studio


Pdf is a file type that is very popular today, where every article or other text work that we have worked on can be converted into a file with pdf extension so that readers can be more flexible in reading our work, especially on the Android platform.





So, in this post I will discuss how to display PDF files on Android Studio. As usual, create a new project. then add the Assets folder

Right-click the project > New > Folder > Folder Assets


Then, in the Assets folder you save your PDF file


After that, open build.gradle then enter the following library

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.github.barteksc:android-pdf-viewer:2.7.0'
}

When finished, open activity_main.xml and enter the following code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_above="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <Button
        android:id="@+id/btn"
        android:text="LOAD PDF"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

Now, we open MainActivity.java then enter the following code to display the Pdf file when the "LOAD PDF" button is clicked






import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.github.barteksc.pdfviewer.PDFView;

public class MainActivity extends AppCompatActivity {
    PDFView pdfView;
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pdfView = (PDFView) findViewById(R.id.pdfView);
        btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {  
            @Override
            public void onClick(View v) {
                pdfView.fromAsset("visualbasic.pdf").load();
            }
        });
    }
}

When it's finished, the program is ready to run.

No comments:

Powered by Blogger.