Aandroid pdf viewer native

Android pdf viewer Without any library using android PdfRenderer class to view pdf file on android version api 19+.

Android View XML file

 

Activity.
 
package com.tt.sharedprint;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.pdf.PdfRenderer;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.print.PrintManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.tt.sharedprint.customview.CustomPrintDocumentAdapter;
import com.tt.sharedprint.customview.TouchImageView;

public class ViewActivity extends Activity implements View.OnClickListener{//PdfViewerActivity
	
	WebView webView1;
	
	AQuery aq;
	ProgressDialog prgDialog;
	String url = "http://kaushalprajapati.net/wp-content/uploads/2016/12/test.pdf";// "http://programmerguru.com/android-tutorial/wp-content/uploads/2014/01/jai_ho.mp3";
//	String url = "https://ttdrive.s3-us-west-2.amazonaws.com/277/CUT%20OF%20MARKS%20ENGINEERING.pdf?AWSAccessKeyId=AKIAJUIU5SYUB6NPS2LQ&Expires=1465305646&Signature=HPRUsmKaBs8KWpJKi7sQmqlbQBg%3D";
//	String url = "https://ttdrive.s3-us-west-2.amazonaws.com/277/D_19.PDF?AWSAccessKeyId=AKIAJUIU5SYUB6NPS2LQ&Expires=1465305860&Signature=NrqVGbOeNoVPj9YaB%2FD%2F4Md%2F7KE%3D";
	 /**
     * Key string for saving the state of current page index.
     */
    private static final String STATE_CURRENT_PAGE_INDEX = "current_page_index";

    /**
     * File descriptor of the PDF.
     */
    private ParcelFileDescriptor mFileDescriptor;

    /**
     * {@link android.graphics.pdf.PdfRenderer} to render the PDF.
     */
    private PdfRenderer mPdfRenderer;

    /**
     * Page that is currently shown on the screen.
     */
    private PdfRenderer.Page mCurrentPage;

    /**
     * {@link android.widget.ImageView} that shows a PDF page as a {@link android.graphics.Bitmap}
     */
    private ImageView mImageView;

    /**
     * {@link android.widget.Button} to move to the previous page.
     */
    private Button mButtonPrevious;

    /**
     * {@link android.widget.Button} to move to the next page.
     */
    private Button mButtonNext;
    Activity activity;
    int index = 0;
    File fileObj;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view);
		activity = this;
 

		/*String myPdfUrl = "http://kaushalprajapati.net/wp-content/uploads/2016/12/test.pdf";
		String url = "http://docs.google.com/gview?embedded=true&url=" + myPdfUrl;
		Log.i("", "Opening PDF: " + url);
		webView1.getSettings().setJavaScriptEnabled(true); 
		webView1.loadUrl(url);*/
		
