> ## Documentation Index
> Fetch the complete documentation index at: https://docs.markpdf.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# Ejemplos

> Casos de uso reales para el paquete Flutter/Dart: file_picker, archivos PDF grandes, BYOS, RAG y ZIP.

# Ejemplos

## Selecciona y convierte un PDF (`file_picker`)

```dart theme={null}
import 'package:file_picker/file_picker.dart';
import 'package:markpdf/markpdf.dart';

final client = MarkpdfClient(apiKey: 'YOUR_API_KEY');

Future<String?> pickAndConvert() async {
  final result = await FilePicker.platform.pickFiles(
    type: FileType.custom,
    allowedExtensions: ['pdf'],
    withData: true, // necesario para obtener bytes en Web
  );
  if (result == null) return null;

  final picked = result.files.single;
  final convertResult = await client.convertBytes(
    picked.bytes!,
    picked.name,
    options: const ConvertOptions(mode: ConversionMode.fast),
  );

  return switch (convertResult) {
    MarkdownResult(:final markdown) => markdown,
    JsonConvertResult(:final result) => result.markdown,
    QueuedResult() => null, // no debería pasar con autoPoll: true (default)
  };
}
```

`withData: true` es necesario para que `file_picker` devuelva los bytes en la memoria, algo esencial en Flutter Web, donde no hay un sistema de archivos.

## Mostrar el Markdown convertido en pantalla

```dart theme={null}
class ConvertScreen extends StatefulWidget {
  const ConvertScreen({super.key});

  @override
  State<ConvertScreen> createState() => _ConvertScreenState();
}

class _ConvertScreenState extends State<ConvertScreen> {
  final client = MarkpdfClient(apiKey: 'YOUR_API_KEY');
  String? markdown;
  bool loading = false;

  Future<void> convert(Uint8List bytes, String filename) async {
    setState(() => loading = true);
    try {
      final result = await client.convertBytes(bytes, filename);
      if (result is MarkdownResult) {
        setState(() => markdown = result.markdown);
      }
    } on MarkpdfException catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Error: ${e.message}')),
      );
    } finally {
      setState(() => loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: loading
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: SelectableText(markdown ?? 'Selecciona un PDF'),
            ),
    );
  }
}
```

## PDF grande con rango de páginas

```dart theme={null}
final result = await client.convertFromUrl(
  'https://bucket.example.com/manual-800-papages.pdf?sig=...',
  filename: 'manual.pdf',
  options: const ConvertOptions(pages: '120-145', mode: ConversionMode.fast),
);
```

Combínelo con [`pdfIndex`](/docs/public/es/sdks/flutter/reference#pdfindex) para saber qué rango pedir sin descargar el PDF completo al dispositivo.

## BYOS: sube el resultado directamente a tu almacenamiento

Genere el URL prefirmado desde su backend y páselo al cliente:

```dart theme={null}
final result = await client.convertFromUrl(
  pdfUrl,
  options: ConvertOptions(
    responseFormat: ResponseFormat.json,
  ),
);
```

<Note>
  `ConvertOptions` no expone `outputUrl` directamente porque en las aplicaciones móviles el URL prefirmado generalmente se genera y consume en su backend, no en el dispositivo. Si necesita BYOS del cliente, considere exponer su propio punto final que recibe PDF, cree el URL prefirmado desde su almacenamiento y llame a API con [Node.js](/docs/public/es/sdks/nodejs/examples#byos-subir-el-resultado-directo-a-tu-storage) o [Python](/docs/public/es/sdks/python/examples).
</Note>

## Canalización RAG con `pdfIndex`

```dart theme={null}
final spine = await client.pdfIndex('https://bucket.example.com/informe-anual.pdf?sig=...');
print('${spine.pageCount} pápages, ~${spine.estimatedTokensFull} full tokens');

final target = spine.sections.firstWhere((s) => s.text.contains('Resultados'));
final following = spine.sections.where((s) => s.page > target.page).firstOrNull;
final endPage = following?.page != null ? following!.page - 1 : spine.pageCount;

final result = await client.convertFromUrl(
  'https://bucket.example.com/informe-anual.pdf?sig=...',
  options: ConvertOptions(pages: '${target.page}-$endPage', mode: ConversionMode.fast),
);
```

Consulte el [PDF Índice de agentes de IA](/docs/public/es/concepts/pdf-index-for-ai-agents).

## Procesar un ZIP

```dart theme={null}
final bytes = await File('/path/documents.zip').readAsBytes();
final result = await client.convertBytes(
  bytes,
  'documents.zip',
  options: const ConvertOptions(
    inputFormat: InputFormat.zip,
    responseFormat: ResponseFormat.json,
  ),
);

if (result is JsonConvertResult) {
  print(result.result.markdown); // Markdown concatenated from the supported documents inside the ZIP
}
```

<Warning>
  Los límites de tamaño y cantidad de archivos dentro de ZIP están en [Límites](/docs/public/es/concepts/limits). Un ZIP fuera de rango lanza `PayloadTooLargeException`.
</Warning>
