Rendering pages
Render PDF pages and thumbnails to PNG and Bitmap with NexPDF for Android, and map PDF coordinates to view pixels.
License module
Rendering is part of the viewer module and works without a key. Unlicensed and trial renders carry
a watermark; commercial keys render without one.
Render a page
renderPagePng(pageIndex, dpi) returns the PNG bytes of a page. At 72 dpi one pixel is one PDF
point. For a sharp image, multiply 72 by the screen density and the zoom:
import android.graphics.BitmapFactory
import com.nexdevit.nexpdf.NexPdfDocument
val dpi = 72.0 * resources.displayMetrics.density
val png = doc.renderPagePng(0, dpi)
val bitmap = BitmapFactory.decodeByteArray(png, 0, png.size)Rendering is synchronous. Run it off the main thread:
lifecycleScope.launch {
val bitmap = withContext(Dispatchers.Default) {
val png = doc.renderPagePng(3, 144.0)
BitmapFactory.decodeByteArray(png, 0, png.size)
}
imageView.setImageBitmap(bitmap)
}Render a thumbnail
NexPdfJni.renderThumbPng(handle, pageIndex, maxDim) fits the page into a square of maxDim
pixels, keeping the aspect ratio:
val thumb = NexPdfJni.renderThumbPng(doc.handle(), 0, 256)Page size and orientation
pageWidth(i) and pageHeight(i) return the displayed size in points, with the crop box,
/Rotate and /UserUnit applied. pageView(i) returns a PageView with the rotation, the crop
box and the transform from PDF user space to the displayed page:
val view = doc.pageView(0)
Log.i("NexPDF", "${view.width} x ${view.height}, rotation ${view.rotation}")
val k = dpi / 72 // pixels per point
val (x, y) = view.toView(k, 72.0, 700.0) // PDF point to bitmap pixels, origin top-left
val pdf = view.toPdf(k, tapX.toDouble(), tapY.toDouble()) // a tap back to PDF pointsrectToView and rectToPdf convert rectangles the same way, for example to draw a search hit on
the bitmap.
Memory
Decoded fonts, glyphs and images are cached by the renderer for the whole process, within a size
limit, so a font or picture used on many pages is decoded once. NexPdfJni.memoryUsageBytes(handle)
estimates what a document uses, and NexPdfJni.trimMemory(doc.handle()) compacts its buffers from
onTrimMemory. See Platform notes.
Overprint simulation
Renders simulate overprint for PDF/X documents only, the engine default.
NexPdfJni.setOverprint(handle, mode) changes it for later renders of that document. Mode 0 is the
default, 1 always simulates, 2 never:
NexPdfJni.setOverprint(doc.handle(), 1)
val png = doc.renderPagePng(0, 300.0)