chaviaras michalis
chaviaras michalis

Reputation: 364

Android : Very large html(>25k lines) to pdf is not generated

I have an html that I want to be converted to a pdf. The html is thousands of lines. I have observed that for less than 25k(more or less) lines of html code the generation to pdf is happening in about 2-3 seconds. When the html passes the above threshold then the html is never generated and the programm runs forever(I waited for 10 mins). Right now excuse me that I can't provide to you the exact number of lines of the above threshold because the html is produced randomly. I checked that the html is correct and I paste it to an html viewer and it worked.

At first for the generation of the pdf I used the classic one pdfConverter : https://github.com/blink22/react-native-html-to-pdf/blob/master/android/src/main/java/android/print/PdfConverter.java .

I modified the code in order to see what happened and I implement all the functions of the WebviewClient. Here is my modified code :

class PdfConverter private constructor() : Runnable {
    private var mContext: Context? = null
    private var mHtmlString: String? = null
    private var mPdfFile: File? = null
    private var mPdfPrintAttrs: PrintAttributes? = null
    private var mIsCurrentlyConverting = false
    private var mWebView: WebView? = null
    var pdfcreator_observer :PdfCreator? = null


    override fun run() {
        mWebView = WebView(mContext as Context)
        mWebView!!.webViewClient = object : WebViewClient() {
            override fun onReceivedError (view: WebView,
                                          request: WebResourceRequest,
                                          error: WebResourceError
            ){
                Log.d("michav/1","michav/onReceivedError")
            }
            override fun onReceivedHttpError (view: WebView,
                                              request: WebResourceRequest,
                                              errorResponse: WebResourceResponse
            ){
                Log.d("michav/1","michav/onReceivedHttpError")
            }
            override fun onReceivedSslError(view: WebView,
                                            handler: SslErrorHandler,
                                            error: SslError
            ){
                Log.d("michav/1","michav/onReceivedSslError")
            }

            override fun onRenderProcessGone(view: WebView, detail:RenderProcessGoneDetail):Boolean{
                Log.d("michav/1", "michav/onRenderProcessGone")
                return true
            }

            override fun doUpdateVisitedHistory( view: WebView, url:String, isReload:Boolean){
                Log.d("michav/1", "michav/doUpdateVisitedHistory")
            }

            override fun onFormResubmission(view:WebView, dontResend:Message , resend:Message  ){
                Log.d("michav/1", "michav/onFormResubmission")
            }

            override fun onLoadResource(view:WebView, url:String){
                Log.d("michav/1", "michav/onLoadResource")
            }
            override fun onPageCommitVisible(view:WebView, url:String){
                Log.d("michav/1", "michav/onPageCommitVisible")
            }
            override fun onPageStarted(view:WebView, url:String, favicon:Bitmap ){
                Log.d("michav/1", "michav/onPageStarted")
            }
            override fun onReceivedClientCertRequest(view:WebView, request:ClientCertRequest){
                Log.d("michav/1", "michav/onReceivedClientCertRequest")
            }

            override fun onReceivedHttpAuthRequest(view:WebView, handler:HttpAuthHandler, host:String, realm:String){
                Log.d("michav/1", "michav/onReceivedHttpAuthRequest")
            }
            override fun onReceivedLoginRequest(view:WebView, realm:String, account:String, args:String){
                Log.d("michav/1", "michav/onReceivedLoginRequest")
            }
            override fun onSafeBrowsingHit(view:WebView, request:WebResourceRequest, threatType:Int, callback:SafeBrowsingResponse){
                Log.d("michav/1", "michav/onSafeBrowsingHit")
            }
            override fun onScaleChanged(view:WebView, oldScale:Float, newScale:Float){
                Log.d("michav/1", "michav/onScaleChanged")
            }

            override fun onTooManyRedirects(view:WebView, cancelMsg:Message, continueMsg:Message){
                Log.d("michav/1", "michav/onTooManyRedirects")
            }

            override fun onUnhandledKeyEvent(view:WebView, event:KeyEvent){
                Log.d("michav/1", "michav/onUnhandledKeyEvent")
            }
            override fun shouldInterceptRequest(view:WebView, request:WebResourceRequest):WebResourceResponse{
                Log.d("michav/1", "michav/shouldInterceptRequest")
                return WebResourceResponse("","",(1) as InputStream)
            }
            override fun shouldInterceptRequest(view:WebView, url:String):WebResourceResponse{
                Log.d("michav/1", "michav/shouldInterceptRequest")
                return WebResourceResponse("","",(1) as InputStream)
            }
            override fun shouldOverrideKeyEvent(view:WebView, event:KeyEvent):Boolean{
                Log.d("michav/1", "michav/shouldOverrideKeyEvent")
                return true
            }
            override fun shouldOverrideUrlLoading(view:WebView, request:WebResourceRequest):Boolean{
                Log.d("michav/1", "michav/shouldOverrideUrlLoading")
                return true
            }

            override fun shouldOverrideUrlLoading(view:WebView, url:String):Boolean{
                Log.d("michav/1", "michav/shouldOverrideUrlLoading")
                return true
            }


            override fun onPageFinished(view: WebView, url: String) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) throw RuntimeException(
                    "call requires API level 19"
                ) else {
                    val documentAdapter =
                        mWebView!!.createPrintDocumentAdapter()
                    documentAdapter.onLayout(
                        null,
                        pdfPrintAttrs,
                        null,
                        object : LayoutResultCallback() {},
                        null
                    )
                    documentAdapter.onWrite(
                        arrayOf(PageRange.ALL_PAGES),
                        outputFileDescriptor,
                        null,
                        object : WriteResultCallback() {
                            override fun onWriteFinished(pages: Array<PageRange>) {
                                destroy()
                                pdfcreator_observer?.update_from_pdfconverter()
                            }
                        })

                }
            }
        }
        mWebView!!.loadData(mHtmlString, "text/HTML", "UTF-8")

    }


    var pdfPrintAttrs: PrintAttributes?
        get() = if (mPdfPrintAttrs != null) mPdfPrintAttrs else defaultPrintAttrs
        set(printAttrs) {
            mPdfPrintAttrs = printAttrs
        }

    fun convert(
        context: Context?,
        htmlString: String?,
        file: File?
    ) {
        requireNotNull(context) { "context can't be null" }
        requireNotNull(htmlString) { "htmlString can't be null" }
        requireNotNull(file) { "file can't be null" }
        if (mIsCurrentlyConverting) return
        mContext = context
        mHtmlString = htmlString
        mPdfFile = file
        mIsCurrentlyConverting = true
        runOnUiThread(this)
    }

    private val outputFileDescriptor: ParcelFileDescriptor?
        private get() {
            try {
                mPdfFile!!.createNewFile()
                return ParcelFileDescriptor.open(
                    mPdfFile,
                    ParcelFileDescriptor.MODE_TRUNCATE or ParcelFileDescriptor.MODE_READ_WRITE
                )
            } catch (e: Exception) {
                Log.d(TAG, "Failed to open ParcelFileDescriptor", e)
            }
            return null
        }

    private val defaultPrintAttrs: PrintAttributes?
        private get() = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) null else PrintAttributes.Builder()
            .setMediaSize(PrintAttributes.MediaSize.NA_GOVT_LETTER)
            .setResolution(Resolution("RESOLUTION_ID", "RESOLUTION_ID", 600, 600))
            .setMinMargins(PrintAttributes.Margins.NO_MARGINS)
            .build()

    private fun runOnUiThread(runnable: Runnable) {
        val handler = Handler(mContext!!.mainLooper)
        handler.post(this)
    }

    private fun destroy() {
        mContext = null
        mHtmlString = null
        mPdfFile = null
        mPdfPrintAttrs = null
        mIsCurrentlyConverting = false
        mWebView = null
    }

    companion object {
        private const val TAG = "PdfConverter"
        private var sInstance: PdfConverter? = null
        @get:Synchronized
        val instance: PdfConverter?
            get() {
                if (sInstance == null) sInstance =
                    PdfConverter()
                return sInstance
            }
    }
}


