我正在使用这种方法来添加图像到我的PDF。
@Throws(DocumentException::class)
private fun addImage(document: Document)
{
try {
val rectDoc = document.pageSize
val width = rectDoc.width
val height = rectDoc.height
val imageStartX = width - document.rightMargin() - 300f//Absolute Position X
val imageStartY = height - document.topMargin() - 500f//Absolute Position Y
System.gc()
val ims: InputStream? = activity?.assets?.open("test.jpg")//File Location
val bmp = BitmapFactory.decodeStream(ims)
val stream = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream)
val byteArray: ByteArray = stream.toByteArray()
val img = Image.getInstance(byteArray) // img.scalePercent(50);
img.alignment = Image.TEXTWRAP
img.scaleAbsolute(200f, 200f) // ReAdjusting the JPG
img.setAbsolutePosition(imageStartX, imageStartY) // Adding Image
document.add(img)
} catch (e: Exception)
{
e.printStackTrace()
Log.e("JPG ERROR", e.message)
}
}
这个代码块可以帮助我从assets文件夹中添加图片,我需要的是我需要从外部驱动器中添加一个特定的图像。我正在用同一个应用程序生成JPG文件,保存JPG文件。
我找到了这个代码块来获取我的文件。
val absoluteFile = "UserSignature/Signature.jpg"
val photoUri: Uri = Uri.withAppendedPath(
MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL), absoluteFile)
下面是这个的输出。 content:/mediaexternalimagesmediaUserSignatureSignature.jpg。
我可以用同样的功能吗?如果不能,我怎么能呢,谢谢。
EDIT: 这里是解决方案
@Throws(DocumentException::class , IOException::class)
private fun addImageFromGallery(document: Document)
{
try {
val rectDoc = document.pageSize
val width = rectDoc.width
val height = rectDoc.height
val imageStartX = width - document.rightMargin() - 300f//Absolute Position X
val imageStartY = height - document.topMargin() - 500f//Absolute Position Y
System.gc()
val fileLocation = "/storage/emulated/0/Pictures/UserSignature/Signature.jpg"//Example Location - Gallery/UserSignature/Signature.JPG file
val ims = FileInputStream(fileLocation)
Log.d("FileInputStreamDebugTag", "Value: $ims")
val bmp = BitmapFactory.decodeStream(ims)
val stream = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream)
val byteArray: ByteArray = stream.toByteArray()
val img = Image.getInstance(byteArray) // img.scalePercent(50);
img.alignment = Image.TEXTWRAP
img.scaleAbsolute(200f, 200f) // ReAdjusting the JPG
img.setAbsolutePosition(imageStartX, imageStartY) // Adding Image
document.add(img)
} catch (e: Exception)
{
e.printStackTrace()
Log.e("JPG ERROR", e.message)
}
}