I have difficulty adding images from the mobile gallery in the pdf document I am creating. Passing the image path returns the following error: Error: Failed to open: ENOENT (this file or directory does not exist). I created a class that the user can choose photos from gallery or capture a new image by camera. I am storing the path of these images in an arraylist. So I need to pass these paths to the function that creates the pdf document.
private val pathImage: ArrayList<String> = arrayListOf()
private fun openCam() {
imageCapture.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
if (checkPermission()) {
val diretorio: File =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
val imagem =
File(diretorio.path + "/" + System.currentTimeMillis().toString() + ".jpg")
uri = Uri.fromFile(imagem)
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, CAM)
} else {
requestPermission()
}
}
})
private fun openGatelry() {
imageGallery.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
startActivityForResult(Intent.createChooser(intent, R.string.select_picture.toString()), GALLERY)
}
})
}
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)
val imageCam = uri.getPath()
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())
showImages()
}
} else {
val uri = data.data
if (uri != null) {
pathImage.add(uri.path.toString())
showImages()
}
}
}
}
// Do something when user press the positive button
val mDoc = Document()
//pdf file name
val mFileName = SimpleDateFormat(
"ddMMyyyy_HHmmss",
Locale.getDefault()
).format(System.currentTimeMillis())
//pdf file path
val mFilePath =
Environment.getExternalStorageDirectory().toString() + "/" + mFileName + ".pdf"
try {
//create instance of PdfWriter class
PdfWriter.getInstance(mDoc, FileOutputStream(mFilePath))
//open the document for writing
mDoc.open()
val image = Image.getInstance("/storage/emulated/0/Pictures/1573066971461.jpg")
mDoc.add(image)
//close document
mDoc.close()