Estructura del documento
Lee y establece metadatos, marcadores y etiquetas de página, muestra y oculta capas, e incrusta o extrae archivos adjuntos mediante la API de C de NexPDF con NexPDF para Flutter.
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).
Las funciones de estructura no tienen método de Dart. Llámalas
mediante dart:ffi sobre doc.handle y guarda
después con doc.save(). Los ejemplos usan estas búsquedas de funciones:
import 'dart:convert';
import 'dart:ffi';
import 'dart:typed_data';
import 'package:ffi/ffi.dart';
import 'package:nexpdf_flutter/nexpdf_flutter.dart';
import 'nexpdf_ffi.dart';
typedef _DocJsonNative = Pointer<Utf8> Function(Pointer<Void>);
typedef _DocSetJsonNative = Int32 Function(Pointer<Void>, Pointer<Utf8>);
typedef _DocSetJson = int Function(Pointer<Void>, Pointer<Utf8>);
/// Calls a `char *f(const NexPdfDocument *)` function and decodes its JSON.
Object? docJson(NexPdfDocument doc, String name) {
final f = nexpdfLib.lookupFunction<_DocJsonNative, _DocJsonNative>(name);
return jsonDecode(nexpdfCall(() => takeString(f(doc.handle))) ?? 'null');
}
/// Calls an `int32_t f(NexPdfDocument *, const char *json)` function.
void setDocJson(NexPdfDocument doc, String name, Object value) {
final f = nexpdfLib.lookupFunction<_DocSetJsonNative, _DocSetJson>(name);
using((a) => nexpdfCall(() => f(doc.handle, jsonEncode(value).toNativeUtf8(allocator: a))));
}Metadatos
nexpdf_metadata_json devuelve el diccionario de información del documento (título, autor, asunto,
palabras clave y las demás entradas que tenga el archivo). nexpdf_set_metadata(doc, title, author, subject, keywords) lo modifica; un puntero nulo (nullptr) conserva el valor actual.
final info = docJson(doc, 'nexpdf_metadata_json') as Map<String, Object?>;
print('${info['title']} ${info['author']}');
// int32_t nexpdf_set_metadata(NexPdfDocument *doc, const char *title, const char *author,
// const char *subject, const char *keywords);
final setMetadata = nexpdfLib.lookupFunction<
Int32 Function(Pointer<Void>, Pointer<Utf8>, Pointer<Utf8>, Pointer<Utf8>, Pointer<Utf8>),
int Function(Pointer<Void>, Pointer<Utf8>, Pointer<Utf8>, Pointer<Utf8>, Pointer<Utf8>)>('nexpdf_set_metadata');
using((a) => nexpdfCall(() => setMetadata(doc.handle,
'Q3 report'.toNativeUtf8(allocator: a), 'Finance'.toNativeUtf8(allocator: a), nullptr, nullptr)));
final titled = doc.save();Marcadores
Los marcadores (el esquema) son un árbol JSON con title, page (desde 0) y children opcional.
nexpdf_set_outlines_json reemplaza todo el árbol.
void walk(List<Object?> items, [int depth = 0]) {
for (final item in items.cast<Map<String, Object?>>()) {
print('${' ' * depth}${item['title']} (page ${(item['page'] as int) + 1})');
walk((item['children'] as List?) ?? const [], depth + 1);
}
}
walk(docJson(doc, 'nexpdf_outlines_json') as List);
setDocJson(doc, 'nexpdf_set_outlines_json', [
{'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 después. nexpdf_page_labels_json devuelve la etiqueta de cada página y los
rangos que las producen.
final labels = docJson(doc, 'nexpdf_page_labels_json') as Map<String, Object?>;
print((labels['labels'] as List).take(4)); // e.g. (i, ii, 1, 2)
setDocJson(doc, 'nexpdf_set_page_labels_json', [
{'start': 0, 'style': 'roman'},
{'start': 2, 'style': 'decimal', 'first': 1},
]);
setDocJson(doc, 'nexpdf_set_page_labels_json', []); // removes the labelsLos estilos son decimal, roman, ROMAN, letters, LETTERS y none. Un rango también puede
tener un prefix, por ejemplo "A-".
Capas
Las capas (grupos de contenido opcional) son partes de una página que se pueden mostrar u ocultar, habituales en planos de CAD y mapas. Cada capa se identifica por su número de objeto y su generación.
final layers = (docJson(doc, 'nexpdf_layers_json') as List).cast<Map<String, Object?>>();
for (final layer in layers) {
print('${layer['name']} ${layer['visible'] == true ? 'visible' : 'hidden'}');
}
// int32_t nexpdf_set_layer_visible(NexPdfDocument *doc, uint32_t num, uint16_t generation, int32_t visible);
final setLayerVisible = nexpdfLib.lookupFunction<Int32 Function(Pointer<Void>, Uint32, Uint16, Int32),
int Function(Pointer<Void>, int, int, int)>('nexpdf_set_layer_visible');
final notes = layers.firstWhere((l) => l['name'] == 'Notes');
nexpdfCall(() => setLayerVisible(doc.handle, notes['num'] as int, notes['gen'] as int, 0)); // 1 shows it
final png = doc.renderPagePng(0, dpi: 144); // rendered without the layerAdjuntos
Los PDF pueden contener archivos: a nivel de documento (una lista de adjuntos) o en una página (una
anotación de clip). nexpdf_attachments_json enumera ambos; page es null para los archivos de
nivel de documento.
for (final a in (docJson(doc, 'nexpdf_attachments_json') as List).cast<Map<String, Object?>>()) {
print('${a['name']} ${a['mime']} ${a['size']} ${a['page']}');
}
// NexPdfBytes nexpdf_attachment_data(const NexPdfDocument *doc, const char *name);
final attachmentData = nexpdfLib.lookupFunction<NexPdfBytes Function(Pointer<Void>, Pointer<Utf8>),
NexPdfBytes Function(Pointer<Void>, Pointer<Utf8>)>('nexpdf_attachment_data');
// int32_t nexpdf_add_attachment(NexPdfDocument *doc, const char *name, const uint8_t *data,
// size_t len, const char *mime, const char *description);
final addAttachment = nexpdfLib.lookupFunction<
Int32 Function(Pointer<Void>, Pointer<Utf8>, Pointer<Uint8>, Size, Pointer<Utf8>, Pointer<Utf8>),
int Function(Pointer<Void>, Pointer<Utf8>, Pointer<Uint8>, int, Pointer<Utf8>, Pointer<Utf8>)>('nexpdf_add_attachment');
// int32_t nexpdf_remove_attachment(NexPdfDocument *doc, const char *name);
final removeAttachment = nexpdfLib.lookupFunction<_DocSetJsonNative, _DocSetJson>('nexpdf_remove_attachment');
final Uint8List xml = using((a) =>
nexpdfCall(() => takeBytes(attachmentData(doc.handle, 'invoice.xml'.toNativeUtf8(allocator: a)))));
using((a) => nexpdfCall(() => addAttachment(doc.handle, 'data.csv'.toNativeUtf8(allocator: a),
toNative(csvBytes, a), csvBytes.length, 'text/csv'.toNativeUtf8(allocator: a),
'Source data'.toNativeUtf8(allocator: a))));
using((a) => nexpdfCall(() => removeAttachment(doc.handle, 'old.csv'.toNativeUtf8(allocator: a))));
final withData = doc.save();Para adjuntar un archivo a una página con un icono visible, usa nexpdf_add_file_attachment_annot;
consulta Anotaciones.
En el lector
El lector nativo incluye marcadores y adjuntos, así que los usuarios pueden explorarlos sin escribir código.
Relacionado
- Edición: páginas, texto e imágenes
- Abrir y guardar
Renderizado de páginas
Renderiza páginas PDF a PNG con NexPDF para Flutter, muéstralas en un widget Image y convierte las coordenadas PDF en píxeles del widget.
Extracción de texto
Extrae Markdown, el texto de las páginas y bloques de texto posicionados con NexPDF para Flutter, y recupera pasajes para un modelo de lenguaje.