Android:不会生成很大的html(> 25k行)到pdf的文件

问题描述 投票:1回答:1

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

起初,我使用经典的pdfConverter: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转换过程?

android html kotlin webview webviewclient
1个回答
0
投票

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

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

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

从您新创建的handlerThread中调用

val handler = Handler(handlerThread.looper)
handler.post(this)
© www.soinside.com 2019 - 2024. All rights reserved.