Skip to content

Instantly share code, notes, and snippets.

@nicemak
Created June 17, 2022 07:49
Show Gist options
  • Select an option

  • Save nicemak/b9951af6a4acde9f80e12f91a66ad459 to your computer and use it in GitHub Desktop.

Select an option

Save nicemak/b9951af6a4acde9f80e12f91a66ad459 to your computer and use it in GitHub Desktop.
Get screenshot and save it to PDF
saveImageToPDF(layout, layout.getScreenShot(), fileName)
fun View.getScreenShot(): Bitmap {
val returnedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(returnedBitmap)
val bgDrawable = background
if (bgDrawable != null) bgDrawable.draw(canvas)
else canvas.drawColor(Color.WHITE)
draw(canvas)
return returnedBitmap
}
fun Context.saveImageToPDF(view : View, bitmap : Bitmap, filename : String) : Boolean
{
val mFolder = File(this.getExternalFilesDir(null)!!.absolutePath + "/" + "iKonnect")
log(this.getExternalFilesDir(null)!!.absolutePath + "/" + "iKonnect")
log(mFolder.absolutePath)
if (!mFolder.exists()) mFolder.mkdirs()
val mFile = File(mFolder, "$filename.pdf")
//val height: Int = view.height + bitmap.height
val document = PdfDocument()
val pageInfo = PdfDocument.PageInfo.Builder(bitmap.width, bitmap.height, 1).create()
val page = document.startPage(pageInfo)
val canvas : Canvas = page.canvas
view.draw(canvas)
// Rect(0, view.height, bitmap.width, bitmap.height),
canvas.drawBitmap(
bitmap, null, Rect(0, 0, 0, 0), null
)
document.finishPage(page)
return try
{
mFile.createNewFile()
val out : OutputStream = FileOutputStream(mFile)
document.writeTo(out)
document.close()
out.close()
true
}
catch (e : Exception)
{
log("Exception: $e")
false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment