Search code examples
androiditext

image from gallery is not displaying on pdf file in android


I am trying to creating pdfs from images in my Android application. I get the image successfully and created the pdf file successfully. But When I open my pdf file, images are not displayed. I have tried many solutions on Internet but all in vain. I am pasting my code. Kindly guide me.

First I am pasting the code for getting image from gallery

       Intent myIntent = new Intent(Intent.ACTION_PICK, 
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
             
              startActivityForResult(myIntent,120);

Now I am pasting the code of OnActivityResult Method, in which I am getting the image and craeating a pdf file.

 try {
    Document doc = new Document();
    if (resultCode == RESULT_OK) {
        if (requestCode == 120) {
            if (data.getData() != null) {
               Uri uri   = data.getData();


               Image image = Image.getInstance(uri.toString());
               FileOutputStream fileOutputStream =openFileOutput("mypdf.pdf", Context.MODE_PRIVATE);
                   PdfWriter.getInstance(doc, fileOutputStream);
                   doc.open();
                   doc.add(image);

                   doc.close();


            }
        }
    }
    } catch (IOException | DocumentException e) {
        e.printStackTrace();
    }

Solution

  • I have solved it, The solution was to use Input Stream as follows:

     Uri uri = data.getData();
            InputStream ims = getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(ims);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            Image image = Image.getInstance(byteArray);
            doc.add(image);
            doc.close();