Search code examples
javaandroidkotlinmobilereport

How to add captured images from camera or gallery in pdf report?


I am developing a feature where the user can create a report of the work order performed. With this report you will get information of the order itself, such as customer name, service, location, etc ... as well as the captured images of the service. I already managed to generate the report with the data I want, including formatting. However I have difficulty attaching the acquired images from the camera or gallery in this same report. Already researched numerous times and the attempts I make does not appear the image in the report.

Get imagem from camera

private val pathImage: ArrayList<String> = arrayListOf<String>()

override fun onActivityResult(
    requestCode: Int,
    resultCode: Int,
    data: Intent?
) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == CAM && resultCode == Activity.RESULT_OK && data != null) {
        val novaIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)
        sendBroadcast(novaIntent)
        imageCam = uri.getPath().toString()
        if (imageCam != null) {
            Log.i("TAG", "Camera: " + imageCam)
            pathImage.add(imageCam)
        }
    } else if (requestCode == GALLERY && resultCode == Activity.RESULT_OK && data != null) {
        val clipData = data.clipData
        if (clipData != null) {
            for (i in 0 until clipData.itemCount) {
                val uri: Uri = clipData.getItemAt(i).uri
                pathImage.add(uri.path.toString())
            }
        } else {
            val uri = data.data
            if (uri != null) {
                pathImage.add(uri.path.toString())
            }
        }
    }
}

createReport

     val mDoc = Document()
    //pdf file name
    mFileName = SimpleDateFormat(
        "ddMMyyyy_HHmmss",
        Locale.getDefault()
    ).format(System.currentTimeMillis())
    //pdf file path
    mFilePath =
        Environment.getExternalStorageDirectory().toString() + "/" + mFileName + ".pdf"
    try {
        //create instance of PdfWriter class
        PdfWriter.getInstance(mDoc, FileOutputStream(mFilePath))
        //open the document for writing
        mDoc.open()

        //settings
        mDoc.setPageSize(PageSize.A4)
        mDoc.addCreationDate()
        mDoc.addAuthor(userDTO.user.fullname)
        mDoc.addCreator("Pratik Butani")
        mDoc.setPageSize(PageSize.LETTER)
        //font settings
        val mColorAccent = BaseColor(0, 153, 204, 255)
        val mHeadingFontSize = 20.0f
        val mValueFontSize = 16.0f
        //Font
        val fontName = BaseFont.createFont(
            "assets/fonts/brandon_medium.otf",
            BaseFont.IDENTITY_H,
            BaseFont.EMBEDDED,
            true
        )
        for ( image in pathImage) {
            val img = Image.getInstance(image)
            mDoc.setPageSize(img)
            mDoc.newPage()
            img.setAbsolutePosition(0f, 0f)
            mDoc.add(img)
        }

        //close document
        mDoc.close()
        } catch (e: Exception) {
        //if anything goes wrong causing exception, get and show exception message
        Toast.makeText(this@DetailsActivity, e.message, Toast.LENGTH_SHORT).show()
    }

Return error: /document/image:8495: open failed: ENOENT (No such file or directory)


Solution

  • You have done mistake while getting path from uri in onActivityResult method on this line pathImage.add(uri.path.toString()).

    You can try following method to get Path from URI:

    public static String getPathFromUri(final Context context, final Uri uri) {
    
        // DocumentProvider
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
    
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
    
                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
    
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
    
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
    
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
    
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };
    
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
    
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();
    
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
    
        return null;
    }
    

    Here is the full gist that will help you.

    Thank you.