Skip to content

Instantly share code, notes, and snippets.

@imandaliya
Last active August 9, 2021 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imandaliya/0e3abecb31512960a658638f3c9fea05 to your computer and use it in GitHub Desktop.
Save imandaliya/0e3abecb31512960a658638f3c9fea05 to your computer and use it in GitHub Desktop.
// original link : https://androidexplained.github.io/android/android11/scoped-storage/2020/09/29/file-saving-android-11.html
private fun openDocumentToSavePDF() {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "application/pdf"
val fileName = "Screenshot_${Calendar.getInstance().time}.pdf"
putExtra(Intent.EXTRA_TITLE, fileName)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.DIRECTORY_DOCUMENTS)
}
}
resultLauncher.launch(intent)
}
private val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
result.data?.data?.let { savePDFToStorage(it) }
}
}
private fun savePDFToStorage(uri: Uri) {
val metrics = resources.displayMetrics
val document = PdfDocument()
val pageInfo = PageInfo.Builder(metrics.widthPixels, metrics.heightPixels, 1).create()
val page = document.startPage(pageInfo)
val bitmap = getViewScreenshot(imageView)
page.canvas.drawBitmap(bitmap, 0f, 0f, null)
document.finishPage(page)
val imageOutStream = contentResolver.openOutputStream(uri)
document.writeTo(imageOutStream)
document.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment