Search code examples
imageandroid-studioandroid-intentitext

Insert Image into PDF Document


Is it possible to add an image to the PDF document? My layout has one (Button) and one (ImageView), I would like that when I click (Button), it will open the Gallery to select the image, show it in (ImageView) and add it to the PDF document, as if it were a generator curriculum, thank you in advance.

*Using com.itextpdf:itextg:5.5.10


Solution

  • here is the complete code of what you wanted. Try this and let me know.

    In the onCreate method:

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_image_to_pdf);
    
            imageView = findViewById(R.id.imageView);
            galleryBtn = findViewById(R.id.gallery);
            convertBtn = findViewById(R.id.convert);
    
            galleryBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
                    String imageFileName = "PDF_" + timeStamp + "_";
                    File storageDir = getAlbumDir();
                    try {
                        pdfPath = File.createTempFile(
                                imageFileName, /* prefix */
                                ".pdf", /* suffix */
                                storageDir  /* directory */
                        );
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(photoPickerIntent, GALLERY_INTENT);
                }
            });
    
            convertBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (bitmap == null) {
                        Toast.makeText(ImageToPDF.this, "Please select the image from gallery", Toast.LENGTH_LONG).show();
                    } else {
                        convertToPDF(pdfPath);
                    }
                }
            });
        }
    

    Create a directory for PDF file:

    private File getAlbumDir() {
            File storageDir = null;
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                storageDir = new File(Environment.getExternalStorageDirectory()
                        + "/dcim/"
                        + "Image to pdf");
                if (!storageDir.mkdirs()) {
                    if (!storageDir.exists()) {
                        Log.d("CameraSample", "failed to create directory");
                        return null;
                    }
                }
            } else {
                Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
            }
            return storageDir;
        }
    

    On camera activity intent result:

    @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == GALLERY_INTENT) {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    if (selectedImage != null) {
                        Cursor cursor = getContentResolver().query(selectedImage,
                                filePathColumn, null, null, null);
                        if (cursor != null) {
                            cursor.moveToFirst();
                            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                            String imagePath = cursor.getString(columnIndex);
                            bitmap = BitmapFactory.decodeFile(imagePath);
                            imageView.setImageBitmap(bitmap);
                            cursor.close();
                        }
                    }
                } else if (resultCode == Activity.RESULT_CANCELED) {
                    Log.e("Canceled", "Image not selected");
                }
            }
        }
    

    Now code to convert image to PDF and save to the directory:

    private void convertToPDF(File pdfPath) {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
    
            PdfDocument pdfDocument = new PdfDocument();
            PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(width, height, 1).create();
            PdfDocument.Page page = pdfDocument.startPage(pageInfo);
    
            Canvas canvas = page.getCanvas();
    
            Paint paint = new Paint();
            paint.setColor(Color.parseColor("#ffffff"));
            canvas.drawPaint(paint);
    
            bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
            paint.setColor(Color.BLUE);
            canvas.drawBitmap(bitmap, 0, 0, null);
            pdfDocument.finishPage(page);
    
            try {
                pdfDocument.writeTo(new FileOutputStream(pdfPath));
                Toast.makeText(ImageToPDF.this, "Image is successfully converted to PDF", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
            pdfDocument.close();
        }