Development issue/problem:
I need to convert a PDF file (PDF page) to a bitmap (or image file) under Android.
1. Use the Apache Pdfbox jar. But it uses some Java classes that are not supported by Android.
2. I tried the Itext pot which converts the image to a pdf (I need it to work the other way around)
So I tried a lot of pots too. But there is no positive result.
byte [] byte;
attempt [.
File = new File(this.getFilesDir().getAbsolutePath()+/2010Q2_SDK_Overview.pdf) ;
FileInputStream = new FileInputStream(file) ;
// Obtain file size
long length = file.length();
byte = new byte((int) length);
int offset = 0;
int numRead = 0;
while (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.getBox().width(),
(int) page.getBox().height());
// Bitmap bufferedImage = Bitmap.createBitmap((int)rect.width(), (int)rect.height(),
// Bitmap.Config.ARGB_8888);)
Image Bitmap = 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’m getting an image file,
Instead,
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.enpdf.nio.ByteBuffer ;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.os.bundle;
import android.util.Base64 ;
Test123The public class Activity extends the activity {
/** Called when creating the activity. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main) ;
byte [] byte;
attempt [.
File = new File(this.getFilesDir().getAbsolutePath()+/2010Q2_SDK_Overview.pdf) ;
FileInputStream = new FileInputStream(file) ;
// Obtain file size
long length = file.length();
byte = new byte((int) length);
int offset = 0;
int numRead = 0;
while (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.getBox().width(),
(int) page.getBox().height());
// Bitmap bufferedImage = Bitmap.createBitmap((int)rect.width(), (int)rect.height(),
// Bitmap.Config.ARGB_8888);)
Image Bitmap = 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) ;
} capture (exception e) {
e.printStackTrace();
}
}
}
If not, is there another way to view a PDF on Android using a feature built into the application?
How can I solve this problem?
Solution 1:
I solved that problem. Just give the device time to display each page.
To solve the problem, simply modify the following elements
PDFPage page = pdf_file.getPage(2) ;
at the following address:
PDFPage page = pdf_file.getPage(2, true) ;
To view PDFs on Android, you must first convert the PDFs to images and then display them to the user. (I will use the web preview).
So that’s why we need this library. It’s my edited version of this guy.
After importing the library into the project, you need to create your activity.
XML :
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.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 ;
//method of creation :
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//settings
PDFImage.sShowImages = true; // show images
PDFPaint.s_doAntiAlias = true; // flowing text
HardReference.sKeepCaches = true; // cache images
//Set up webview
wv = (WebView)findViewById(R.id.webView1);
wv.getSettings().setBuiltInZoomControls(true);//Display button zoom
wv.getSettings().setSupportZoom(true);//Slightly zoom
//Think about view width
wv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
ViewSize = wv.getWidth();
wv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}) ;
try
{
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)
{
}
}
// Loading images :
private vacuum pdfLoadImages(final byte[] data)
{
try
{
// enter async
new AsyncTask()
{
// create and show a progress dialog
ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, , Open… ๐
@ Oberriede
protected void onPostExecute(String html)
{
//after asynchronously closing the progress dialog
progressDialog.dismiss();
//load HTML in webview
wv.loadDataWithBaseURL(, html, text/html,UTF-8, );
}
@Background
protected string doInBackground(Void… parameters)
{
try
{
//Produce PDF document object from bytes
ByteBuffer bb = ByteBuffer.NEW(data);
PDFFile pdf = new PDFFile(bb);
//Generate first page of PDF document
PDFPage = pdf.getPage(1, true);
// create a scale value according to the final WebView width template by dragging
= ViewSize / PDFpage.getWidth() * 0.95f;
// convert page to bitmap with scale value
Bitmap page = PDFpage.getImage((int)(PDFpage.getWidth() * scale), (int)(PDFpage.getHeight() * scale), null, true, true);
// store the bitmap in an array of bytes
ByteArrayOutputStream stream = new ByteArrayOutputStream();
page.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
stream.reset();
//Convert byte array to base64 string
String base64 = Base64.encodeToString(byteArray, Base64.NO_WRAP);
//Create HTML + add the first image to html
String html = Error! The file name is not specified.
// Loop the remaining pages and repeat from the top
for (int i = 2; i
;
}
stream.close();
html +=;
return html;
}
catch(exception e)
{
Log.d(error, e.toString());
}
return zero;
}
}execute();
System.gc();// execute GC
}
catch(exception e)
{
Log.d(error, e.toString());
}
}
Solution 2:
I know this is an old question, but I ran into this problem last week and none of the answers really worked.
Here is how I solve this problem without using external libraries.
Based on the code from the android developer’s website, which uses the android’s PDFRenderer class (API 21+), I wrote the following method:
private ArrayList pdfToBitmap(File pdfFile) {
ArrayList bitmaps = new ArrayList() ;
try {
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY)) ;
Grid map;
final int pageCount = renderer.getPageCount();
for (int i = 0; i
returns an array of bitmaps, one bitmap for each page of the PDF file.
The height and width are calculated based on this response to produce better images.
Solution 3:
This problem is a bit older, but I had to do the same thing today, so here’s my solution:
/**
* Use this function to load a PDF file of your assets and display it as a bitmap.
*
* @param context
* current context.
* @param filePath
* current pdf file.
* @Returns a bitmap.
*/ {Bitmap bi = null;InputStream inStream = null;try {AssetManager assetManager = context.getAssets();Log.d(TAG, Atting 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 is already closed}.} return bi;}.
/**
* Use this to display the PDF file specified as InputStream for the bitmap.
*
* @param context
* current context.
* @param inStream
* Input stream of the PDF file.
* @Returns 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 is already closed
}
}
return bi;
}
By the way, I use this library. And my pdf file contains only one page and is an image, in other cases you may have to modify your code.
I hope that helps someone.
Solution 4:
Here is the code, hoping it will help you. I was able to render all pages in Bitmap.
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 = new file (StoragePath);
PdfRenderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
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_FOR_DISPLAY_MODE);
pdfViewer.setImageMatrix(m);
pdfViewer.setImageBitmap(bitmap);
pdfViewer.invalidate() ;
} catch (Exception ex) {
Log.v(TAG, ex.getMessage());
} finally {
}
Solution no. 5:
Dependencies
Dependencies {
execution of 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) ;
Solution no. 6:
We can do this with the Qoppa PDF toolkit.
Steps to use the Qoppa PDF Toolkit.
Download it from http://www.qoppa.com/android/pdfsdk/download.
This folder contains four items:
- version_history.txt – this text file is updated with every new version of the toolbox.
- qoppapdf.jar is the main jar file of the toolbox. This jar file must be added to the classpath of your project.
- asset folder – This folder contains the assets used in the tool set, for example B. Fonts and symbols. After extracting the zip files, you need to copy the files from this folder to the Assets folder of your project.
- libs folder – This folder contains the native Android libraries. These libraries are needed to decode some JPEG images, as well as JPEG-2000 images that are not supported by Android. The contents of the libs folder should be copied to the libs folder in your project. If you don’t have a libs folder in your project, create one and copy its contents.
The code is:
// Convert PDF to raster image…
StandardFontTF.mAssetMgr = getAssets() ;
//Load the document to get the first page
try {
PDFDocument pdf = new PDFDocument(/sdcard/PDFFilename.pdf, null) ;
PDFPage page = pdf.getPage(0) ;
//Create a bitmap and a canvas to make the page
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) ;
//Save Bitmap
OutputStream os = new FileOutputStream(/sdcard/GeneratedImageByQoppa.jpg);
bm.compress(CompressFormat.JPEG, 80, os);
os.close();
} catch (PDFException e) {
// TODO Automatically generated block catch
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Automatically generated intercept block
e.printStackTrace();
} catch (IOException e) {
// TODO Automatically generated intercept block
e.printStackTrace();
}
Good luck!
Related Tags:
convert pdf to image android code,android pdf to image library,android canvas pdf,show pdf in imageview android,android pdfdocument example,convert bitmap to pdf in android programmatically,pdf to image android github,convert bitmap to pdf android github,pdfpage android,pdf android studio,android convert pdf to image,convert multiple image to pdf in android programmatically,android native pdf viewer