45

I need to convert PDFfile(PDF page) into a Bitmap(or Image file) in Android.

1.Used Pdfbox jar from Apache. But it uses some java classes that is not supported in android. 2. Tried Itext jar which converts image to pdf(I need its reverse operation) Like that I have tried many jars. But no positive result.

byte[] bytes;
    try {

        File file = new File(this.getFilesDir().getAbsolutePath()+"/2010Q2_SDK_Overview.pdf");
        FileInputStream is = new FileInputStream(file);

        // Get the size of the file
        long length = file.length();
        bytes = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }


        ByteBuffer buffer = ByteBuffer.NEW(bytes);
        String data = Base64.encodeToString(bytes, Base64.DEFAULT);
        PDFFile pdf_file = new PDFFile(buffer);
        PDFPage page = pdf_file.getPage(2);

        RectF rect = new RectF(0, 0, (int) page.getBBox().width(),
                (int) page.getBBox().height());
      //  Bitmap bufferedImage = Bitmap.createBitmap((int)rect.width(), (int)rect.height(),
         //        Bitmap.Config.ARGB_8888);

        Bitmap image = page.getImage((int)rect.width(), (int)rect.height(), rect);
        FileOutputStream os = new FileOutputStream(this.getFilesDir().getAbsolutePath()+"/pdf.jpg");
        image.compress(Bitmap.CompressFormat.JPEG, 80, os);

       // ((ImageView) findViewById(R.id.testView)).setImageBitmap(image);

I am getting the Image File, enter image description here

Instead of, enter image description here

package com.test123;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import net.sf.andpdf.nio.ByteBuffer;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.os.Bundle;
import android.util.Base64;

public class Test123Activity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        byte[] bytes;
        try {

            File file = new File(this.getFilesDir().getAbsolutePath()+"/2010Q2_SDK_Overview.pdf");
            FileInputStream is = new FileInputStream(file);

            // Get the size of the file
            long length = file.length();
            bytes = new byte[(int) length];
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
            }


            ByteBuffer buffer = ByteBuffer.NEW(bytes);
            String data = Base64.encodeToString(bytes, Base64.DEFAULT);
            PDFFile pdf_file = new PDFFile(buffer);
            PDFPage page = pdf_file.getPage(2);

            RectF rect = new RectF(0, 0, (int) page.getBBox().width(),
                    (int) page.getBBox().height());
          //  Bitmap bufferedImage = Bitmap.createBitmap((int)rect.width(), (int)rect.height(),
             //        Bitmap.Config.ARGB_8888);

            Bitmap image = page.getImage((int)rect.width(), (int)rect.height(), rect);
            FileOutputStream os = new FileOutputStream(this.getFilesDir().getAbsolutePath()+"/pdf.jpg");
            image.compress(Bitmap.CompressFormat.JPEG, 80, os);

            //((ImageView) findViewById(R.id.testView)).setImageBitmap(image);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Else, any other way to display pdf file in android using function inbuilt within application?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Neela
  • 1,328
  • 4
  • 23
  • 45
  • We can convert the pdf to image using awt tools in java.but awt is not supported by android.i am also using itext..if u know python u can convert pdf to bitmap using ghostscript. –  Jan 11 '12 at 06:03
  • I dont know python.. Is there any way to do it in java? – Neela Jan 11 '12 at 06:19
  • Please see the above code.. I have used the jar from the link, https://github.com/jblough/Android-Pdf-Viewer-Library/blob/master/PdfViewer.jar I able to convert the PDFpage into jpg file. But the converted image is partially converted. I dont know where I am wrong? – Neela Jan 11 '12 at 06:25
  • what is the code u r giving?is this working? –  Jan 11 '12 at 06:31
  • Its working in the sense, I am getting the first image instead of second one. – Neela Jan 11 '12 at 06:38
  • i am getting some errors when i am going to import the project android-pdf-viewer-library in my eclipse –  Jan 11 '12 at 06:44
  • please give me the full source code –  Jan 11 '12 at 06:45
  • Create a new android project, Include the above code in your activity class. Add a PDFViewer.jar file from the downloaded library to your buildpath. – Neela Jan 11 '12 at 06:55
  • please share the source code.u are giving only try block only –  Jan 11 '12 at 07:12
  • I have only the above activity class in my project and the PDFViewer.jar linked to its buildpath. – Neela Jan 11 '12 at 07:17
  • i am getting some error in base64.. The import android.util.Base64 cannot be resolved –  Jan 11 '12 at 07:25
  • Base64 is exists only available from the apilevel 8 (2.2), Anyway that is not used here, Forgot to comment it. You can remove/comment it. – Neela Jan 11 '12 at 07:28
  • how can u see the image file.where is it stored that image file.here i got a blank screen –  Jan 11 '12 at 07:34
  • You can find it in File Explorer in the path "/data/data/com.test123/files/". Get the file explorer from "Window->Show View->File Explorer". you got same page in the sense? blank page or pdf page? – Neela Jan 11 '12 at 08:13
  • For the input pdf file save any pdf file in the location "/data/data/com.test123/files/". And then replace file name in the code. For saving this into file, go to File Explorer and to keep the selection on files folder under the path given above. Then you can see the Mobile icon on the top. Click that, and browse for particular pdf file and then click ok. – Neela Jan 11 '12 at 08:19
  • Go to this answer, https://stackoverflow.com/questions/10698360/how-to-convert-a-pdf-page-to-an-image-in-android/63684103#63684103 – Naimatullah Sep 01 '20 at 08:37