//		File ext = Environment.getExternalStorageDirectory();
//		File target = new File(ext, "pgfolder/jai_ho.mp3");
//		ProgressDialog prgDialog = new ProgressDialog(this);
//		prgDialog.setMessage("Downloading MP3 from Internet. Please wait...");
//		prgDialog.setIndeterminate(false);
//		prgDialog.setMax(100);      
//		prgDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//		prgDialog.setCancelable(false);
		
		aq = new AQuery(this);
		aq.id(R.id.btnProgressBar).clicked(this, "downloadSongandPlay");
		 
		mImageView = (TouchImageView) findViewById(R.id.image);
        mButtonPrevious = (Button) findViewById(R.id.previous);
        mButtonNext = (Button) findViewById(R.id.next);
        // Bind events.
        mButtonPrevious.setOnClickListener(this);
        mButtonNext.setOnClickListener(this);
        // Show the first page by default.
        
        // If there is a savedInstanceState (screen orientations, etc.), we restore the page index.
        if (null != savedInstanceState) {
            index = savedInstanceState.getInt(STATE_CURRENT_PAGE_INDEX, 0);
        }
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.image_print, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			try {
				if(fileObj!=null){
					PrintManager printManager = (PrintManager)getSystemService(Context.PRINT_SERVICE);
		            String jobName =  " Document";
		            CustomPrintDocumentAdapter pda = new CustomPrintDocumentAdapter(fileObj);
		//            new PrintAttributes.Builder().setMediaSize(MediaSize.ISO_A4);
		            printManager.print(jobName, pda, null);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	    @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	@Override
	protected void onDestroy() {
		try {
            closeRenderer();
        } catch (IOException e) {
            e.printStackTrace();
        }
		super.onDestroy();
	}
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (null != mCurrentPage) {
            outState.putInt(STATE_CURRENT_PAGE_INDEX, mCurrentPage.getIndex());
        }
    }
	  // AQuery button click callback method
    public void downloadSongandPlay(View v) {
        // Mp3 file location in SD card
//        File file = new File(Environment.getExternalStorageDirectory().getPath()+"/pgfolder/test.pdf");
        File file = new  File(getCacheDir()+"/pgfolder/test.pdf", "MyCache");
        deleteRecursive(file);
        // Get SD card location
        File ext = new  File(getCacheDir(), "MyCache");//Environment.getExternalStorageDirectory();
        // Target location where downloaded file to be stored
        File target = new File(ext, "/pgfolder/test.pdf");
 
        // Disable button in order to avoid multiple button hits
        aq.id(R.id.btnProgressBar).enabled(false);
        // When Mp3 File exists under SD card
        if (file.exists()) {
//            Toast.makeText(getApplicationContext(), "File already exist under SD card, playing Music", Toast.LENGTH_LONG).show();
//            Intent intent = new Intent(this, PdfViewer.class);
//			 Uri URL = Uri.fromFile(file);
//			 intent.putExtra(PdfViewer.EXTRA_PDFFILENAME, file.getAbsoluteFile().getPath() );
//			 startActivity(intent);
            try {
	            openRenderer(activity,file);
	        } catch (IOException e) {
	            e.printStackTrace();
	            Toast.makeText(activity, "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
	            finish();
	        }
	        showPage(index);
        // If the Music File doesn't exist in SD card (Not yet downloaded)
        } else {
            Toast.makeText(getApplicationContext(), "File doesn't exist under SD Card, downloading Mp3 from Internet", Toast.LENGTH_LONG).show();
            prgDialog = new ProgressDialog(this); // Instantiate Progress Dialog Bar
            prgDialog.setMessage("Downloading MP3 from Internet. Please wait..."); // Set Progress Dialog Bar message
            prgDialog.setIndeterminate(false);  
            prgDialog.setMax(100); // Progress Bar max limit
            prgDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // Progress Bar style
            prgDialog.setCancelable(false); // Progress Bar cannot be cancelable
            // Display progress dialog bar and initiate download of Mp3 file
            aq.progress(prgDialog).download(url, target, new AjaxCallback() {
                // Once download is complete
                public void callback(String url, File file, AjaxStatus status) {
                    // If file does exist
                    if (file != null) {
//                    	 Intent intent = new Intent(ViewActivity.this, PdfViewer.class);
//            			 Uri URL = Uri.fromFile(file);
//            			 intent.putExtra(PdfViewer.EXTRA_PDFFILENAME, URL);
//            			 intent.putExtra(PdfViewer.EXTRA_PDFFILENAME, file.getAbsoluteFile().getPath());
//            			 Log.d("URL", "URL " + URL);
//            			 Log.d("URL", "URL " + file.getAbsoluteFile());
//            			 startActivity(intent);
            			 
            			 try {
            				 fileObj = file;
            		            openRenderer(activity,file);
            		        } catch (IOException e) {
            		            e.printStackTrace();
            		            Toast.makeText(activity, "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
            		            finish();
            		        }
            		        showPage(index);
            		        
//                        playMusic();
                    // If file doesn't exist display error message
                    } else {
                        Toast.makeText(aq.getContext(), "Error occured: Status" + status,
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }
    void deleteRecursive(File fileOrDirectory) {
        if (fileOrDirectory.isDirectory())
            for (File child : fileOrDirectory.listFiles())
                deleteRecursive(child);

        fileOrDirectory.delete();
    }
    ////////////////////////////////////////////////////

    /**
     * Sets up a {@link android.graphics.pdf.PdfRenderer} and related resources.
     */
    private void openRenderer(Context context, File file) throws IOException {
        // In this sample, we read a PDF from the assets directory.
//        mFileDescriptor = context.getAssets().open("sample.pdf").getParcelFileDescriptor();
        // This is the PdfRenderer we use to render the PDF.
//        mPdfRenderer = new PdfRenderer(mFileDescriptor);
//        File file = new FileUtils().fileFromAsset(context, "test.pdf");
        mFileDescriptor = ParcelFileDescriptor.open(file,ParcelFileDescriptor.MODE_READ_ONLY); 
        mPdfRenderer = new PdfRenderer(mFileDescriptor);

    }

    /**
     * Closes the {@link android.graphics.pdf.PdfRenderer} and related resources.
     *
     * @throws java.io.IOException When the PDF file cannot be closed.
     */
    private void closeRenderer() throws IOException {
        if (null != mCurrentPage) {
            mCurrentPage.close();
        }
        mPdfRenderer.close();
        mFileDescriptor.close();
    }

    /**
     * Shows the specified page of PDF to the screen.
     *
     * @param index The page index.
     */
    private void showPage(int index) {
        if (mPdfRenderer.getPageCount() <= index) {
            return;
        }
        // Make sure to close the current page before opening another one.
        if (null != mCurrentPage) {
            mCurrentPage.close();
        }
        // Use `openPage` to open a specific page in PDF.
        mCurrentPage = mPdfRenderer.openPage(index);
        // Important: the destination bitmap must be ARGB (not RGB).
        Bitmap bitmap = Bitmap.createBitmap(mCurrentPage.getWidth(), mCurrentPage.getHeight(),
                Bitmap.Config.ARGB_8888);
        // Here, we render the page onto the Bitmap.
        // To render a portion of the page, use the second and third parameter. Pass nulls to get
        // the default result.
        // Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
        mCurrentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        // We are ready to show the Bitmap to user.
        mImageView.setImageBitmap(bitmap);
        updateUi();
    }

    /**
     * Updates the state of 2 control buttons in response to the current page index.
     */
    private void updateUi() {
        int index = mCurrentPage.getIndex();
        int pageCount = mPdfRenderer.getPageCount();
        mButtonPrevious.setEnabled(0 != index);
        mButtonNext.setEnabled(index + 1 < pageCount);
        setTitle(getString(R.string.app_name_with_index, index + 1, pageCount));
    }

    /**
     * Gets the number of pages in the PDF. This method is marked as public for testing.
     *
     * @return The number of pages.
     */
    public int getPageCount() {
        return mPdfRenderer.getPageCount();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.previous: {
                // Move to the previous page
                showPage(mCurrentPage.getIndex() - 1);
                break;
            }
            case R.id.next: {
                // Move to the next page
                showPage(mCurrentPage.getIndex() + 1);
                break;
            }
        }
    }
	 
}
</pre>
&nbsp;
 

Add a Comment