I call the above code with the following code

fun createPdfFromHtml(htmlstring: String) {
        val directory = File(directory_whole_path)
        if (!directory.exists()) {
            directory.mkdir()
            Toast.makeText(
                m_context,
                "The directory $directory_whole_path created",
                Toast.LENGTH_SHORT
            ).show()
        }
        var converter: PdfConverter? = PdfConverter.instance
        val file = File(
            directory_whole_path,
            nameofpdf
        )
        converter?.pdfcreator_observer = this
        converter?.convert(m_context, htmlstring, file)
        mFilepdf = file
    }

None of the debugging logs in pdfConverter is called. I try to know what is happening and when I have the large html the code runs forever. Do you suggest to me to change the html conversion procedure ?

EDIT I changed the code as the first answer :

 val directory = File(directory_whole_path)
        if (!directory.exists()) {
            directory.mkdir()
            Toast.makeText(
                m_context,
                "The directory $directory_whole_path created",
                Toast.LENGTH_SHORT
            ).show()
        }
        var this_to_pass =this
        GlobalScope.launch(Dispatchers.Default ){
            var converter: PdfConverter? = PdfConverter.instance
            val file = File(
                directory_whole_path,
                nameofpdf
            )
            converter?.pdfcreator_observer = this_to_pass

            converter?.convert(m_context, htmlstring, file)
            mFilepdf = file
        }

But also nothing worked ... still the problem occurs ... when the pdf is a little bit larger than 25k lines of html code the programm runs forever. For this attempt I also put in comment all the webviewclient overrides except the on pagefinished.

Also in the "run" of Android Studio the below is displayed :

W/chromium: [WARNING:navigation_controller_impl.cc(2579)] Refusing to load URL as it exceeds 2097152 characters. 

Upvotes: 1

Views: 423

Answers (2)

chaviaras michalis
chaviaras michalis

Reputation: 364

I had to change the below line in the PdfConverter :

mWebView!!.loadData(mHtmlString, "text/HTML", "UTF-8")

to

mWebView!!.loadDataWithBaseURL(
            "file:///android_asset/",
            mHtmlString,
            "text/html",
            "UTF-8",
            ""
        )

With this command I can get html-to-pdf-conversion without limit to the characters

Upvotes: 2

Alex Timonin
Alex Timonin

Reputation: 1968

Your conversion code seems to be running on the UI thread, and that's a problem. Please make sure you move the work to a background thread. There are a ton of possibilities for that: kotlin coroutines, IntentService, HandlerThread, AsyncTask, etc etc

Since your converter is a runnable, the easiest way would be to create a HandlerThread, and instead of calling your converter from the main thread

val handler = Handler(mContext!!.mainLooper)
handler.post(this)

call it from your newly created handlerThread

val handler = Handler(handlerThread.looper)
handler.post(this)

Also, be sure to call handlerThread.quit() in your activity/fragment's onDestroy!

Upvotes: 1

Related Questions