7 Answers7

29

I solved this issue. it's as simple as letting the device have time to render each page.

To fix this all you have to do is change

PDFPage page = pdf_file.getPage(2);

to

PDFPage page = pdf_file.getPage(2, true);

Firstly to view a PDF in Android you have to convert the PDF into images then display them to the user. (I am going to use a webview)

So to do this we need this library. It is my edited version of this git.

After you have imported the library into your project you need to create your activity.

The XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
            android:id="@+id/webView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</LinearLayout>

The java:

//Imports:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.webkit.WebView;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFImage;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFPaint;
import net.sf.andpdf.nio.ByteBuffer;
import net.sf.andpdf.refs.HardReference;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

//Globals:
private WebView wv;
private int ViewSize = 0;

//OnCreate Method:
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Settings
    PDFImage.sShowImages = true; // show images
    PDFPaint.s_doAntiAlias = true; // make text smooth
    HardReference.sKeepCaches = true; // save images in cache

    //Setup webview
    wv = (WebView)findViewById(R.id.webView1);
    wv.getSettings().setBuiltInZoomControls(true);//show zoom buttons
    wv.getSettings().setSupportZoom(true);//allow zoom
    //get the width of the webview
    wv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
    {
        @Override
        public void onGlobalLayout()
        {
            ViewSize = wv.getWidth();
            wv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
    });

    try
    {
        File file = new File(Environment.getExternalStorageDirectory().getPath() + "/randompdf.pdf");
        RandomAccessFile f = new RandomAccessFile(file, "r");
        byte[] data = new byte[(int)f.length()];
        f.readFully(data);
        pdfLoadImages(data);
    }
    catch(Exception ignored)
    {
    }
}

