Friday 30 December 2016

PowerPoint : PPT Reader



STEP - 1 : Create a New Project

STEP - 2 : Paste  a library to lib folder

Click here to download : itsrts-pptviewer.jar



STEP - 3 : Add dependency to App level Gradle
build.gradle (App)
Inside dependency

compile files('libs/itsrts-pptviewer.jar')


STEP - 4 : Add permission to Manifest

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

STEP - 5 : Paste or Download a ppt into your phone download folder.

STEP - 6 : Inside your activity, paste your code which show ppt file

activity_main.xml

<RelativeLayout 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"    android:padding="@dimen/activity_horizontal_margin"    >
    <com.itsrts.pptviewer.PPTViewer        android:id="@+id/pptviewer"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_marginTop="24dp"        />
</RelativeLayout>

MainActivity.java

import android.os.Environment;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import com.itsrts.pptviewer.PPTViewer;import java.io.File;
public class MainActivity extends AppCompatActivity {

    PPTViewer pptViewer;    String path = null;    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);
        pptViewer = (PPTViewer) findViewById(R.id.pptviewer);
        File f = new File(Environment.getExternalStorageDirectory().getPath(), "/Download/fashion.ppt");

        //  File f = FileUtils.fileFromAsset(MainActivity.this, "junit.ppt");          path = f.getPath().toString();
        pptViewer.setNext_img(R.drawable.next).setPrev_img(R.drawable.prev)
                .setSettings_img(R.drawable.settings)
                .setZoomin_img(R.drawable.zoomin)
                .setZoomout_img(R.drawable.zoomout);        pptViewer.loadPPT(this, path);
    }
}

STEP - 7 : Create a class, which handle the interation between app storage ( Phone or Assets)

FileUtils.java

import android.content.Context;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;
public class FileUtils {

    private FileUtils() {
        // Prevents instantiation    }

    public static File fileFromAsset(Context context, String assetName) throws IOException {
        File outFile = new File(context.getCacheDir(), assetName + "-pdfview.pdf");        if (assetName.contains("/")) {
            outFile.getParentFile().mkdirs();        }
        copy(context.getAssets().open(assetName), outFile);        return outFile;    }

    public static void copy(InputStream inputStream, File output) throws IOException {
        OutputStream outputStream = null;        try {
            outputStream = new FileOutputStream(output);            int read = 0;            byte[] bytes = new byte[1024];            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);            }
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();                }
            } finally {
                if (outputStream != null) {
                    outputStream.close();                }
            }
        }
    }
}



\\\

PDF : Simple PDF Reader by Google



STEP - 1 : Add permission to Manifest
Manifest.xml

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

STEP - 2 : a. Create a New Project

b. Create Assets folder

Go to -  app  ---  right click  ---  new ---  folder ---  Assets Folder ---  Finish

STET - 3 : Copy a pdf file in Assets folder
In my case - Name : "sample.pdf"


STEP - 4 : On Main Activity
a. Move PDF Button - move pdf from assets to storage
 b. View PDF Button - Show PDF after move

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools"     
android:id="@+id/activity_main" 
 android:layout_width="match_parent"     
android:layout_height="match_parent"     
android:paddingBottom="@dimen/activity_vertical_margin" 
 android:paddingLeft="@dimen/activity_horizontal_margin" 
 android:paddingRight="@dimen/activity_horizontal_margin"     
android:paddingTop="@dimen/activity_vertical_margin" 
 android:orientation="vertical"    >
    <Button 
 android:layout_width="match_parent"         
android:layout_height="wrap_content" 
android:text="View PDF"         
android:onClick="viewPDF"         
/> 
<Button 
 android:layout_width="match_parent"         
android:layout_height="wrap_content"         
android:text="Move PDF" 
 android:layout_marginTop="48dp" 
 android:onClick="movePDF"         
/></LinearLayout>

MainActivity.java

