Create and Display PDF within Android Application

Embedding functionality to Create and Display PDF within Android Application can increase engagement of your user significantly. Rather than asking user to bounce off to other pdf viewer application, we will create an application with support of Pdf creation and viewing functionalities.

 

[su_button url=”https://github.com/androidsrc/PdfReadWrite” target=”blank” style=”stroked” background=”#51d461″ color=”#ffffff” size=”6″ center=”yes” radius=”0″ icon=”icon: arrow-circle-o-down”]Download Full Source Code[/su_button]

 

[su_carousel source=”media: 522,523,524,525,526″ link=”lightbox” width=”1000″ height=”720″ items=”2″ mousewheel=”no”]android.permission.INTERNET[/su_carousel]

Sample Application For Creation and Display of Pdf

1. Create a new Android Application Project with Package name com.androidsrc.pdfdemo. Make sure to select API 21. As PdfRenderer was introduced in requires API level 21. If you are creating functionality of Pdf document creation only, you can opt for API 19 as well.

2. Preparing AndroidManifest.xml

Add permission into your manifest file to read and write from external storage. Ensure to add uses-sdk tag with minSdkVersion specified as 21.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidsrc.pdfdemo" android:versionCode="1" android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" android:configChanges="mcc|mnc|locale|keyboard|keyboardHidden|screenLayout|uiMode|orientation|screenSize" android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3. Preparing UI Components

For our main view, we will use FrameLayout as parent view. It will have four child LinearLayout views for displaying pdf options, pdf document listing and reading pdf, creating pdf. We will navigate between these views intercepting back key and close option in menu. Final activity_main.xml will be as below after including views for above functionalities.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context="com.androidsrc.pdfdemo.MainActivity">

    <LinearLayout
        android:id="@+id/options_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="20dp">

        <Button
            android:id="@+id/read_pdf"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Open Existing Pdf"/>

        <Button
            android:id="@+id/create_new_pdf"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="Create New Pdf"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/read_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="invisible">

        <ImageView
            android:id="@+id/pdfView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="@android:color/white"
            android:scaleType="fitCenter"/>

        <LinearLayout
            style="?android:attr/buttonBarStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:measureWithLargestChild="true"
            android:orientation="horizontal">

            <Button
                android:id="@+id/previous"
                style="?android:attr/buttonBarButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Previous"/>

            <Button
                android:id="@+id/next"
                style="?android:attr/buttonBarButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Next"/>
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/pdf_selection_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="20dp"
        android:visibility="invisible">

        <ListView
            android:id="@+id/pdfList"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
        </ListView>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/write_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="20dp"
        android:visibility="invisible">

        <EditText
            android:id="@+id/pdf_content"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="top"
            android:hint="Enter content"
            android:lineSpacingExtra="4dp"
            android:lines="15"/>

        <Button
            android:id="@+id/generate_pdf"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Generate Pdf">
        </Button>
    </LinearLayout>

</FrameLayout>

We will be using ListView for displaying list of Pdf document available. Create new layout file /res/layout/list_item.xml for list viw item. It will just have TextView which will display path for Pdf documents.

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:textColor="@android:color/black"/>

Create new menu file /res/menu/main.xml. It will have one menu item which will incorporate functionality to navigate between different views in layout.

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.androidsrc.pdfdemo.MainActivity">

    <item
        android:id="@+id/action_close"
        android:orderInCategory="100"
        android:showAsAction="always"
        android:title="Close"/>

</menu>

4. Preparing Applicaiton Launcher Activity Source Code

Creating PDF Document

For creating PDF Document, we will use PdfDocument class which was added in API level 19. It prvoides api to create new PDF document, you can process content creation page by page using PdfDocument.Page. PDF page associates a canvas on which you can draw your content. For representing attributes of a page like height, width and page number etc PdfDocument.PageInfo is used.

// crate a page info with attributes as below
// page number, height and width
// i have used height and width to that of pdf content view
int pageNumber = 1;
PageInfo pageInfo = new PageInfo.Builder(content.getWidth(),
        content.getHeight() - 20, pageNumber).create();

// create a new page from the PageInfo
Page page = document.startPage(pageInfo);

// repaint the user's text into the page
content.draw(page.getCanvas());

// do final processing of the page
document.finishPage(page);

// saving pdf document to sdcard
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss");
String pdfName = "pdfdemo"
        + sdf.format(Calendar.getInstance().getTime()) + ".pdf";

// all created files will be saved at path /sdcard/PDFDemo_AndroidSRC/
File outputFile = new File("/sdcard/PDFDemo_AndroidSRC/", pdfName);

try {
    outputFile.createNewFile();
    OutputStream out = new FileOutputStream(outputFile);
    document.writeTo(out);
    document.close();
    out.close();
} catch (IOException e) {
    e.printStackTrace();
}

Pretty cool, with just few lines of codes as above you can create new Pdf document. You can simply provide your user to share content of your application in form of Pdf document. For applications like billing, patient information etc, user can quickly opt to create Pdf and share.

Displaying PDF Document

For displaying PDF Document, we will use PdfRenderer class which was added in API level 21. With this you can render Pdf Document pages into native views of your android application. PdfRenderer.Page is used to open, render and closing page of particular index in Pdf document.

// filePath represent path of Pdf document on storage
File file = new File(filePath);
// FileDescriptor for file, it allows you to close file when you are
// done with it
ParcelFileDescriptor mFileDescriptor = null;
try {
    mFileDescriptor = ParcelFileDescriptor.open(file,
            ParcelFileDescriptor.MODE_READ_ONLY);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
// PdfRenderer enables rendering a PDF document
PdfRenderer mPdfRenderer = null;
try {
    mPdfRenderer = new PdfRenderer(mFileDescriptor);
} catch (IOException e) {
    e.printStackTrace();
}

// Open page with specified index
PdfRenderer.Page mCurrentPage = mPdfRenderer.openPage(index);
Bitmap bitmap = Bitmap.createBitmap(mCurrentPage.getWidth(),
        mCurrentPage.getHeight(), Bitmap.Config.ARGB_8888);

// Pdf page is rendered on Bitmap
mCurrentPage.render(bitmap, null, null,
PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
// Set rendered bitmap to ImageView (pdfView in my case)
pdfView.setImageBitmap(bitmap);

mCurrentPage.close();
mPdfRenderer.close();
try {
    mFileDescriptor.close();
} catch (IOException e) {
    e.printStackTrace();
}

Complete code for MainActivity.java

package com.androidsrc.pdfdemo;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfDocument.Page;
import android.graphics.pdf.PdfDocument.PageInfo;
import android.graphics.pdf.PdfRenderer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

public class MainActivity extends Activity implements OnClickListener {

    /**
     * For identifying current view mode read/create/listing/options
     *
     * @author androidsrc.net
     */
    interface CurrentView {
        int OPTIONS_LAYOUT = 1;
        int READ_LAYOUT = 2;
        int WRITE_LAYOUT = 3;
        int PDF_SELECTION_LAYOUT = 4;
    }

    /**
     * FrameLayout child views. We will manage our UI to one layout Hide/Show
     * these views as per requirement
     */
    LinearLayout optionsLayout;
    LinearLayout readLayout;
    LinearLayout writeLayout;
    LinearLayout pdfSelectionLayout;

    private static int currentView;

    // Pdf content will be generated with User Input Text
    EditText pdfContentView;
    // For navigating back
    MenuItem closeOption;
    // List view for showing pdf files
    ListView pdfList;
    // Background task to generate pdf file listing
    PdfListLoadTask listTask;
    // Adapter to list view
    ArrayAdapter<String> adapter;
    // array of pdf files
    File[] filelist;

    // index to track currentPage in rendered Pdf
    private static int currentPage = 0;
    // View on which Pdf content will be rendered
    ImageView pdfView;

    // Currently rendered Pdf file
    String openedPdfFileName;
    Button generatePdf;
    Button next;
    Button previous;

    // File Descriptor for rendered Pdf file
    private ParcelFileDescriptor mFileDescriptor;
    // For rendering a PDF document
    private PdfRenderer mPdfRenderer;
    // For opening current page, render it, and close the page
    private PdfRenderer.Page mCurrentPage;

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

        optionsLayout = (LinearLayout) findViewById(R.id.options_layout);
        readLayout = (LinearLayout) findViewById(R.id.read_layout);
        writeLayout = (LinearLayout) findViewById(R.id.write_layout);
        pdfSelectionLayout = (LinearLayout) findViewById(R.id.pdf_selection_layout);
        pdfContentView = (EditText) findViewById(R.id.pdf_content);

        findViewById(R.id.read_pdf).setOnClickListener(this);
        findViewById(R.id.create_new_pdf).setOnClickListener(this);
        next = (Button) findViewById(R.id.next);
        next.setOnClickListener(this);
        previous = (Button) findViewById(R.id.previous);
        previous.setOnClickListener(this);
        generatePdf = (Button) findViewById(R.id.generate_pdf);
        generatePdf.setOnClickListener(this);

        pdfList = (ListView) findViewById(R.id.pdfList);
        pdfList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // On Clicking list item, Render Pdf file corresponding to
                // filePath
                openedPdfFileName = adapter.getItem(position);
                openRenderer(openedPdfFileName);
                updateView(CurrentView.READ_LAYOUT);
            }
        });
        pdfView = (ImageView) findViewById(R.id.pdfView);

        currentView = CurrentView.OPTIONS_LAYOUT;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        closeOption = menu.findItem(R.id.action_close);
        closeOption.setVisible(false);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_close) {
            if (currentView == CurrentView.PDF_SELECTION_LAYOUT) {
                updateView(CurrentView.OPTIONS_LAYOUT);
                updateActionBarText();
            } else if (currentView == CurrentView.READ_LAYOUT) {
                if (listTask != null)
                    listTask.cancel(true);
                listTask = new PdfListLoadTask();
                listTask.execute();
                updateView(CurrentView.PDF_SELECTION_LAYOUT);
            } else if (currentView == CurrentView.WRITE_LAYOUT) {
                hideInputMethodIfShown();
                updateView(CurrentView.OPTIONS_LAYOUT);
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Handler back key Update UI current view is not options view else call
     * super.onBackPressed()
     */
    @Override
    public void onBackPressed() {
        if (currentView == CurrentView.PDF_SELECTION_LAYOUT) {
            updateView(CurrentView.OPTIONS_LAYOUT);
            updateActionBarText();
        } else if (currentView == CurrentView.READ_LAYOUT) {
            if (listTask != null)
                listTask.cancel(true);
            listTask = new PdfListLoadTask();
            listTask.execute();
            updateView(CurrentView.PDF_SELECTION_LAYOUT);
        } else if (currentView == CurrentView.WRITE_LAYOUT) {
            hideInputMethodIfShown();
            updateView(CurrentView.OPTIONS_LAYOUT);
        } else {
            super.onBackPressed();
        }
    }

    /**
     * API to hide keyboard if shown Will be used when user naviagates after
     * generating Pdf
     */
    private void hideInputMethodIfShown() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(pdfContentView.getWindowToken(), 0, null);
    }

    /**
     * API to update ActionBar text
     */
    private void updateActionBarText() {
        if (currentView == CurrentView.READ_LAYOUT) {
            int index = mCurrentPage.getIndex();
            int pageCount = mPdfRenderer.getPageCount();
            previous.setEnabled(0 != index);
            next.setEnabled(index + 1 < pageCount);
            getActionBar().setTitle(
                    openedPdfFileName + "(" + (index + 1) + "/" + pageCount
                            + ")");
        } else {
            getActionBar().setTitle(R.string.app_name);
        }
    }

    /**
     * API to update View
     *
     * @param updateView updateView specifies the target view
     */
    private void updateView(int updateView) {
        switch (updateView) {
            case CurrentView.OPTIONS_LAYOUT:
                currentView = CurrentView.OPTIONS_LAYOUT;
                closeOption.setVisible(false);
                optionsLayout.setVisibility(View.VISIBLE);
                readLayout.setVisibility(View.INVISIBLE);
                writeLayout.setVisibility(View.INVISIBLE);
                pdfSelectionLayout.setVisibility(View.INVISIBLE);
                break;
            case CurrentView.READ_LAYOUT:
                currentView = CurrentView.READ_LAYOUT;
                showPage(currentPage);

                closeOption.setVisible(true);
                optionsLayout.setVisibility(View.INVISIBLE);
                readLayout.setVisibility(View.VISIBLE);
                writeLayout.setVisibility(View.INVISIBLE);
                pdfSelectionLayout.setVisibility(View.INVISIBLE);
                break;
            case CurrentView.PDF_SELECTION_LAYOUT:
                currentView = CurrentView.PDF_SELECTION_LAYOUT;

                closeRenderer();

                if (listTask != null)
                    listTask.cancel(true);
                listTask = new PdfListLoadTask();
                listTask.execute();

                closeOption.setVisible(true);
                optionsLayout.setVisibility(View.INVISIBLE);
                readLayout.setVisibility(View.INVISIBLE);
                writeLayout.setVisibility(View.INVISIBLE);
                pdfSelectionLayout.setVisibility(View.VISIBLE);
                break;
            case CurrentView.WRITE_LAYOUT:
                currentView = CurrentView.WRITE_LAYOUT;

                closeOption.setVisible(true);
                optionsLayout.setVisibility(View.INVISIBLE);
                readLayout.setVisibility(View.INVISIBLE);
                writeLayout.setVisibility(View.VISIBLE);
                pdfSelectionLayout.setVisibility(View.INVISIBLE);
                break;
        }
    }

    /**
     * Callback for handling view click events
     */
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        switch (viewId) {
            case R.id.read_pdf:
                updateView(CurrentView.PDF_SELECTION_LAYOUT);
                break;
            case R.id.create_new_pdf:
                updateView(CurrentView.WRITE_LAYOUT);
                break;
            case R.id.generate_pdf:
                if (pdfContentView.getText().toString().isEmpty()) {
                    Toast.makeText(getApplicationContext(),
                            "Please enter text to generate Pdf", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    new PdfGenerationTask().execute();
                    v.setEnabled(false);
                }
                break;
            case R.id.next:
                currentPage++;
                showPage(currentPage);
                break;
            case R.id.previous:
                currentPage--;
                showPage(currentPage);
                break;
        }

    }

    /**
     * API for initializing file descriptor and pdf renderer after selecting pdf
     * from list
     *
     * @param filePath
     */
    private void openRenderer(String filePath) {
        File file = new File(filePath);
        try {
            mFileDescriptor = ParcelFileDescriptor.open(file,
                    ParcelFileDescriptor.MODE_READ_ONLY);
            mPdfRenderer = new PdfRenderer(mFileDescriptor);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * API for cleanup of objects used in rendering
     */
    private void closeRenderer() {

        try {
            if (mCurrentPage != null)
                mCurrentPage.close();
            if (mPdfRenderer != null)
                mPdfRenderer.close();
            if (mFileDescriptor != null)
                mFileDescriptor.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * API show to particular page index using PdfRenderer
     *
     * @param index
     */
    private void showPage(int index) {
        if (mPdfRenderer == null || mPdfRenderer.getPageCount() <= index
                || index < 0) {
            return;
        }
        // For closing the current page before opening another one.
        try {
            if (mCurrentPage != null) {
                mCurrentPage.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Open page with specified index
        mCurrentPage = mPdfRenderer.openPage(index);
        Bitmap bitmap = Bitmap.createBitmap(mCurrentPage.getWidth(),
                mCurrentPage.getHeight(), Bitmap.Config.ARGB_8888);

        // Pdf page is rendered on Bitmap
        mCurrentPage.render(bitmap, null, null,
                PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        // Set rendered bitmap to ImageView
        pdfView.setImageBitmap(bitmap);
        updateActionBarText();
    }

    /**
     * Background task for listing pdf files
     *
     * @author androidsrc.net
     */
    private class PdfListLoadTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            File files = new File("/sdcard/PDFDemo_AndroidSRC/");
            filelist = files.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return ((name.endsWith(".pdf")));
                }
            });

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub

            if (filelist != null && filelist.length >= 1) {
                ArrayList<String> fileNameList = new ArrayList<>();
                for (int i = 0; i < filelist.length; i++)
                    fileNameList.add(filelist[i].getPath());
                adapter = new ArrayAdapter<>(getApplicationContext(),
                        R.layout.list_item, fileNameList);
                pdfList.setAdapter(adapter);
            } else {
                Toast.makeText(getApplicationContext(),
                        "No pdf file found, Please create new Pdf file",
                        Toast.LENGTH_LONG).show();
                updateView(CurrentView.OPTIONS_LAYOUT);
                updateActionBarText();
            }
        }

    }

    /**
     * Background task to generate pdf from users content
     *
     * @author androidsrc.net
     */
    private class PdfGenerationTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {

            PdfDocument document = new PdfDocument();

            // repaint the user's text into the page
            View content = findViewById(R.id.pdf_content);

            // crate a page description
            int pageNumber = 1;
            PageInfo pageInfo = new PageInfo.Builder(content.getWidth(),
                    content.getHeight() - 20, pageNumber).create();

            // create a new page from the PageInfo
            Page page = document.startPage(pageInfo);

            content.draw(page.getCanvas());

            // do final processing of the page
            document.finishPage(page);

            SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss");
            String pdfName = "pdfdemo"
                    + sdf.format(Calendar.getInstance().getTime()) + ".pdf";

            File outputFile = new File("/sdcard/PDFDemo_AndroidSRC/", pdfName);

            try {
                outputFile.createNewFile();
                OutputStream out = new FileOutputStream(outputFile);
                document.writeTo(out);
                document.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return outputFile.getPath();
        }

        @Override
        protected void onPostExecute(String filePath) {
            if (filePath != null) {
                generatePdf.setEnabled(true);
                pdfContentView.setText("");
                Toast.makeText(getApplicationContext(),
                        "Pdf saved at " + filePath, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "Error in Pdf creation" + filePath, Toast.LENGTH_SHORT).show();
            }
        }
    }
}

5.Buid and Run your Application

We are done. Build and run your application, you can read and create Pdf document within your application.

You may also like...

20 Responses

  1. Asad Mughal says:

    its really a good tutorial

  2. Sunil Singh says:

    can I add textcolor and textstyle in PDF using PDFviewer pls help

  3. daniyal says:

    it is showing errors

  4. Pranav Pal Lekhi says:

    The line ‘outputFile.createNewFile();’ is giving me an IOException. It says ‘ENOENT No such file or directory’. What could I be doing wrong?

  5. Prachi Singh says:

    Hi, thanks a lot for your help! Can you tell me how to zoom-in or zoom-out while displaying a pdf?

  6. Masi Ahmad says:

    Hi i also get the errors

    content.getWidth()
    and content.draw(page.getCanvas());

    And idont know how to call runOnUiThread

  7. Jon says:

    Hi does anyone get a “NullPointerException” on closeOption?

    10-08 16:06:23.001 30249-30249/com.micron.jrobinsonriv.read_pdf E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.micron.jrobinsonriv.read_pdf, PID: 30249
    java.lang.NullPointerException: Attempt to invoke interface method ‘android.view.MenuItem android.view.MenuItem.setVisible(boolean)’ on a null object reference
    at com.micron.jrobinsonriv.read_pdf.Read_pdf_main.updateView(Read_pdf_main.java:249)
    at com.micron.jrobinsonriv.read_pdf.Read_pdf_main.onClick(Read_pdf_main.java:275)
    at android.view.View.performClick(View.java:5702)
    at android.widget.TextView.performClick(TextView.java:10887)
    at android.view.View$PerformClick.run(View.java:22546)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:158)
    at android.app.ActivityThread.main(ActivityThread.java:7237)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

  8. Carlos Sierra says:

    how to use this when your app uses only a webview ( I develop hybrid apps, using html content local storage )

  9. ani says:

    Thank you so much for the sharing. I’m having an issue when trying to put a message dialog. It needs to click “OK” button several times(~2-3 times) to close the dialog.

  10. Mica Kardashian says:

    Como faço pra ler pdf com uma api abaixo da 21?
    quero na versão 4.0

  11. Pavneet Singh says:

    when i click the botton “open pdf” and “create pdf “application is crash !!
    Give me solution…

  12. Abdul Rehman says:

    its has many errors update the code and in how much android app api till it works?

  1. August 30, 2016

    […] create-and-display-pdf-within-android-application String myPdfUrl = "http://example.com/awesome.pdf&quot;; String url = "http://docs.google.com/gview?embedded=true&url=&quot; + myPdfUrl; Log.i(TAG, "Opening PDF: " + url); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl(url); […]

  2. April 20, 2018

    […] Create and Display PDF within Android Application […]

Leave a Reply

Your email address will not be published. Required fields are marked *