Created
October 28, 2020 04:55
Revisions
-
AbGhost-cyber created this gist
Oct 28, 2020 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,66 @@ 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) { } }