import android.app.ProgressDialog; 
import android.content.Context;import android.content.Intent;import android.content.res.AssetManager;import android.os.AsyncTask;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;
import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;
public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);
    }
    public void viewPDF(View view)
    {
        Intent pdfIntent = new Intent(MainActivity.this, PDFViewActivity.class);        startActivity(pdfIntent);    }
    public void movePDF(View view)
    {
        AsyncTaskRunner taskRunner = new AsyncTaskRunner(MainActivity.this);        taskRunner.execute();    }



    //  ---------------------------------------------------for image transfer    public  class AsyncTaskRunner extends AsyncTask<Void,String,Void> {

        ProgressDialog progressDialog;        private Context ctx;        public AsyncTaskRunner(Context myContext) {
            this.ctx = myContext;        }
        @Override        protected void onPreExecute() {
            super.onPreExecute();            progressDialog = ProgressDialog.show(ctx,"Moving File",  "Processing...");        }
        @Override        protected Void doInBackground(Void... voids) {

            publishProgress("Processing..."); // Calls onProgressUpdate()            try {
                copyDirorfileFromAssetManager("AllFile", "Pdf");            } catch (IOException e) {
                e.printStackTrace();            }
            return null;        }

        @Override        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);            progressDialog.dismiss();        }

        public String copyDirorfileFromAssetManager(String arg_assetDir, String arg_destinationDir) throws IOException {
            String dest_dir_path =  addLeadingSlash(arg_destinationDir);            File dest_dir = new File(ctx.getExternalFilesDir(null),  dest_dir_path);            createDir(dest_dir);            AssetManager asset_manager = ctx.getAssets();            String[] files = asset_manager.list(arg_assetDir);            for (int i = 0; i < files.length; i++) {
                String abs_asset_file_path = addTrailingSlash(arg_assetDir) + files[i];                String sub_files[] = asset_manager.list(abs_asset_file_path);                if (sub_files.length == 0) {
                    String dest_file_path = addTrailingSlash(dest_dir_path) + files[i];                    File dest_file = new File(ctx.getExternalFilesDir(null),  dest_file_path);                    System.out.print(dest_file);                    String testpath = String.valueOf(dest_file);                    copyAssetFile(abs_asset_file_path, testpath);                } else {
                    copyDirorfileFromAssetManager(abs_asset_file_path, addTrailingSlash(arg_destinationDir) + files[i]);                }
            }
            return dest_dir_path;        }

        public void copyAssetFile(String assetFilePath, String destinationFilePath) throws IOException {

            InputStream in = ctx.getAssets().open(assetFilePath);            OutputStream out = new FileOutputStream(destinationFilePath);            byte[] buf = new byte[1024];            int len;            while ((len = in.read(buf)) > 0)
                out.write(buf, 0, len);            in.close();            out.close();        }

        public String addTrailingSlash(String path) {
            if (path.charAt(path.length() - 1) != '/') {
                path += "/";            }
            return path;        }

        public String addLeadingSlash(String path) {
            if (path.charAt(0) != '/') {
                path = "/" + path;            }
            return path;        }

        public void createDir(File dir) throws IOException {
            if (dir.exists()) {
                if (!dir.isDirectory()) {
                    throw new IOException("Can't create directory, a file is in the way");                }
            } else {
                dir.mkdirs(); 
        if (!dir.isDirectory()) {
                    throw new IOException("Unable to create directory");                }
            }
        }
    }
}


STEP - 5 : Create a activity, which is work like as a container of pdf


activity_pdfview.xml

<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/container"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity"    tools:ignore="MergeRootFrame" />

PDFViewActivity.java

package pdfreader2.pdf.app.com.pdffromstorage;
import android.app.Activity;import android.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;
public class PDFViewActivity extends Activity {

    public static final String FRAGMENT_PDF_RENDERER_BASIC = "pdf_renderer_basic";
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_pdfview);        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PdfRendererBasicFragment(),                            FRAGMENT_PDF_RENDERER_BASIC)
                    .commit();        }
    }
    
}

STEP - 6 : Create a fragment, which retrieve data from storage and show on view

a. create a class, where your MainActivity.java exist

PdfRendererBasicFragment.java

import android.app.Activity;import android.app.Fragment;import android.content.Context;import android.graphics.Bitmap;import android.graphics.pdf.PdfRenderer;import android.os.Bundle;import android.os.ParcelFileDescriptor;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast;
import java.io.File;import java.io.IOException;
public class PdfRendererBasicFragment extends Fragment implements View.OnClickListener {

