I am trying to convert webview into Pdf and saving it on personal mobile using Print Manager. It works fine when printer is not connected but if printer is connected to mobile then save pdf option is not showing. Device has android 10.
fun printWebPage(webView: WebView, loadID: String) {
var jobName = ""
printBtnPressed = true
val printManager =
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
requireContext().getSystemService(Context.PRINT_SERVICE) as PrintManager
} else {
TODO("VERSION.SDK_INT < KITKAT")
}
// on below line we are creating a variable for job name
if(loadID.isEmpty()){
jobName = "Load Detail"
}else{
jobName = "Load ID:$loadID"
}
// on below line we are initializing our print adapter.
val printAdapter =
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
// on below line we are creating
// our print document adapter.
webView.createPrintDocumentAdapter(jobName)
} else {
TODO("VERSION.SDK_INT < LOLLIPOP")
}
// on below line we are checking id
// print manager is not null
assert(printManager != null)
// on below line we are initializing
// our print job with print manager
printJob = printManager.print(
jobName, printAdapter,
// on below line we are calling
// build method for print attributes.
PrintAttributes.Builder().build()
)
}
Print Manager rarely recognizes any printer, and I guess its main purpose has become to simply save to pdf...
In my case, I solved this by firstly converting the webview into a bitmap, then scaling the bitmap to fit into the pdf page.
As for the printing part, I think it was more flexible to simply share the pdf and ask the user to select his printer software, as it's more useful than simply saving as pdf.
If you want to print several pages, I think it is more manageable to create different bitmaps and assign them to different pdf pages.
This code converts a webview into a pdf page and then shares it, asking the user to select his printer app: