I am working on an Android app using Jetpack Compose, and I have a WebView in which I display HTML content. I want to provide users with the ability to download the WebView’s content as a PDF. For this purpose, I’m using the getSystemService(Context.PRINT_SERVICE) method along with createPrintDocumentAdapter() to generate the PDF.
However, when I download the WebView content as a PDF, I notice that it adds padding (white spaces) to the border, which negatively affects the overall appearance of the PDF. I have tried using PrintAttributes.Margins.NO_MARGINS, but it doesn’t seem to solve the issue. Here’s the relevant code snippet:
fun printWebPage(webView: WebView?, originalContext: Context) {
if (webView != null) {
val printManager = originalContext.getSystemService(Context.PRINT_SERVICE) as PrintManager
val jobName = "webpage_" + System.currentTimeMillis()
val printAdapter = webView.createPrintDocumentAdapter(jobName)
// Define the printing attributes
val printAttributes = PrintAttributes.Builder()
.setMediaSize(PrintAttributes.MediaSize.ISO_A4)
.setMinMargins(PrintAttributes.Margins.NO_MARGINS)
.build()
// Start the printing process
printManager.print(jobName, printAdapter, printAttributes)
}
}