    private static final String STATE_CURRENT_PAGE_INDEX = "current_page_index";
    private ParcelFileDescriptor mFileDescriptor;
    private PdfRenderer mPdfRenderer;
    private PdfRenderer.Page mCurrentPage;
    private ImageView mImageView;
    private Button mButtonPrevious;
    private Button mButtonNext;
    Context context;    public PdfRendererBasicFragment() {
    }

    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_pdf_renderer_basic, container, false);    }

    @Override    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);        // Retain view references.        mImageView = (ImageView) view.findViewById(R.id.image);        mButtonPrevious = (Button) view.findViewById(R.id.previous);        mButtonNext = (Button) view.findViewById(R.id.next);        // Bind events.        mButtonPrevious.setOnClickListener(this);        mButtonNext.setOnClickListener(this);        // Show the first page by default.        int index = 0;        // If there is a savedInstanceState (screen orientations, etc.), we restore the page index.        if (null != savedInstanceState) {
            index = savedInstanceState.getInt(STATE_CURRENT_PAGE_INDEX, 0);        }
        showPage(index);    }

    @Override    public void onAttach(Activity activity) {
        super.onAttach(activity);        try {
            openRenderer(activity);        } catch (IOException e) {
            e.printStackTrace();            Toast.makeText(activity, "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();            activity.finish();        }
    }

    @Override    public void onDetach() {
        try {
            closeRenderer();        } catch (IOException e) {
            e.printStackTrace();        }
        super.onDetach();    }

    @Override    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);        if (null != mCurrentPage) {
            outState.putInt(STATE_CURRENT_PAGE_INDEX, mCurrentPage.getIndex());        }
    }

    private void openRenderer(Context context) throws IOException {
        // In this sample, we read a PDF from the assets directory.        //mFileDescriptor = context.getAssets().openFd("sample.pdf").getParcelFileDescriptor();        //File f = FileUtils.fileFromAsset(context, "AllFile/Pdf/sample.pdf");        File dest_dir = new File(getActivity().getExternalFilesDir(null), "/Pdf/Pdf/sample.pdf");        // ParcelFileDescriptor pfd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);        mFileDescriptor = ParcelFileDescriptor.open(dest_dir, ParcelFileDescriptor.MODE_READ_ONLY);       //  mFileDescriptor = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);        // This is the PdfRenderer we use to render the PDF.        mPdfRenderer = new PdfRenderer(mFileDescriptor);    }


    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);        getActivity().setTitle(getString(R.string.app_name));    }

    /**     * 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;            }
        }
    }

}

b. create a layout in  res--->layout, which is view of pdf
fragment_pdf_renderer_basic.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"    android:orientation="vertical"    >
    <ImageView        android:id="@+id/image"        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="@string/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="@string/next" />    </LinearLayout>
</LinearLayout>


STEP - 6 : Create a class, which handle the interation between app storage ( Phone or Assets)

FileUtils.java

import android.content.Context;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;
public class FileUtils {

    private FileUtils() {
        // Prevents instantiation    }

    public static File fileFromAsset(Context context, String assetName) throws IOException {
        File outFile = new File(context.getCacheDir(), assetName + "-pdfview.pdf");        if (assetName.contains("/")) {
            outFile.getParentFile().mkdirs();        }
        copy(context.getAssets().open(assetName), outFile);        return outFile;    }

    public static void copy(InputStream inputStream, File output) throws IOException {
        OutputStream outputStream = null;        try {
            outputStream = new FileOutputStream(output);            int read = 0;            byte[] bytes = new byte[1024];            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);            }
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();                }
            } finally {
                if (outputStream != null) {
                    outputStream.close();                }
            }
        }
    }
}



\\\

Wednesday 28 December 2016

PDF : PDF READER Under Apache


Caution : It's install one aditional app to show PDF

STEP - 1 : First Create a new application in android studio
File --> New ---> New Project ---> ' Enter App Name and Package Name'  ---> Next  ---> Target Devices  ---> Next  --->  Add an Activity to Mobile ( Choose Empty Activity) ---> Next  --->
Activity Name  ---> Finish.

 STEP - 2 : First, Download the sample module from below link
////// https://drive.google.com/file/d/0BzTjcv17QPlwY25HY2FNb0hzREE/view?usp=sharing
After download,import this module in app.
File ---> New  --->  Import Module  --->   Click on [...] three dot icon to browse module  ---->  Select it  ---> OK

After few minute,  it import the module

STEP - 3 : Now, add dependency to your Project level gradle

classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'

Project Gradle : Before
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'       
        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir}


Project Gradle : After added dependency

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir}



STEP - 4 : Paste below code in your activity page

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="file.download.app.com.pdfreader1.MainActivity">
    <Button        android:id="@+id/btn1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Click to view PDF"        /></RelativeLayout>


MainActivity.java

import android.app.Activity;import android.content.Intent;import android.content.pm.PackageManager;import android.os.Bundle;import android.view.View;import android.widget.Button;

public class MainActivity extends Activity {


    Button btnPDF;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);
        btnPDF = (Button)findViewById(R.id.btn1);        btnPDF.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                Intent i;                PackageManager manager = getPackageManager();                try {
                    i = manager.getLaunchIntentForPackage("com.github.barteksc.sample");                    if (i == null)
                        throw new PackageManager.NameNotFoundException();                    i.addCategory(Intent.CATEGORY_LAUNCHER);                    i.putExtra("file","sample.pdf");                    startActivity(i);                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();                }

            }
        });

    }
}


STEP - 5 : Now Run the app then you unable to see 'MainActivity' because Sample Module Activity ' PDFViewActivity' replaced it, like this -



STEP - 6 : To show first, App MainActivity, need to configure app ( In EditConfiguration ).
follow the image

A. Click on sample ( Left tab of Run )




B. Now, Click  on Edit Configuration



C. Open Genral Tab  --->  Module   ---->  Click on Sample




D. Select App  --->OK















////