//Load Images:
private void pdfLoadImages(final byte[] data)
{
    try
    {
        // run async
        new AsyncTask<Void, Void, String>()
        {
            // create and show a progress dialog
            ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "", "Opening...");

            @Override
            protected void onPostExecute(String html)
            {
                //after async close progress dialog
                progressDialog.dismiss();
                //load the html in the webview
                wv.loadDataWithBaseURL("", html, "text/html","UTF-8", "");
            }

            @Override
            protected String doInBackground(Void... params)
            {
                try
                {
                    //create pdf document object from bytes
                    ByteBuffer bb = ByteBuffer.NEW(data);
                    PDFFile pdf = new PDFFile(bb);
                    //Get the first page from the pdf doc
                    PDFPage PDFpage = pdf.getPage(1, true);
                    //create a scaling value according to the WebView Width
                    final float scale = ViewSize / PDFpage.getWidth() * 0.95f;
                    //convert the page into a bitmap with a scaling value
                    Bitmap page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true);
                    //save the bitmap to a byte array
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    page.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    byte[] byteArray = stream.toByteArray();
                    stream.reset();
                    //convert the byte array to a base64 string
                    String base64 = Base64.encodeToString(byteArray, Base64.NO_WRAP);
                    //create the html + add the first image to the html
                    String html = "<!DOCTYPE html><html><body bgcolor=\"#b4b4b4\"><img src=\"data:image/png;base64,"+base64+"\" hspace=10 vspace=10><br>";
                    //loop though the rest of the pages and repeat the above
                    for(int i = 2; i <= pdf.getNumPages(); i++)
                    {
                        PDFpage = pdf.getPage(i, true);
                        page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true);
                        page.compress(Bitmap.CompressFormat.PNG, 100, stream);
                        byteArray = stream.toByteArray();
                        stream.reset();
                        base64 = Base64.encodeToString(byteArray, Base64.NO_WRAP);
                        html += "<img src=\"data:image/png;base64,"+base64+"\" hspace=10 vspace=10><br>";
                    }
                    stream.close();
                    html += "</body></html>";
                    return html;
                }
                catch (Exception e)
                {
                    Log.d("error", e.toString());
                }
                return null;
            }
        }.execute();
        System.gc();// run GC
    }
    catch (Exception e)
    {
        Log.d("error", e.toString());
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
string.Empty
  • 10,393
  • 4
  • 39
  • 67
  • this solution works, but images aren't drawn in the bitmap, even with `.sShowImages`set to `true`, and your version of the library. Do you have any idea why this might happen? – Agos Jun 27 '13 at 14:20
  • i have downloaded your library, now please tell me, what imports do you use? – Asiimwe Jul 09 '13 at 17:05
  • why not just use the add missing imports feature that comes with your IDE? – string.Empty Jul 09 '13 at 17:29
  • I figured it out but couldn't edit quick enough, can this library also be used to covert bitmaps to pdf? – Asiimwe Jul 09 '13 at 17:33
  • i dont think so. but there are other libraries that can. – string.Empty Jul 09 '13 at 17:35
  • you've just changed the code i had copied, whats new in this one? – Asiimwe Jul 09 '13 at 18:02
  • its more optimized with more info, the admin removed my code so i put it back. – string.Empty Jul 09 '13 at 19:06
  • the images of the PDF pages, those which have text dont come out as sharp? anything i can do to improve the image quality? – Asiimwe Jul 10 '13 at 20:45
  • Not that i know of. you could ask on github, but i doubt you will get a response as the creator of the library is inactive, his last comment was 10 months ago. This thead is the most active: https://github.com/jblough/Android-Pdf-Viewer-Library/issues/14 – string.Empty Jul 11 '13 at 07:23
  • yeah, it suggests to the GC that it would be a good time to run. it will either do nothing or clear the memory. – string.Empty Jul 12 '13 at 18:02
  • 1
    PDFFile pdf = new PDFFile(bb); in the row E/CounterA: java.lang.NullPointerException. How to fix this? – Jamshid Sep 17 '13 at 10:50
  • @nicolastyler earlier someone asked for the imports. Could u list em anyway. Vim doesn't have add missing import :) thanks for the answer it might be my ticket through – baash05 Sep 29 '13 at 10:29
  • Edited the answer, added imports. That should be all you need, You should be able to find all these imports without much effort even without using the auto adding of imports. – string.Empty Sep 29 '13 at 21:37
  • is webview really necessary??? can't we use any other thing to show the pdf? and the images are coming completely different, is any other way possible? – Ari Oct 22 '13 at 11:51
  • no a webview is not necessary but this library extracts images, a webview is just the best viewer for the images. – string.Empty Oct 22 '13 at 18:32
  • I am getting error in this 2 lines NEW is giving error in first line and getImage method is giving error in the second line ByteBuffer bb = ByteBuffer.NEW(channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size())); Bitmap page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true); So can any body tell me how to resolve it... – Faiz Anwar Mar 26 '14 at 12:53
  • @NicolasTyler I am still getting that java.awt import issue with android while doing PDFPage.getImage...how did u guys solved it?/ – sheetal May 05 '14 at 12:11
  • @NicolasTyler thanks for your answer all is working fine but I am not able to find bitmap images in my device. Plz provide the path to find Images. Plz help – Abhishek Tamta Sep 22 '14 at 16:04
  • @AbhishekTamta in the example above the images are not stored. As this would make the loading time really long. – string.Empty Sep 23 '14 at 06:42
  • @NicolasTyler I am getting java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:94) error using your code, It points inside for loop while creating html string, can you suggest me any fix for it? – Shrikant Sep 23 '14 at 07:31
  • 1
    @NicolasTyler I know in above example the images are not stored please tell me where I show the converted bitmap because in Activity this is showing only blank Layout. I have to put PDF files in assets folder or somewhere else? Please suggest. – Abhishek Tamta Sep 23 '14 at 10:23
  • This doesn't work! Bitmap page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true); is a jwt method!! – Prachi Feb 12 '15 at 06:02
  • @NicolasTyler I made two projects and I used both versions of library but I have two different problems, using your version the font is broken, using default version of library the images don't appear. Can you help me to solve the problem with font from your version? I mention that in both projects I used the code snippets from your post. – roroinpho21 Apr 07 '16 at 11:43
  • If the pdf file has 2 or more pages will it still work? I tried using it but everytime i choose the pdf file that has more pages the app crashes. Please help me. Thank you. – Kairi San Apr 10 '16 at 01:10
  • I cannot go inside the `for` condition. – Kairi San Apr 10 '16 at 02:27
  • I found out the reason why it crashes it can't handle a lot of pages for example 30 pages of the PDF file. is the any solution to it? thanks – Kairi San Apr 10 '16 at 04:00
  • I havn't worked on this in a few years, @roroinpho21 if fiddling with the `PDFPaint.s_doAntiAlias` doesnt work, then i dont know what is wrong. @Kairi San It might be that your device runs out of memory. The above code is just an example and you could create a pager implementation instead to save ram by only showing one page at a time. – string.Empty Apr 11 '16 at 07:06
  • Thanks for your answer @NicolasTyler. Finally, I manage to solve the problem using this [post](https://github.com/jblough/Android-Pdf-Viewer-Library/issues/14#issuecomment-16795791). – roroinpho21 Apr 11 '16 at 07:30
20

I know this question is old but I ran into this problem last week, and none of the answers really worked for me.

Here's how I solve this issue without using third-party libraries.

Based on the code from android developers site using android's PDFRenderer class (API 21+), I wrote the following method:

private  ArrayList<Bitmap> pdfToBitmap(File pdfFile) {
    ArrayList<Bitmap> bitmaps = new ArrayList<>();

    try {
        PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY));

        Bitmap bitmap;
        final int pageCount = renderer.getPageCount();
        for (int i = 0; i < pageCount; i++) {
            PdfRenderer.Page page = renderer.openPage(i);

            int width = getResources().getDisplayMetrics().densityDpi / 72 * page.getWidth();
            int height = getResources().getDisplayMetrics().densityDpi / 72 * page.getHeight();
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

            page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);

            bitmaps.add(bitmap);

            // close the page
            page.close();

        }

        // close the renderer
        renderer.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return bitmaps;

}

