Pular para o conteúdo
NexPDF

Estrutura do documento

Leia e defina metadados, marcadores e rótulos de página, mostre e oculte camadas, e incorpore ou extraia anexos de arquivo pela API C do NexPDF com o NexPDF para Flutter.

Português

Módulo de licença

Ler metadados, marcadores, rótulos de página, camadas e anexos, e ativar ou desativar camadas, funciona sem chave. Alterar metadados, marcadores, rótulos de página e anexos precisa do módulo editor (nível Startup e superiores).

As funções de estrutura não têm método Dart. Chame-as por meio de dart:ffi sobre doc.handle e depois salve com doc.save(). Os exemplos usam estas buscas de função:

lib/nexpdf_structure.dart
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))));
}

Metadados

nexpdf_metadata_json retorna o dicionário de informações do documento (título, autor, assunto, palavras-chave e as outras entradas que o arquivo tem). nexpdf_set_metadata(doc, title, author, subject, keywords) o altera; um ponteiro nulo (nullptr) mantém o valor atual.

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

Os marcadores (a estrutura de tópicos) são uma árvore JSON de title, page (a partir de 0) e children opcional. nexpdf_set_outlines_json substitui a árvore inteira.

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}]},
]);

Rótulos de página

Os rótulos de página são os números de página que um visualizador mostra, como i, ii para um prefácio e 1, 2 depois dele. nexpdf_page_labels_json retorna o rótulo de cada página e os intervalos que os produzem.

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 labels

Os estilos são decimal, roman, ROMAN, letters, LETTERS e none. Um intervalo também pode ter um prefix, por exemplo "A-".

Camadas

As camadas (grupos de conteúdo opcional) são partes de uma página que podem ser mostradas ou ocultadas, comuns em desenhos CAD e mapas. Cada camada é identificada pelo número de objeto e pela geração.

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 layer

Anexos

Os PDFs podem carregar arquivos: no nível do documento (uma lista de anexos) ou em uma página (uma anotação de clipe de papel). nexpdf_attachments_json lista os dois; page é null para arquivos no nível do 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 anexar um arquivo a uma página com um ícone visível, use nexpdf_add_file_attachment_annot; veja Anotações.

No leitor

O leitor nativo já traz marcadores e anexos, então os usuários podem navegar por eles sem nenhum código.

Nesta página