Getting started
Activate a license, open a PDF, count its pages, render a page to a Bitmap and extract its text with NexPDF for Android.
This example opens a PDF from the app's assets, logs the page count, renders the first page to a
Bitmap and logs the text of every page. It runs without a license key too: viewing is always
allowed, and rendered pages then carry a watermark.
Add the dependency
Add com.nexdevit:nexpdf-android:1.1.0 as described in Installation,
and put sample.pdf (and, if you have one, nexpdf_license.xml) in app/src/main/assets/.
Activate the license at start-up
import android.app.Application
import android.util.Log
import com.nexdevit.nexpdf.NexPdfJni
import com.nexdevit.nexpdf.NexPdfLicense
class App : Application() {
override fun onCreate() {
super.onCreate()
val rc = NexPdfLicense.initialize(this) // assets/nexpdf_license.xml or manifest meta-data
if (rc < 0) Log.w("NexPDF", "license not active ($rc): ${NexPdfJni.lastError()}")
}
}Register the class with android:name=".App" on <application> in the manifest.
Open, render and extract
import android.graphics.BitmapFactory
import com.nexdevit.nexpdf.NexPdfDocument
val bytes = assets.open("sample.pdf").use { it.readBytes() }
NexPdfDocument.openBytes(bytes).use { doc ->
val count = doc.pageCount()
Log.i("NexPDF", "$count pages, first page ${doc.pageWidth(0)} x ${doc.pageHeight(0)} pt")
val png = doc.renderPagePng(0, 144.0)
imageView.setImageBitmap(BitmapFactory.decodeByteArray(png, 0, png.size))
for (i in 0 until count) {
Log.i("NexPDF", "--- page ${i + 1} ---\n" + doc.pageText(i))
}
}What the code does
NexPdfLicense.initialize(context)reads the key from the manifest meta-datacom.nexdevit.nexpdf.license_key, else fromassets/nexpdf_license.xml, and activates it for the platformandroidand the app's package name. See License.NexPdfDocument.openBytes(bytes)opens a PDF. JPEG, PNG and TIFF pictures become one page each. Word, Excel and PowerPoint files, EPUB and FictionBook books, XPS packages and CBZ comics are converted (conversionmodule), andopenBytes(bytes, password)opens encrypted PDFs.pageWidth(i)andpageHeight(i)are the displayed size in points: crop box, rotation and/UserUnitapplied.renderPagePng(i, dpi)returns PNG bytes. 72 dpi is one pixel per point.pageText(i)returns the page text in reading order.saveBytes()returns the document, with your changes, as PDF bytes.
Rendering and text extraction run on the calling thread: in a real app, call them from a
background thread or a coroutine on Dispatchers.Default.