zcatpdf/FUTURE_IMPROVEMENTS.md
reugenio 3826cbaed4 Release v1.0 - Feature Complete PDF Generation Library
Major features added since v0.5:
- PNG support with alpha/transparency (soft masks)
- FlateDecode compression via libdeflate-zig
- Bookmarks/Outline for document navigation
- Bezier curves, circles, ellipses, arcs
- Transformations (rotate, scale, translate, skew)
- Transparency/opacity (fill and stroke alpha)
- Linear and radial gradients (Shading Patterns)
- Code128 (1D) and QR Code (2D) barcodes
- TrueType font parsing (metrics, glyph widths)
- RC4 encryption module (40/128-bit)
- AcroForms module (TextField, CheckBox)
- SVG import (basic shapes and paths)
- Template system (reusable layouts)
- Markdown styling (bold, italic, links, headings, lists)

Documentation:
- README.md: Complete API reference with code examples
- FUTURE_IMPROVEMENTS.md: Detailed roadmap for future development
- CLAUDE.md: Updated to v1.0 release status

Stats:
- 125+ unit tests passing
- 16 demo examples
- 46 source files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-09 02:01:17 +01:00

11 KiB

zpdf - Mejoras Futuras

Este documento detalla las posibles mejoras y funcionalidades que podrían implementarse en versiones futuras de zpdf. Fecha: 2025-12-09 Versión actual: v1.0


1. TTF Font Embedding (Prioridad: ALTA)

Estado Actual

El módulo src/fonts/ttf.zig puede parsear archivos TrueType y extraer:

  • Métricas de fuente (ascender, descender, units_per_em)
  • Anchos de glyph
  • Mapeo character-to-glyph (cmap)
  • Nombre de familia

Lo que falta

Para renderizar texto con fuentes TTF embebidas en el PDF necesitamos:

  1. CIDFont Type 2 Output

    • Generar objeto /Type /Font /Subtype /Type0 (composite font)
    • Crear /DescendantFonts con CIDFont
    • Generar /CIDSystemInfo dictionary
    • Escribir /W array con anchos de caracteres
  2. Font Descriptor

    • /Type /FontDescriptor
    • /FontName, /FontFamily
    • /Flags (serif, symbolic, etc.)
    • /FontBBox, /ItalicAngle, /Ascent, /Descent
    • /CapHeight, /StemV
  3. Font Program Embedding

    • Subset del archivo TTF (solo glyphs usados)
    • Stream con /Filter /FlateDecode
    • /Length1 con tamaño original
  4. ToUnicode CMap

    • Mapeo de CIDs a caracteres Unicode
    • Necesario para copiar/pegar texto del PDF

Archivos a modificar

  • src/fonts/ttf.zig - Añadir funciones de subsetting
  • src/output/producer.zig - Generar objetos CIDFont
  • src/page.zig - Soporte para usar TTF fonts al dibujar texto

Referencias

  • PDF Reference 1.4, Sección 5.6 (Composite Fonts)
  • PDF Reference 1.4, Sección 5.8 (Font Descriptors)
  • TrueType Reference Manual de Apple

Estimación de complejidad

ALTA - Requiere entender bien la estructura CIDFont y el subsetting de TTF.


2. PDF Encryption Integration (Prioridad: MEDIA)

Estado Actual

El módulo src/security/ tiene implementado:

  • rc4.zig - Cifrado RC4 (40-bit y 128-bit)
  • encryption.zig - Procesamiento de passwords, key derivation, permission flags

Lo que falta

  1. Integración con OutputProducer

    // En output/producer.zig
    pub fn produceEncrypted(
        self: *Self,
        user_password: ?[]const u8,
        owner_password: ?[]const u8,
        permissions: Permissions,
    ) ![]u8
    
  2. Encrypt Dictionary en Trailer

    /Encrypt <<
      /Filter /Standard
      /V 2
      /R 3
      /Length 128
      /O <owner_hash>
      /U <user_hash>
      /P -3904  % permissions as signed integer
    >>
    
  3. Cifrado de Streams y Strings

    • Cada stream debe cifrarse con key derivada de obj_num + gen_num
    • Las strings en el documento también deben cifrarse
    • Excepciones: /ID en trailer, strings en /Encrypt dict
  4. Document ID

    • Generar /ID [<id1> <id2>] en trailer
    • Usar MD5 de timestamp + filename + file size