the method returns an array of bitmaps, one bitmap for every page in the pdf file.

The height and width are calculated based on this answer to create better-quality images.

Community
  • 1
  • 1
Diego Ruiz
  • 300
  • 1
  • 4
  • 7
2

This question is a bit old, but I had to do the same today, so this is my solution:

/**
 * Use this to load a pdf file from your assets and render it to a Bitmap.
 * 
 * @param context
 *            current context.
 * @param filePath
 *            of the pdf file in the assets.
 * @return a bitmap.
 */
@Nullable
public static Bitmap renderToBitmap(Context context, String filePath) {
    Bitmap bi = null;
    InputStream inStream = null;
    try {
        AssetManager assetManager = context.getAssets();
        Log.d(TAG, "Attempting to copy this file: " + filePath);
        inStream = assetManager.open(filePath);
        bi = renderToBitmap(context, inStream);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            inStream.close();
        } catch (IOException e) {
            // do nothing because the stream has already been closed
        }
    }
    return bi;
}

/**
 * Use this to render a pdf file given as InputStream to a Bitmap.
 * 
 * @param context
 *            current context.
 * @param inStream
 *            the inputStream of the pdf file.
 * @return a bitmap.
 * @see https://github.com/jblough/Android-Pdf-Viewer-Library/
 */
@Nullable
public static Bitmap renderToBitmap(Context context, InputStream inStream) {
    Bitmap bi = null;
    try {
        byte[] decode = IOUtils.toByteArray(inStream);
        ByteBuffer buf = ByteBuffer.wrap(decode);
        PDFPage mPdfPage = new PDFFile(buf).getPage(0);
        float width = mPdfPage.getWidth();
        float height = mPdfPage.getHeight();
        RectF clip = null;
        bi = mPdfPage.getImage((int) (width), (int) (height), clip, true,
                true);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            inStream.close();
        } catch (IOException e) {
            // do nothing because the stream has already been closed
        }
    }
    return bi;
}

Also, I am using this library. And my pdf file contains only one page and is an image, may be in other cases, you have to update your code.

I hope this will help someone.

ahmed_khan_89
  • 2,755
  • 26
  • 49
  • Hi, is there any library like this but instead of clicking the button previous and next the user can scroll between pages of PDF? I'm using the same library. – Kairi San Apr 10 '16 at 00:45
  • sorry I have no idea, I just needed to convert pdf images to bitmaps. I would recommend to create a new question about pdf pagination... good luck. – ahmed_khan_89 Apr 11 '16 at 11:18
  • 1
    A lot of thanks to you , the code works with the lib https://github.com/jblough/Android-Pdf-Viewer-Library/ – NickUnuchek Jan 31 '18 at 21:43
  • @ahmed_khan_89 why output bitmap is smaller then source image in pdf ? – NickUnuchek Feb 02 '18 at 08:08
  • I don't know, I didn't get this issue. But if it might help you, you can choose the width and height of the output bitmap by passing different values in the getImage method. – ahmed_khan_89 Feb 02 '18 at 21:52
