|
1 | 1 | package com.margelo.nitro.nitrohtmlpdf |
2 | | - |
3 | | -import com.facebook.proguard.annotations.DoNotStrip |
4 | 2 |
|
5 | | -@DoNotStrip |
| 3 | +import android.content.Context |
| 4 | +import android.graphics.Paint |
| 5 | +import android.graphics.pdf.PdfDocument |
| 6 | +import android.os.Handler |
| 7 | +import android.os.Looper |
| 8 | +import android.webkit.WebView |
| 9 | +import android.webkit.WebViewClient |
| 10 | +import com.margelo.nitro.core.Promise |
| 11 | +import java.io.File |
| 12 | +import java.io.FileOutputStream |
| 13 | +import java.util.concurrent.CountDownLatch |
| 14 | +import java.util.concurrent.TimeUnit |
| 15 | +import kotlin.math.ceil |
| 16 | + |
6 | 17 | class NitroHtmlPdf : HybridNitroHtmlPdfSpec() { |
7 | | - override fun multiply(a: Double, b: Double): Double { |
8 | | - return a * b |
9 | | - } |
| 18 | + companion object { |
| 19 | + @JvmStatic |
| 20 | + var appContext: Context? = null |
| 21 | + } |
| 22 | + |
| 23 | + private val context: Context |
| 24 | + get() = appContext ?: throw IllegalStateException("Context not initialized. Call NitroHtmlPdf.appContext = context first.") |
| 25 | + |
| 26 | + override fun generatePdf(options: PdfOptions): Promise<PdfResult> { |
| 27 | + return Promise.async { |
| 28 | + createPdf(options) |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + private fun createPdf(options: PdfOptions): PdfResult { |
| 33 | + val latch = CountDownLatch(1) |
| 34 | + var result: PdfResult? = null |
| 35 | + |
| 36 | + Handler(Looper.getMainLooper()).post { |
| 37 | + try { |
| 38 | + val pageSizeString = options.pageSize?.name ?: "A4" |
| 39 | + val pageSize = getPageSize(pageSizeString, options.width, options.height) |
| 40 | + val headerHeight = options.headerHeight?.toFloat() ?: 0f |
| 41 | + val footerHeight = options.footerHeight?.toFloat() ?: 0f |
| 42 | + |
| 43 | + var headerWebView: WebView? = null |
| 44 | + var footerWebView: WebView? = null |
| 45 | + val webViews = mutableListOf<WebView>() |
| 46 | + |
| 47 | + if (!options.header.isNullOrEmpty() && headerHeight > 0) { |
| 48 | + headerWebView = createWebView(pageSize.width.toInt(), headerHeight.toInt()) |
| 49 | + val wrappedHeader = "<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1'><style>*{margin:0!important;padding:0!important;box-sizing:border-box;}html,body{margin:0!important;padding:0!important;width:100%;height:100%;overflow:hidden;}</style></head><body>${options.header}</body></html>" |
| 50 | + headerWebView.loadDataWithBaseURL(null, wrappedHeader, "text/html", "UTF-8", null) |
| 51 | + webViews.add(headerWebView) |
| 52 | + } |
| 53 | + |
| 54 | + if (!options.footer.isNullOrEmpty() && footerHeight > 0) { |
| 55 | + footerWebView = createWebView(pageSize.width.toInt(), footerHeight.toInt()) |
| 56 | + val wrappedFooter = "<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1'><style>*{margin:0!important;padding:0!important;box-sizing:border-box;}html,body{margin:0!important;padding:0!important;width:100%;height:100%;overflow:hidden;}</style></head><body>${options.footer}</body></html>" |
| 57 | + footerWebView.loadDataWithBaseURL(null, wrappedFooter, "text/html", "UTF-8", null) |
| 58 | + webViews.add(footerWebView) |
| 59 | + } |
| 60 | + |
| 61 | + val contentWebView = createWebView(pageSize.width.toInt(), pageSize.height.toInt()) |
| 62 | + contentWebView.loadDataWithBaseURL(null, options.html, "text/html", "UTF-8", null) |
| 63 | + webViews.add(contentWebView) |
| 64 | + |
| 65 | + val loadLatch = CountDownLatch(webViews.size) |
| 66 | + webViews.forEach { webView -> |
| 67 | + webView.webViewClient = object : WebViewClient() { |
| 68 | + override fun onPageFinished(view: WebView?, url: String?) { |
| 69 | + loadLatch.countDown() |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + Thread { |
| 75 | + loadLatch.await(5, TimeUnit.SECONDS) |
| 76 | + Thread.sleep(500) |
| 77 | + Handler(Looper.getMainLooper()).post { |
| 78 | + result = renderPdf(contentWebView, headerWebView, footerWebView, options) |
| 79 | + webViews.forEach { it.destroy() } |
| 80 | + latch.countDown() |
| 81 | + } |
| 82 | + }.start() |
| 83 | + |
| 84 | + } catch (e: Exception) { |
| 85 | + result = PdfResult("", false, e.message) |
| 86 | + latch.countDown() |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + latch.await() |
| 91 | + return result ?: PdfResult("", false, "Failed to create PDF") |
| 92 | + } |
| 93 | + |
| 94 | + private fun createWebView(width: Int, height: Int): WebView { |
| 95 | + return WebView(context).apply { |
| 96 | + settings.javaScriptEnabled = true |
| 97 | + settings.loadWithOverviewMode = false |
| 98 | + settings.useWideViewPort = false |
| 99 | + settings.domStorageEnabled = true |
| 100 | + settings.setSupportZoom(false) |
| 101 | + setInitialScale(100) |
| 102 | + measure( |
| 103 | + android.view.View.MeasureSpec.makeMeasureSpec(width, android.view.View.MeasureSpec.EXACTLY), |
| 104 | + android.view.View.MeasureSpec.makeMeasureSpec(height, android.view.View.MeasureSpec.EXACTLY) |
| 105 | + ) |
| 106 | + layout(0, 0, width, height) |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + private fun renderPdf( |
| 111 | + webView: WebView, |
| 112 | + headerWebView: WebView?, |
| 113 | + footerWebView: WebView?, |
| 114 | + options: PdfOptions |
| 115 | + ): PdfResult { |
| 116 | + return try { |
| 117 | + val pageSizeString = options.pageSize?.name ?: "A4" |
| 118 | + val pageSize = getPageSize(pageSizeString, options.width, options.height) |
| 119 | + val headerHeight = options.headerHeight?.toFloat() ?: 0f |
| 120 | + val footerHeight = options.footerHeight?.toFloat() ?: 0f |
| 121 | + val marginTop = (options.marginTop?.toFloat() ?: 0f) + headerHeight |
| 122 | + val marginBottom = (options.marginBottom?.toFloat() ?: 0f) + footerHeight + if (options.showPageNumbers == true) 20f else 0f |
| 123 | + val marginLeft = options.marginLeft?.toFloat() ?: 0f |
| 124 | + val marginRight = options.marginRight?.toFloat() ?: 0f |
| 125 | + |
| 126 | + webView.measure( |
| 127 | + android.view.View.MeasureSpec.makeMeasureSpec(pageSize.width.toInt(), android.view.View.MeasureSpec.EXACTLY), |
| 128 | + android.view.View.MeasureSpec.makeMeasureSpec(0, android.view.View.MeasureSpec.UNSPECIFIED) |
| 129 | + ) |
| 130 | + webView.layout(0, 0, pageSize.width.toInt(), webView.measuredHeight) |
| 131 | + |
| 132 | + val contentHeight = webView.measuredHeight.toFloat() |
| 133 | + val printableHeight = pageSize.height - marginTop - marginBottom |
| 134 | + val totalPages = ceil(contentHeight / printableHeight).toInt().coerceAtLeast(1) |
| 135 | + |
| 136 | + val pdfDocument = PdfDocument() |
| 137 | + |
| 138 | + for (pageIndex in 0 until totalPages) { |
| 139 | + val pageInfo = PdfDocument.PageInfo.Builder( |
| 140 | + pageSize.width.toInt(), |
| 141 | + pageSize.height.toInt(), |
| 142 | + pageIndex |
| 143 | + ).create() |
| 144 | + |
| 145 | + val page = pdfDocument.startPage(pageInfo) |
| 146 | + val canvas = page.canvas |
| 147 | + |
| 148 | + canvas.save() |
| 149 | + canvas.translate(marginLeft, marginTop) |
| 150 | + canvas.clipRect(0f, 0f, pageSize.width - marginLeft - marginRight, printableHeight) |
| 151 | + canvas.translate(0f, -(pageIndex * printableHeight)) |
| 152 | + webView.draw(canvas) |
| 153 | + canvas.restore() |
| 154 | + |
| 155 | + if (headerWebView != null && headerHeight > 0) { |
| 156 | + canvas.save() |
| 157 | + canvas.translate(marginLeft, 0f) |
| 158 | + headerWebView.draw(canvas) |
| 159 | + canvas.restore() |
| 160 | + } |
| 161 | + |
| 162 | + if (options.showPageNumbers == true) { |
| 163 | + val currentPage = pageIndex + 1 |
| 164 | + var pageText = options.pageNumberFormat ?: "Page {page} of {total}" |
| 165 | + pageText = pageText.replace("{page}", currentPage.toString()) |
| 166 | + pageText = pageText.replace("{total}", totalPages.toString()) |
| 167 | + |
| 168 | + val paint = Paint().apply { |
| 169 | + textSize = options.pageNumberFontSize?.toFloat() ?: 12f |
| 170 | + color = android.graphics.Color.BLACK |
| 171 | + textAlign = Paint.Align.CENTER |
| 172 | + } |
| 173 | + val x = pageSize.width / 2 |
| 174 | + val y = pageSize.height - footerHeight - 5f |
| 175 | + canvas.drawText(pageText, x, y, paint) |
| 176 | + } |
| 177 | + |
| 178 | + if (footerWebView != null && footerHeight > 0) { |
| 179 | + canvas.save() |
| 180 | + canvas.translate(marginLeft, pageSize.height - footerHeight) |
| 181 | + footerWebView.draw(canvas) |
| 182 | + canvas.restore() |
| 183 | + } |
| 184 | + |
| 185 | + pdfDocument.finishPage(page) |
| 186 | + } |
| 187 | + |
| 188 | + val directory = options.directory ?: context.cacheDir?.absolutePath ?: "/data/local/tmp" |
| 189 | + val file = File(directory, options.fileName) |
| 190 | + FileOutputStream(file).use { pdfDocument.writeTo(it) } |
| 191 | + pdfDocument.close() |
| 192 | + |
| 193 | + PdfResult(file.absolutePath, true, null) |
| 194 | + } catch (e: Exception) { |
| 195 | + PdfResult("", false, e.message) |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + private fun getPageSize(size: String, width: Double?, height: Double?): Size { |
| 200 | + if (width != null && height != null) { |
| 201 | + return Size(width.toFloat(), height.toFloat()) |
| 202 | + } |
| 203 | + |
| 204 | + return when (size) { |
| 205 | + "A4" -> Size(595f, 842f) |
| 206 | + "LETTER" -> Size(612f, 792f) |
| 207 | + "LEGAL" -> Size(612f, 1008f) |
| 208 | + "A3" -> Size(842f, 1191f) |
| 209 | + "A5" -> Size(420f, 595f) |
| 210 | + else -> Size(595f, 842f) |
| 211 | + } |
| 212 | + } |
| 213 | + |
| 214 | + private data class Size(val width: Float, val height: Float) |
10 | 215 | } |
0 commit comments