Archivos a modificar

  • src/output/producer.zig - Añadir modo encriptado
  • src/pdf.zig - API para activar encriptación
  • src/security/encryption.zig - Funciones helper adicionales

Código de ejemplo (objetivo)

var pdf = zpdf.Pdf.init(allocator, .{});
pdf.setEncryption(.{
    .user_password = "user123",
    .owner_password = "admin456",
    .permissions = .{
        .print = true,
        .modify = false,
        .copy = false,
    },
    .key_length = 128,
});
try pdf.save("encrypted.pdf");

Referencias

  • PDF Reference 1.4, Capítulo 3.5 (Encryption)
  • Algoritmos 3.1-3.6 del PDF Reference

Estimación de complejidad

MEDIA - El cifrado ya está implementado, solo falta integrarlo.


3. AcroForms Output (Prioridad: MEDIA)

Estado Actual

El módulo src/forms/field.zig define:

  • TextField - Campos de texto
  • CheckBox - Casillas de verificación
  • FieldFlags - Flags de campo (readonly, required, etc.)

Lo que falta

  1. AcroForm Dictionary en Catalog

    /AcroForm <<
      /Fields [4 0 R 5 0 R 6 0 R]
      /NeedAppearances true
      /DR << /Font << /Helv 7 0 R >> >>
      /DA (/Helv 12 Tf 0 g)
    >>
    
  2. Field Annotations

    4 0 obj <<
      /Type /Annot
      /Subtype /Widget
      /FT /Tx          % Text field
      /T (nombre)      % Field name
      /V (valor)       % Current value
      /Rect [100 700 300 720]
      /F 4             % Print flag
      /Ff 0            % Field flags
      /DA (/Helv 12 Tf 0 g)
      /AP << /N 5 0 R >>  % Appearance stream
    >>
    
  3. Appearance Streams

    • Cada campo necesita un appearance stream
    • Define cómo se renderiza visualmente el campo
  4. Tipos de campo adicionales

    • Radio buttons (/FT /Btn con /Ff flag radio)
    • Dropdown/Combo (/FT /Ch)
    • Signature fields (/FT /Sig)

Archivos a modificar

  • src/forms/field.zig - Añadir más tipos de campo
  • src/output/producer.zig - Generar AcroForm y annotations
  • src/pdf.zig - API para añadir campos

Código de ejemplo (objetivo)

var pdf = zpdf.Pdf.init(allocator, .{});
var page = try pdf.addPage(.{});

try page.addTextField(.{
    .name = "nombre",
    .x = 100,
    .y = 700,
    .width = 200,
    .height = 20,
    .default_value = "Escribe aquí...",
});

try page.addCheckBox(.{
    .name = "acepto",
    .x = 100,
    .y = 650,
    .checked = false,
});

Referencias

  • PDF Reference 1.4, Capítulo 8.6 (Interactive Forms)
  • PDF Reference 1.4, Sección 8.4.5 (Widget Annotations)

Estimación de complejidad

MEDIA-ALTA - Los appearance streams son complicados.


4. SVG Avanzado (Prioridad: BAJA)

Estado Actual

El módulo src/svg/parser.zig soporta:

  • Elementos: <rect>, <circle>, <ellipse>, <line>, <path>
  • Atributos: fill, stroke, stroke-width
  • Path commands: M, L, H, V, C, S, Q, T, A, Z

Lo que falta

  1. Elemento <text>

    <text x="100" y="50" font-family="Arial" font-size="24">Hello</text>
    
    • Parsing de atributos de texto
    • Mapeo font-family a fuentes PDF
  2. Transformaciones

    <g transform="translate(100,50) rotate(45) scale(2)">
    
    • Parsing de atributo transform
    • Aplicar matriz de transformación
  3. Gradientes SVG

    <linearGradient id="grad1">
      <stop offset="0%" stop-color="red"/>
      <stop offset="100%" stop-color="blue"/>
    </linearGradient>
    <rect fill="url(#grad1)"/>
    
    • Parsing de <linearGradient> y <radialGradient>
    • Mapeo a gradientes PDF existentes
  4. Grupos y referencias

    <defs>
      <symbol id="icon">...</symbol>
    </defs>
    <use href="#icon" x="100" y="200"/>
    
  5. Clipping paths

    <clipPath id="clip">
      <circle cx="100" cy="100" r="50"/>
    </clipPath>
    
  6. Estilos CSS inline

    <rect style="fill:red; stroke:blue; stroke-width:2"/>
    

