package com.gtappdevelopers.kotlingfgproject
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.print.PrintAttributes
import android.print.PrintJob
import android.print.PrintManager
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var webView: WebView
lateinit var savePDFBtn: Button
lateinit var printJob: PrintJob
var printBtnPressed = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webView = findViewById(R.id.idWebView)
savePDFBtn = findViewById(R.id.idBtnSavePDF)
webView.setWebViewClient(object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
webView = view
}
})
savePDFBtn.setOnClickListener {
if (webView != null) {
printWebPage(webView)
} else {
Toast.makeText(this, "Webpage not loaded..", Toast.LENGTH_SHORT).show()
}
}
}
fun printWebPage(webview: WebView) {
printBtnPressed = true
val printManager =
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
this
.getSystemService(Context.PRINT_SERVICE) as PrintManager
} else {
TODO("VERSION.SDK_INT < KITKAT")
}
val jobName = " webpage" + webView.url
val printAdapter =
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
webView.createPrintDocumentAdapter(jobName)
} else {
TODO("VERSION.SDK_INT < LOLLIPOP")
}
assert(printManager != null)
printJob = printManager.print(
jobName, printAdapter,
PrintAttributes.Builder().build()
)
}
@RequiresApi(Build.VERSION_CODES.KITKAT)
override fun onResume() {
super.onResume()
if (printBtnPressed) {
if (printJob.isCompleted) {
Toast.makeText(this, "Completed..", Toast.LENGTH_SHORT).show()
}
else if (printJob.isStarted) {
Toast.makeText(this, "Started..", Toast.LENGTH_SHORT).show()
}
else if (printJob.isBlocked) {
Toast.makeText(this, "Blocked..", Toast.LENGTH_SHORT).show()
}
else if (printJob.isCancelled) {
Toast.makeText(this, "Cancelled..", Toast.LENGTH_SHORT).show()
}
else if (printJob.isFailed) {
Toast.makeText(this, "Failed..", Toast.LENGTH_SHORT).show()
}
else if (printJob.isQueued) {
Toast.makeText(this, "Jon Queued..", Toast.LENGTH_SHORT).show()
}
printBtnPressed = false
}
}
}