0

TL;DR: How to calculate the acutal size of a WebView in Mils to set the PrintAdapter's MediaSize so that the WebView will be printed in a single page PDF.

Long version: I want to create a Receipt-PDF by printing from an Android WebView into a PDF. The problem is, that the receipt should always be a 1-page PDF, so the PDF-Page must be dynamically rezied to fit the WebView's height. For this I try to read the WebViews size with a @JavaScriptInterface:"javascript:window.$tag.size(document.querySelector('body').offsetHeight);" and then try to convert this result into Mils to have the length of the document:

    fun size(height: String?) {
        val h = height!!.toFloat()
        val pixel = context.dipToPixel(h)
        val dm = context.getResources().getDisplayMetrics()
        val mils =( pixel / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_IN, 1f, dm)) * 1000
        setHeight(mils)
    }

(Ignore the !!, its just debug code for now) This value I set as MediaSize in the PrintAttributes

val adapter = webView.createPrintDocumentAdapter(document.id)

val printAttributes = PrintAttributes.Builder()
setMediaSize(PrintAttributes.MediaSize("Endless", "Endless", width, height)

My problem is, that the calculation of the height seems to differ a lot for as longer as the document gets, which results in a lot of white space at the end of the acutal page. How can I calculate the size of the WebView correctly, so that the PDF will be always 1 page.

Thommy
  • 5,070
  • 2
  • 28
  • 51
  • I believe your answer lies here https://stackoverflow.com/questions/43394498/how-to-get-the-full-height-of-in-android-webview using `document.body.scrollHeight` on javascript should do the job. – Simon Harvan Mar 17 '22 at 13:14
  • Thx for answer, I tried it, but it gives the same inexplicable values as `offsetHeight` – Thommy Mar 17 '22 at 14:04

0 Answers0