Archivos a modificar

  • src/svg/parser.zig - Añadir parsing de elementos
  • src/svg/transform.zig (nuevo) - Parsing de transformaciones
  • src/svg/gradient.zig (nuevo) - Gradientes SVG

Estimación de complejidad

ALTA - SVG es un formato muy complejo. Implementar soporte completo requiere mucho trabajo.


5. Markdown Avanzado (Prioridad: BAJA)

Estado Actual

El módulo src/markdown/markdown.zig soporta:

  • Bold: **text** o __text__
  • Italic: *text* o _text_
  • Bold+Italic: ***text***
  • Strikethrough: ~~text~~
  • Links: [text](url)
  • Headings: #, ##, ###
  • Lists: - bullet y 1. numbered

Lo que falta

  1. Code blocks

    ```zig
    const x = 42;
    ```
    
    • Fondo gris
    • Fuente monospace (Courier)
    • Syntax highlighting (opcional, muy complejo)
  2. Inline code

    Use `const` for constants
    
    • Fondo gris
    • Fuente Courier
  3. Blockquotes

    > This is a quote
    > with multiple lines
    
    • Indentación
    • Línea vertical izquierda
    • Color de texto gris
  4. Tablas Markdown

    | Header 1 | Header 2 |
    |----------|----------|
    | Cell 1   | Cell 2   |
    
    • Parsing de sintaxis de tabla
    • Integración con Table helper existente
  5. Imágenes

    ![Alt text](image.jpg)
    
    • Cargar imagen
    • Insertar en posición
  6. Horizontal rules

    ---
    
  7. Nested lists

    - Item 1
      - Subitem 1.1
      - Subitem 1.2
    - Item 2
    
  8. Task lists

    - [x] Completed task
    - [ ] Pending task
    

Archivos a modificar

  • src/markdown/markdown.zig - Añadir parsing de elementos
  • src/markdown/renderer.zig (nuevo) - Renderer dedicado a PDF

Estimación de complejidad

MEDIA - El parsing es relativamente simple, la renderización requiere más trabajo.


6. Otras Mejoras Menores

6.1 Compresión de imágenes JPEG

  • Actualmente JPEG se incluye sin modificar (passthrough)
  • Podría añadirse recompresión para reducir tamaño
  • Requiere librería de decodificación JPEG

6.2 Soporte para más formatos de imagen

  • GIF - Convertir a PNG internamente
  • WebP - Formato moderno, buena compresión
  • TIFF - Común en documentos escaneados
  • BMP - Formato simple sin compresión

6.3 Metadata XMP

  • Actualmente usamos metadata básica (/Title, /Author, etc.)
  • XMP permite metadata más rica y extensible
  • Útil para PDF/A compliance

6.4 PDF/A Compliance

  • Estándar para archivado a largo plazo
  • Requiere:
    • Embeber todas las fuentes
    • No encriptación
    • Metadata XMP
    • Color profiles ICC

6.5 Layers (Optional Content Groups)

  • Capas que pueden mostrarse/ocultarse
  • Útil para planos, versiones de documento

6.6 Watermarks

  • Texto o imagen semitransparente de fondo
  • Función helper addWatermark()

6.7 Digital Signatures

  • Firmas digitales PKI
  • Certificados X.509
  • Timestamps

6.8 Annotations avanzadas

  • Notas (sticky notes)
  • Highlights
  • Stamps
  • Drawing annotations

Priorización Recomendada

Si se retoma el desarrollo, este es el orden sugerido:

  1. TTF Font Embedding - Muy útil para documentos con fuentes personalizadas
  2. PDF Encryption - Ya está casi listo, solo falta integración
  3. AcroForms Output - Formularios interactivos son muy demandados
  4. Markdown Code Blocks - Mejora útil con poco esfuerzo
  5. SVG Text - Completaría el soporte SVG básico
  6. Watermarks - Feature común y relativamente simple

Recursos y Referencias

Especificaciones

Librerías de referencia

Herramientas de debugging

  • qpdf --check file.pdf - Validar estructura PDF
  • mutool show file.pdf trailer - Inspeccionar objetos
  • pdftotext file.pdf - - Extraer texto (verifica fonts)

Documento generado: 2025-12-09 zpdf v1.0 - Feature Complete