Ir al contenido
NexPDF

Estructura del documento

Lee y establece metadatos, marcadores y etiquetas de página, muestra y oculta capas, e incrusta o extrae archivos adjuntos con NexPDF para Android.

Español

Módulo de licencia

Leer metadatos, marcadores, etiquetas de página, capas y adjuntos, y activar o desactivar capas, funciona sin clave. Cambiar metadatos, marcadores, etiquetas de página y adjuntos necesita el módulo editor (nivel Startup y superiores).

Todas las llamadas siguientes son métodos estáticos de NexPdfJni que reciben doc.handle(). Los resultados JSON se analizan con org.json.

Metadatos

metadataJson(handle) devuelve el diccionario de información del documento (título, autor, asunto, palabras clave y las demás entradas que tenga el archivo). setMetadata(handle, title, author, subject, keywords) lo cambia; null conserva el valor actual.

import com.nexdevit.nexpdf.NexPdfDocument
import com.nexdevit.nexpdf.NexPdfJni
import org.json.JSONArray
import org.json.JSONObject

NexPdfDocument.openBytes(bytes).use { doc ->
    val h = doc.handle()
    val info = JSONObject(NexPdfJni.metadataJson(h))
    Log.i("NexPDF", "${info.optString("title")} ${info.optString("author")}")

    NexPdfJni.setMetadata(h, "Q3 report", "Finance", null, null)
    val titled = doc.saveBytes()
}

Marcadores

Los marcadores (el esquema) son un árbol JSON de title, page (empezando en 0) y children opcionales. setOutlinesJson reemplaza todo el árbol.

fun walk(items: JSONArray, depth: Int = 0) {
    for (i in 0 until items.length()) {
        val item = items.getJSONObject(i)
        Log.i("NexPDF", "  ".repeat(depth) + "${item.getString("title")} (page ${item.getInt("page") + 1})")
        item.optJSONArray("children")?.let { walk(it, depth + 1) }
    }
}
walk(JSONArray(NexPdfJni.outlinesJson(h)))

NexPdfJni.setOutlinesJson(h, """[{"title":"Summary","page":0},{"title":"Details","page":2,"children":[{"title":"Costs","page":3}]}]""")

Etiquetas de página

Las etiquetas de página son los números de página que muestra un visor, como i, ii para un prefacio y 1, 2 a continuación. pageLabelsJson() devuelve la etiqueta de cada página y los rangos que las producen, y setPageLabelsJson(rangesJson) establece los rangos (NexPdfJni.pageLabelsJson(handle) y setPageLabelsJson(handle, rangesJson) para un identificador sin envolver):

val labels = JSONObject(doc.pageLabelsJson())
Log.i("NexPDF", labels.getJSONArray("labels").toString())       // e.g. ["i","ii","1","2"]

check(doc.setPageLabelsJson("""[{"start":0,"style":"roman"},{"start":2,"style":"decimal","first":1}]""")) {
    NexPdfJni.lastError()
}
val labelled = doc.saveBytes()

Los estilos son decimal, roman, ROMAN, letters, LETTERS y none. Un rango también puede tener un prefix, por ejemplo "A-". [] elimina las etiquetas.

Capas

Las capas (grupos de contenido opcional) son partes de una página que se pueden mostrar u ocultar, algo habitual en planos de CAD y mapas. Cada capa se identifica por su número de objeto y su generación.

val layers = JSONArray(NexPdfJni.layersJson(h))
for (i in 0 until layers.length()) {
    val layer = layers.getJSONObject(i)
    Log.i("NexPDF", "${layer.getString("name")} ${if (layer.getBoolean("visible")) "visible" else "hidden"}")
}

val notes = (0 until layers.length()).map { layers.getJSONObject(it) }.first { it.getString("name") == "Notes" }
NexPdfJni.setLayerVisible(h, notes.getInt("num"), notes.getInt("gen"), false)   // hide; true shows it again
val png = NexPdfJni.renderPagePng(h, 0, 144.0)                                  // rendered without the layer

Adjuntos

Los PDF pueden llevar archivos: a nivel de documento (una lista de adjuntos) o en una página (una anotación de clip). attachmentsJson(handle) enumera ambos; page es null para los archivos a nivel de documento.

val list = JSONArray(NexPdfJni.attachmentsJson(h))
for (i in 0 until list.length()) {
    val a = list.getJSONObject(i)
    Log.i("NexPDF", "${a.getString("name")} ${a.optString("mime")} ${a.optLong("size")} ${a.opt("page")}")
}

File(filesDir, "invoice.xml").writeBytes(NexPdfJni.attachmentData(h, "invoice.xml"))

NexPdfJni.addAttachment(h, "data.csv", csvBytes, "text/csv", "Source data")
NexPdfJni.removeAttachment(h, "old.csv")
val withData = doc.saveBytes()

Para adjuntar un archivo a una página con un icono visible, usa addFileAttachmentAnnot; consulta Anotaciones. El lector muestra los marcadores y los adjuntos al usuario.

En esta página