Skip to content

Instantly share code, notes, and snippets.

@AbGhost-cyber
Created October 28, 2020 04:55
Show Gist options
  • Save AbGhost-cyber/4f14a99d6dcc545a0b529495cf22f26d to your computer and use it in GitHub Desktop.
Save AbGhost-cyber/4f14a99d6dcc545a0b529495cf22f26d to your computer and use it in GitHub Desktop.
private fun checkWritePermissionAndProcessPdf() {
ActivityCompat.requestPermissions(
requireActivity(),
arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_CODE
)
if (checkSelfPermission(
requireContext(),
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
)
== PackageManager.PERMISSION_GRANTED
) {
processPdf()
} else {
// show Snackbar toast message
}
}
private fun processPdf() {
val pageInfo = PdfDocument.PageInfo.Builder(2250, 1400, 1).create()
val document = PdfDocument()
val page = document.startPage(pageInfo)
val content =
this.requireActivity().window.decorView.findViewById<ConstraintLayout>(R.id.your_parent_view)
content.measure(2480, 3508)
content.layout(0, 0, 2480, 3508)
val measureWidth = View.MeasureSpec.makeMeasureSpec(
page.canvas.width,
View.MeasureSpec.EXACTLY
)
val measuredHeight = View.MeasureSpec.makeMeasureSpec(
page.canvas.height,
View.MeasureSpec.EXACTLY
)
content.measure(measureWidth, measuredHeight)
content.layout(0, 0, page.canvas.width, page.canvas.height)
content.draw(page.canvas)
document.finishPage(page)
val pdfFolder = File(
requireContext().externalCacheDir?.absolutePath,
"your child path here"
)
if (!pdfFolder.exists()) {
pdfFolder.mkdirs()
Timber.i("Pdf Directory created")
}
//Create time stamp
val date = Date()
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(date)
val fileNamePath = "$pdfFolder$timeStamp.pdf"
val myFile = File(fileNamePath)
val output: OutputStream = FileOutputStream(myFile)
try {
document.writeTo(output)
//you can restore the parent layout params here
} catch (e: IOException) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment