15

I need to send an image as in form of PDF file in my Android application but I dont have idea how to convert bitmap to PDF.

I am able to write pdf with text only.

Is there any solution?

palacsint
  • 28,416
  • 10
  • 82
  • 109
Nandlal Virani
  • 333
  • 1
  • 3
  • 11
  • possible duplicate of [How to generate a PDF using android drawing commands?](http://stackoverflow.com/questions/5292590/how-to-generate-a-pdf-using-android-drawing-commands) – CommonsWare Mar 22 '11 at 11:16

3 Answers3

33

I think you are using iText Library to convert the text to pdf. Use this to convert image to pdf.

import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class imagesPDF
{     
    public static void main(String arg[])throws Exception
    {                  
        Document document=new Document();
        PdfWriter.getInstance(document,new FileOutputStream("YourPDFHere.pdf"));
        document.open();
        Image image = Image.getInstance ("yourImageHere.jpg");
        document.add(new Paragraph("Your Heading for the Image Goes Here"));
        document.add(image);               
        document.close();
   }
}
Ashok Goli
  • 5,043
  • 8
  • 38
  • 68
  • Hi Ashok , import com.lowagie.text.pdf.* is not available in android. Can we add externally this library in Android ?? where can i get this library from ??? – Nandlal Virani Mar 22 '11 at 13:14
  • Yes, you have to add a the Lowagie iText Library to Android. You can download the latest version of iText from http://sourceforge.net/projects/itext/files/ . Just include this in your project's lib, add it to your build path and it's all set for you to crack it down. – Ashok Goli Mar 22 '11 at 15:19
  • Hey @KK_07k11A0585, what is the exception that you received? It should work if you place the itext library in your project and classpath. – Ashok Goli Dec 27 '11 at 18:13
  • @AshokFelix It is working now i tried thank u for reply But i want to convert a **page of a pdf file into image** or atleast **i want to view pdf files**. Is it possible using itext ???? – KK_07k11A0585 Dec 28 '11 at 04:17
  • @KK_07k11A0585, Unfortunately, iText doesn't convert PDF to image formats. It is not meant for that. 'View PDF' on which platform specifically? Desktop, Web, Mobile (Android, iPhone)? If it's Android, then there are a lot of Open Source PDF Viewers that you may want to go through to get an idea. Or even better, reuse them (mind the licences) in your apps. – Ashok Goli Dec 28 '11 at 10:35
  • @AshokFelix Is it possible to view pdf files using **itext** – KK_07k11A0585 Dec 28 '11 at 10:43
  • hi @AshokFelix in my case, when I try to open the pdf file, shows me an error message by telling the file "is damaged". Also when I use `document.close();` it gives me a error. With out that line, it runs normally. Are there any necessary fields that we should `add()` for `document` instance that the document appears to be a PDF file such as `addHeader()` or something like that? – AnujAroshA Sep 07 '12 at 06:41
  • But where i find my pdf file. – Born To Win Apr 14 '14 at 09:27
  • Wherever you created the `FileOutputStream("YourPDFHere.pdf")`. If you didn't give any location, it'll be at the root location of your project. – Ashok Goli Apr 15 '14 at 05:56
  • @AshokFelix your answer is been very helpful to me. It add the image in page of pdf. But my need is pdf should have the same size(200*200) like image. Can you please help me ? – Yog Guru Aug 01 '16 at 11:37
  • Hi @AshokFelix very useful answer. but i pass a above 4mb picture but get .58mb pdf .i want that pdf must be above 4mb .is there any solution? – Suman Oct 05 '16 at 06:10
5

Download source code from here(Convert Image to pdf in android programattically)

MainActivity.java

package com.deepshikha.convertbitmap;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.pdf.PdfDocument;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static final int GALLERY_PICTURE = 1;
    Button btn_select, btn_convert;
    ImageView iv_image;
    boolean boolean_permission;
    boolean boolean_save;
    Bitmap bitmap;
    public static final int REQUEST_PERMISSIONS = 1;


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

    private void init() {
        btn_select = (Button) findViewById(R.id.btn_select);
        btn_convert = (Button) findViewById(R.id.btn_convert);
        iv_image = (ImageView) findViewById(R.id.iv_image);
    }

    private void listener() {
        btn_select.setOnClickListener(this);
        btn_convert.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_select:
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, GALLERY_PICTURE);
                break;

            case R.id.btn_convert:
                if (boolean_save){

                    Intent intent1=new Intent(getApplicationContext(),PDFViewActivity.class);
                    startActivity(intent1);

                }else {
                    createPdf();
                }
                break;


        }
    }

    private void createPdf(){
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics displaymetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        float hight = displaymetrics.heightPixels ;
        float width = displaymetrics.widthPixels ;

        int convertHighet = (int) hight, convertWidth = (int) width;

//        Resources mResources = getResources();
//        Bitmap bitmap = BitmapFactory.decodeResource(mResources, R.drawable.screenshot);

        PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);

        Canvas canvas = page.getCanvas();


        Paint paint = new Paint();
        paint.setColor(Color.parseColor("#ffffff"));
        canvas.drawPaint(paint);



        bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);

        paint.setColor(Color.BLUE);
        canvas.drawBitmap(bitmap, 0, 0 , null);
        document.finishPage(page);


        // write the document content
        String targetPdf = "/sdcard/test.pdf";
        File filePath = new File(targetPdf);
        try {
            document.writeTo(new FileOutputStream(filePath));
            btn_convert.setText("Check PDF");
            boolean_save=true;
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
        }

        // close the document
        document.close();
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_PICTURE && resultCode == RESULT_OK) {

            if (resultCode == RESULT_OK) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(
                        selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);
                cursor.close();


                bitmap = BitmapFactory.decodeFile(filePath);
                iv_image.setImageBitmap(bitmap);


                btn_convert.setClickable(true);
            }
        }
    }

    private void fn_permission() {
        if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)||
                (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

            if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_PERMISSIONS);

            }

            if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_PERMISSIONS);

            }
        } else {
            boolean_permission = true;


        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSIONS) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                boolean_permission = true;


            } else {
                Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();

            }
        }
    }


}