0

Here is the code, hope it helps. I managed to render all pages into Bitmap.Cheers

 try {
        pdfViewer = (ImageView) findViewById(R.id.pdfViewer);
        int x = pdfViewer.getWidth();
        int y = pdfViewer.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_4444);
        String StoragePath= Environment.getExternalStorageDirectory()+ "/sample.pdf";
        File file = new File(StoragePath);
        PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
        if (currentPage < 0) {
            currentPage = 0;
        } else if (currentPage > renderer.getPageCount()) {
        }


        Matrix m = pdfViewer.getImageMatrix();
        Rect r = new Rect(0, 0, x, y);
        renderer.openPage(currentPage).render(bitmap, r, m, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        pdfViewer.setImageMatrix(m);
        pdfViewer.setImageBitmap(bitmap);
        pdfViewer.invalidate();


    } catch (Exception ex) {
        Log.v(TAG, ex.getMessage());
    } finally {

    }
DavidB
  • 313
  • 1
  • 8
  • 23
0

dependencies

dependencies {
    implementation 'com.tom_roush:pdfbox-android:1.8.10.1'
}

code

    PDDocument pd = PDDocument.load (new File (in));
    PDFRenderer pr = new PDFRenderer (pd);
    Bitmap bitmap = pr.renderImageWithDPI(0, 300);
Elia Weiss
  • 8,324
  • 13
  • 70
  • 110
0

After going through and trying all the answers, none worked for me for all the PDF files. Rendering issues were there in custom font PDF files. Then I tried using library

The code is as follows:

In your app build.gradle file add the following dependency:

implementation 'com.github.barteksc:android-pdf-viewer:3.2.0-beta.1'

The code for converting PDF pages to images:

      public static List<Bitmap> renderToBitmap(Context context, String filePath) {
            List<Bitmap> images = new ArrayList<>();
            PdfiumCore pdfiumCore = new PdfiumCore(context);
            try {
                File f = new File(pdfPath);
                ParcelFileDescriptor fd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
                PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
                final int pageCount = pdfiumCore.getPageCount(pdfDocument);
                for (int i = 0; i < pageCount; i++) {
                    pdfiumCore.openPage(pdfDocument, i);
                    int width = pdfiumCore.getPageWidthPoint(pdfDocument, i);
                    int height = pdfiumCore.getPageHeightPoint(pdfDocument, i);
                    Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                    pdfiumCore.renderPageBitmap(pdfDocument, bmp, i, 0, 0, width, height);
                    images.add(bmp);
                }
                pdfiumCore.closeDocument(pdfDocument);
            } catch(Exception e) {
                //todo with exception
            }
     return images;
   }

So far it is working for me all the PDF files that I tried.

-1

We can do it using Qoppa PDF toolkit.

Steps to follow to use Qoppa PDF toolkit.

Download it from http://www.qoppa.com/android/pdfsdk/download

This file contains four items:

  1. version_history.txt – This text file will be updated with each new version of the toolkit.
  2. qoppapdf.jar – This is the main jar file for the toolkit. This jar file needs to be added to the classpath for your project.
  3. assets folder – This folder contains assets used by the toolkit, such as fonts and icons. After extracting from the zip files, you will need to copy the files inside this folder to the assets folder in your project.
  4. libs folder – This folder contains native Android libraries, these libraries are needed to decode certain JPEG images as well as JPEG 2000 images that are not supported by Android. The contents of the libs folder need to be copied to the libs folder in your project. If you don’t have a libs folder in your project, create one and copy the contents of this folder into it.

Code is:

        //Converting PDF to Bitmap Image...
        StandardFontTF.mAssetMgr = getAssets();
        //Load document to get the first page
        try {
            PDFDocument pdf = new PDFDocument("/sdcard/PDFFilename.pdf", null);
            PDFPage page = pdf.getPage(0);

            //creating Bitmap and canvas to draw the page into
            int width = (int)Math.ceil(page.getDisplayWidth());
            int height = (int)Math.ceil(page.getDisplayHeight());

            Bitmap bm = Bitmap.createBitmap(width, height, Config.ARGB_8888);
            Canvas c = new Canvas(bm);
            page.paintPage(c);

            //Saving the Bitmap
            OutputStream os = new FileOutputStream("/sdcard/GeneratedImageByQoppa.jpg");
            bm.compress(CompressFormat.JPEG, 80, os);
            os.close();
        } catch (PDFException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
bluish
  • 26,356
  • 27
  • 122
  • 180
Jagadeesh
  • 239
  • 5
  • 9