安卓:不会生成非常大的html(>25k行)到pdf



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

起初,对于pdf的生成,我使用了经典的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 pagedone 之外的所有 webviewclient 覆盖。

同样在Android Studio的"运行"中,显示以下内容:

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

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

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

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

从新创建的处理程序线程调用它

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

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

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

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

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

使用此命令,我可以不受字符限制地获得 html 到 pdf 的转换

最新更新