Thanks!

Deepshikha Puri
  • 2,104
  • 22
  • 23
0

A much simpler way.

Just pass context and list of file It will create a PDF file in cache dir Add your own logic to share/open PDF Works fast and reliable method

  • No library needed (Uses android internal android.graphics.pdf.PdfDocument classes)
  • Works in background, Doesn''t freeze UI
  • No need to declare and grant storage permission :)
private static void createPdf(Context context,ArrayList<File> data){
    File pdfFile = new File(context.getExternalCacheDir().getAbsolutePath() + File.separator + "TemperoryPDF_"+System.currentTimeMillis()+".pdf");
    Toast.makeText(context, "Creating PDF,Please wait..", Toast.LENGTH_SHORT).show();
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            PdfDocument document = new PdfDocument();
            try {
                for(File item:data) {
                    Bitmap bitmap = BitmapFactory.decodeFile(item.getAbsolutePath());
                    PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();
                    PdfDocument.Page page = document.startPage(pageInfo);
                    Canvas canvas = page.getCanvas();
                    Paint paint = new Paint();
                    paint.setColor(Color.parseColor("#ffffff"));
                    canvas.drawPaint(paint);
                    bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
                    canvas.drawBitmap(bitmap, 0, 0, null);
                    document.finishPage(page);
                }
                document.writeTo(new FileOutputStream(pdfFile));
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                document.close();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void unused) {
            super.onPostExecute(unused);
            if(pdfFile.exists() && pdfFile.length()>0) {
                FileUtil.openFile(context, pdfFile.getAbsolutePath()); // See: https://gist.github.com/omkar-tenkale/34d3aa1966653e6949d1ddaee1ba3355
            }else {
                Toast.makeText(context, "Something went wrong creating the PDF :(", Toast.LENGTH_SHORT).show();
            }
        }
    }.execute();

}
Omkar T
  • 755
  • 8
  • 19