Created
June 17, 2022 07:49
-
-
Save nicemak/b9951af6a4acde9f80e12f91a66ad459 to your computer and use it in GitHub Desktop.
Get screenshot and save it to PDF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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