【问题标题】:Android : Very large html(>25k lines) to pdf is not generatedAndroid:未生成非常大的 html(> 25k 行)到 pdf
【发布时间】:2020-05-18 07:48:22
【问题描述】:

我有一个要转换为 pdf 的 html。 html 是数千行。我观察到,对于少于 25k(或多或少)行的 html 代码,生成 pdf 大约需要 2-3 秒。当 html 超过上述阈值时,永远不会生成 html 并且程序永远运行(我等了 10 分钟)。现在对不起,我无法向您提供上述阈值的确切行数,因为 html 是随机生成的。我检查了 html 是否正确,然后将其粘贴到 html 查看器中,它可以正常工作。

一开始,我使用经典的 pdfConverter 生成 pdf:https://github.com/blink22/react-native-html-to-pdf/blob/master/android/src/main/java/android/print/PdfConverter.java

我修改了代码以查看发生了什么,并实现了 WebviewClient 的所有功能。这是我修改后的代码:

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
            }
    }
}


我用下面的代码调用上面的代码

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
    }

pdfConverter 中的调试日志均未调用。我试着知道发生了什么,当我有大的 html 时,代码会永远运行。您是否建议我更改 html 转换程序?

编辑 我将代码更改为第一个答案:

 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
        }

但也没有任何效果...问题仍然存在...当 pdf 略大于 25k 行 html 代码时,程序将永远运行。对于这次尝试,我还评论了除了 on pagefinished 之外的所有 webviewclient 覆盖。

同样在 Android Studio 的“运行”中显示如下:

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

【问题讨论】:

    标签: android html kotlin webview webviewclient


    【解决方案1】:

    您的转换代码似乎在 UI 线程上运行,这是一个问题。请确保将工作移至后台线程。有很多可能性:kotlin 协程、IntentService、HandlerThread、AsyncTask 等等

    由于您的转换器是可运行的,最简单的方法是创建一个 HandlerThread,而不是从主线程调用您的转换器

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

    从你新创建的 handlerThread 调用它

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

    另外,请务必在您的活动/片段的 onDestroy 中调用 handlerThread.quit()

    【讨论】:

    • 感谢您的评论。我会试试的,我会告诉你的。
    • 我修改了代码,就像我的编辑显示的那样。我的问题是我的旧代码如何处理 25k 行,如果我添加了数百个 html 代码,比如说 25.3k,那么问题就变成了执行代码在 UI 线程上的问题?
    • 我发现了一些有用的东西...在运行 android studio 时显示一条消息:“W/chromium: [WARNING:navigation_controller_impl.cc(2579)] 拒绝加载超过 2097152 个字符的 URL 。”
    • 有趣。似乎您需要找到另一个不依赖 WebView 的转换器实现
    【解决方案2】:

    我不得不在 PdfConverter 中更改以下行:

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

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

    使用此命令,我可以在不限制字符的情况下进行 html 到 pdf 的转换

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-13
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      • 2010-11-11
      相关资源
      最近更新 更多