# Convert to PDF

> Conversor genérico de cadena a PDF.

Source: https://docs.sommatic.ai/es/nodes/data.convert.to.pdf/

- Slug: `data.convert.to.pdf`
- Familia: Datos
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: sync

Conversor genérico de cadena a PDF. Acepta texto plano, Markdown o HTML y produce un binario PDF codificado en base64 dentro del envelope (los envelopes de Link Loom no transportan Buffers en bruto entre nodos).

**Tipos de entrada admitidos**
- `text`: se renderiza tal cual, con ajuste de línea simple.
- `markdown`: se interpreta con `marked`; renderiza encabezados, párrafos, negrita/cursiva/código, listas ordenadas y no ordenadas, citas, enlaces y líneas horizontales.
- `html`: se interpreta con `htmlparser2`; renderiza `h1..h6`, `p`, `strong/b`, `em/i`, `code/pre`, `ul/ol/li`, `blockquote`, `a`, `hr`, `br`. Las etiquetas no admitidas se renderizan como texto. Las imágenes (`<img>`) se descartan; si las necesitas, envíalas como adjuntos aparte.

**Decoración de página (todo opcional)**
- `metadata`: objeto que se renderiza como un bloque de clave/valor sobre el cuerpo (p. ej., De/Para/Asunto/Fecha en un correo; Contrato/Cliente/Fecha en un documento).
- `document_header`: texto que se pinta en la parte superior de cada página (p. ej., un encabezado institucional).
- `document_footer`: texto que se pinta en la parte inferior de cada página (p. ej., un pie legal).
- `watermark`: texto de fondo rotado con opacidad configurable.
- `page_numbers`: agrega "Página N de M" en la esquina inferior derecha de cada página.

**Restricciones de diseño**
- Entrada → salida pura. Sin descarga de blobs, sin E/S externa, sin acceso a Cosmos/Mongo. Totalmente comprobable de forma aislada.
- Reutilizable en cualquier escenario de `string → PDF` (cuerpo de correo, contratos, manuales, logs). No está acoplado a ningún dominio concreto.
- Usa pdfkit (JS puro, sin Chromium). Rápido y ligero; adecuado para envelopes.

## Configuración

- `content` (string, obligatorio): El contenido de origen (texto plano, Markdown o HTML) que se convierte en PDF.
- `input_type` (string, opcional): Cómo se interpreta la cadena de contenido. Por defecto: `text`. Valores permitidos: `text`, `markdown`, `html`.
- `filename` (string, opcional): Nombre lógico del PDF generado (se usa en los metadatos y se devuelve en la salida). Por defecto: `document.pdf`.
- `page_size` (string, opcional): Por defecto: `A4`. Valores permitidos: `A4`, `Letter`.
- `page_margin` (number, opcional): Margen uniforme en puntos (72 pt = 1 in). Por defecto: `40`.
- `metadata` (object, opcional): Pares clave/valor que se renderizan como una pequeña tabla sobre el cuerpo.
- `document_header` (object, opcional): Texto que se pinta en la parte superior de cada página.
  - `text` (string, opcional)
  - `style` (object, opcional)
    - `font_size` (number, opcional): Tamaño de fuente en puntos.
    - `bold` (boolean, opcional): Si el texto va en negrita.
    - `color` (string, opcional): Color del texto en hexadecimal (p. ej. "#666666").
    - `align` (string, opcional): Alineación horizontal. Valores permitidos: `left`, `center`, `right`.
- `document_footer` (object, opcional): Texto que se pinta en la parte inferior de cada página (p. ej., un aviso legal).
  - `text` (string, opcional)
  - `style` (object, opcional)
    - `font_size` (number, opcional): Tamaño de fuente en puntos.
    - `bold` (boolean, opcional): Si el texto va en negrita.
    - `color` (string, opcional): Color del texto en hexadecimal (p. ej. "#666666").
    - `align` (string, opcional): Alineación horizontal. Valores permitidos: `left`, `center`, `right`.
- `watermark` (object, opcional): Texto de fondo rotado que se pinta en cada página.
  - `text` (string, opcional)
  - `opacity` (number, opcional): Opacidad de 0 a 1 (predeterminada: 0.06).
  - `rotation` (number, opcional): Rotación en grados (predeterminada: 45).
  - `color` (string, opcional): Color en hexadecimal (predeterminado: "#000000").
  - `font_size` (number, opcional): Tamaño de fuente de la marca de agua (predeterminado: 60 pt).
- `page_numbers` (boolean, opcional): Si es true, imprime "Página N de M" en la esquina inferior derecha de cada página. Por defecto: `false`.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `out` (por defecto): PDF generado correctamente.
- `error`: La conversión falló.

## Contrato de entrada

- `content` (string, obligatorio)
- `input_type` (string, opcional)

## Contrato de salida

- `pdf_base64` (string, opcional): Binario PDF codificado en base64 (cumple las restricciones del envelope de Link Loom).
- `filename` (string, opcional)
- `size_bytes` (number, opcional): Tamaño del PDF en bruto, en bytes (antes de base64).
- `input_type` (string, opcional): Eco del input_type usado.
- `format` (string, opcional): Siempre 'pdf'.

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Convert to PDF").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Convert to PDF`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `out`, según la salida que muestra Puertos.

- `$("Convert to PDF").item.json.pdf_base64` (string) = `"JVBERi0xLjMKJf////8KNyAwIG9iago8PAovVHlwZSAv…"`: Binario PDF codificado en base64 (cumple las restricciones del envelope de Link Loom).
- `$("Convert to PDF").item.json.filename` (string) = `"case-summary.pdf"`
- `$("Convert to PDF").item.json.size_bytes` (number) = `18432`: Tamaño del PDF en bruto, en bytes (antes de base64).
- `$("Convert to PDF").item.json.input_type` (string) = `"markdown"`: Eco del input_type usado.
- `$("Convert to PDF").item.json.format` (string) = `"pdf"`: Siempre 'pdf'.


## Cómo funciona

Convierte texto plano, Markdown o HTML en un PDF con PDFKit y lo devuelve en base64, con título, bloques de datos, encabezado, pie de página, marca de agua y numeración opcionales.

1. Resuelve la configuración. `content` sale de la configuración o del `content` del payload de entrada; un valor vacío hace fallar el nodo.
2. Lee el diseño: `input_type` (por defecto `text`, sin distinguir mayúsculas), `filename` (por defecto `document.pdf`), `page_size` (por defecto `A4`) y `page_margin` (por defecto 50 puntos). Un encabezado suma 30 puntos al margen superior; un pie o la numeración suman 30 puntos al inferior.
3. Dibuja los bloques opcionales antes del cuerpo, en este orden: `title` (con `subtitle`), `traceability` y `metadata`. Si hay alguno, una etiqueta fija en negrita precede al cuerpo.
4. Dibuja el cuerpo: `text` tal cual; `markdown` con el lexer de marked (títulos, párrafos, negrita, cursiva, código en línea, enlaces, listas, bloques de código, citas, separadores); `html` con htmlparser2 (`h1`–`h6`, `p`, `pre`, `blockquote`, `li`, `hr`, `br`, `b`/`strong`, `i`/`em`, `code`, `a`).
5. Pinta en cada página la marca de agua, `document_header`, `document_footer` y, con `page_numbers`, un contador de páginas abajo a la derecha.
6. Devuelve `{ pdf_base64, filename, size_bytes, input_type, format: "pdf" }` por `out`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-render-summary",
  "label": "Render summary PDF",
  "operator_slug": "data.convert.to.pdf",
  "operator_version": "1.0.0",
  "config": {
    "content": "{{ $json.summary_markdown }}",
    "input_type": "markdown",
    "filename": "case-summary.pdf",
    "page_size": "A4",
    "page_numbers": true,
    "document_footer": {
      "text": "Confidential. Generated by an automated workflow."
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "pdf_base64": "JVBERi0xLjMKJf////8KNyAwIG9iago8PAovVHlwZSAvUGFnZQo...",
    "filename": "case-summary.pdf",
    "size_bytes": 18432,
    "input_type": "markdown",
    "format": "pdf"
  },
  "port": "out"
}
```

## Puertos de salida (comportamiento en el código)

### `out`

El PDF se generó. `size_bytes` es el tamaño del PDF antes de base64.

```json
{
  "pdf_base64": "JVBERi0xLjMKJf////8KNyAwIG9iago8PAovVHlwZSAvUGFnZQo...",
  "filename": "case-summary.pdf",
  "size_bytes": 18432,
  "input_type": "markdown",
  "format": "pdf"
}
```

### `error`

`content` está vacío o PDFKit falló.

```json
{
  "error": "content is required"
}
```

## Comportamiento en el código

- `page_margin`: El valor por defecto del código es 50 puntos, no los 40 del esquema. Los valores no numéricos vuelven a 50.
- `title`: No declarada. Título centrado en negrita (14 pt) con un `subtitle` opcional (tampoco declarado) y una línea debajo.
- `traceability`: No declarada. Objeto de pares clave/valor que se dibuja como un bloque pequeño en monoespaciado; se omiten los valores nulos o vacíos. `metadata` funciona igual con fuente normal.
- `watermark`: Valores por defecto del código: `opacity` 0.06, `rotation` -30 grados, `font_size` 40, `color` `#000000` (el texto del esquema dice 45 grados y 60 pt).
- `document_header`: `text` más `style` (`align`, `color`, `font_size` por defecto 8, `bold`). El texto largo se corta con puntos suspensivos: una línea en el encabezado, dos en `document_footer`.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `content is required` | `error` | No hay `content` en la configuración ni en el payload. Asígnalo, por ejemplo `{{ $json.summary_markdown }}`. |
| `Cannot read properties of undefined (reading '0')` | `error` | `page_size` no es un tamaño que PDFKit conozca. Usa `A4` o `Letter`. |

## Notas y límites

- Usa las fuentes estándar de PDF Helvetica y Courier: los caracteres fuera de su juego latino (por ejemplo chino, japonés o emoji) no se muestran bien.
- Las etiquetas fijas están en español: "Trazabilidad", "Encabezados del correo", "Contenido del correo" y "Página N de M".
- Las imágenes se ignoran, las tablas de Markdown no se dibujan y las tablas HTML se aplanan en párrafos.
- El PDF completo se guarda en memoria y viaja en base64 dentro del payload (unas 4/3 de su tamaño). El payload de entrada se reemplaza por el resultado.
- El worker no define `ok` (el ejemplo muestra `true`); el motor enruta solo por `port`.


## Contratos (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "data.convert.to.pdf",
  "name": "Convert to PDF",
  "category": "data",
  "version": "1.0.0",
  "description": "Generic string-to-PDF converter. Accepts plain text, Markdown, or HTML and produces a PDF binary encoded as base64 in the envelope (Link Loom envelopes do not transport raw Buffers between nodes).\n\n**Supported input types**\n- `text` — rendered as-is, plain wrap.\n- `markdown` — parsed with `marked`; renders headings, paragraphs, bold/italic/code, ordered/unordered lists, blockquotes, links, horizontal rules.\n- `html` — parsed with `htmlparser2`; renders `h1..h6`, `p`, `strong/b`, `em/i`, `code/pre`, `ul/ol/li`, `blockquote`, `a`, `hr`, `br`. Non-supported tags render as text. Images (`<img>`) are dropped — carry them as separate attachments if needed.\n\n**Page decoration (all optional)**\n- `metadata` — object rendered as a key/value block above the body (e.g. From/To/Subject/Date for an email; Contract/Client/Date for a document).\n- `document_header` — text painted at the top of every page (e.g. institutional header).\n- `document_footer` — text painted at the bottom of every page (e.g. legal footer).\n- `watermark` — rotated background text with configurable opacity.\n- `page_numbers` — appends \"Página N de M\" to the bottom-right of every page.\n\n**Design constraints**\n- Pure input → output. No blob download, no external I/O, no Cosmos/Mongo touch. Fully testable in isolation.\n- Reusable for any `string → PDF` scenario (email body, contracts, manuals, logs). Not coupled to any specific domain.\n- Uses pdfkit (JS pure, no chromium). Fast and lightweight; suitable for envelopes.",
  "capabilities": [
    "pdf",
    "convert",
    "html-to-pdf",
    "markdown-to-pdf",
    "text-to-pdf"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "content"
    ],
    "properties": {
      "content": {
        "type": "string",
        "title": "Content",
        "format": "textarea",
        "description": "The source content (plain text, Markdown, or HTML) to convert into a PDF."
      },
      "input_type": {
        "type": "string",
        "enum": [
          "text",
          "markdown",
          "html"
        ],
        "default": "text",
        "title": "Input Type",
        "description": "How to interpret the content string."
      },
      "filename": {
        "type": "string",
        "default": "document.pdf",
        "title": "Filename",
        "description": "Logical filename for the produced PDF (used in metadata and echoed in output)."
      },
      "page_size": {
        "type": "string",
        "enum": [
          "A4",
          "Letter"
        ],
        "default": "A4",
        "title": "Page Size"
      },
      "page_margin": {
        "type": "number",
        "default": 40,
        "title": "Page Margin (points)",
        "description": "Uniform margin in points (72pt = 1in)."
      },
      "metadata": {
        "type": "object",
        "title": "Metadata Block",
        "description": "Key/value pairs rendered as a small table above the body.",
        "additionalProperties": {
          "type": "string"
        }
      },
      "document_header": {
        "type": "object",
        "title": "Page Header",
        "description": "Text painted at the top of every page.",
        "properties": {
          "text": {
            "type": "string"
          },
          "style": {
            "type": "object",
            "properties": {
              "font_size": {
                "type": "number",
                "description": "Font size in points."
              },
              "bold": {
                "type": "boolean",
                "description": "Whether the text is bold."
              },
              "color": {
                "type": "string",
                "description": "Text color as hex (e.g. \"#666666\")."
              },
              "align": {
                "type": "string",
                "enum": [
                  "left",
                  "center",
                  "right"
                ],
                "description": "Horizontal alignment."
              }
            }
          }
        }
      },
      "document_footer": {
        "type": "object",
        "title": "Page Footer",
        "description": "Text painted at the bottom of every page (e.g. legal disclaimer).",
        "properties": {
          "text": {
            "type": "string"
          },
          "style": {
            "type": "object",
            "properties": {
              "font_size": {
                "type": "number",
                "description": "Font size in points."
              },
              "bold": {
                "type": "boolean",
                "description": "Whether the text is bold."
              },
              "color": {
                "type": "string",
                "description": "Text color as hex (e.g. \"#666666\")."
              },
              "align": {
                "type": "string",
                "enum": [
                  "left",
                  "center",
                  "right"
                ],
                "description": "Horizontal alignment."
              }
            }
          }
        }
      },
      "watermark": {
        "type": "object",
        "title": "Watermark",
        "description": "Rotated background text painted on every page.",
        "properties": {
          "text": {
            "type": "string"
          },
          "opacity": {
            "type": "number",
            "description": "Opacity 0..1 (default 0.06)."
          },
          "rotation": {
            "type": "number",
            "description": "Rotation in degrees (default 45)."
          },
          "color": {
            "type": "string",
            "description": "Hex color (default \"#000000\")."
          },
          "font_size": {
            "type": "number",
            "description": "Watermark font size (default 60pt)."
          }
        }
      },
      "page_numbers": {
        "type": "boolean",
        "default": false,
        "title": "Show Page Numbers",
        "description": "If true, prints \"Página N de M\" on the bottom-right of every page."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "required": [
      "content"
    ],
    "properties": {
      "content": {
        "type": "string"
      },
      "input_type": {
        "type": "string"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "pdf_base64": {
        "type": "string",
        "description": "PDF binary base64-encoded (fits Link Loom envelope constraints)."
      },
      "filename": {
        "type": "string"
      },
      "size_bytes": {
        "type": "number",
        "description": "Raw PDF size in bytes (pre-base64)."
      },
      "input_type": {
        "type": "string",
        "description": "Echo of the input_type used."
      },
      "format": {
        "type": "string",
        "description": "Always 'pdf'."
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "PDF",
      "description": "PDF generated successfully.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Conversion failed.",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "sync",
  "required_resources": [],
  "tags": [
    "pdf",
    "convert",
    "html",
    "markdown",
    "text",
    "render"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "content"
  ],
  "properties": {
    "content": {
      "type": "string",
      "title": "Content",
      "format": "textarea",
      "description": "The source content (plain text, Markdown, or HTML) to convert into a PDF."
    },
    "input_type": {
      "type": "string",
      "enum": [
        "text",
        "markdown",
        "html"
      ],
      "default": "text",
      "title": "Input Type",
      "description": "How to interpret the content string."
    },
    "filename": {
      "type": "string",
      "default": "document.pdf",
      "title": "Filename",
      "description": "Logical filename for the produced PDF (used in metadata and echoed in output)."
    },
    "page_size": {
      "type": "string",
      "enum": [
        "A4",
        "Letter"
      ],
      "default": "A4",
      "title": "Page Size"
    },
    "page_margin": {
      "type": "number",
      "default": 40,
      "title": "Page Margin (points)",
      "description": "Uniform margin in points (72pt = 1in)."
    },
    "metadata": {
      "type": "object",
      "title": "Metadata Block",
      "description": "Key/value pairs rendered as a small table above the body.",
      "additionalProperties": {
        "type": "string"
      }
    },
    "document_header": {
      "type": "object",
      "title": "Page Header",
      "description": "Text painted at the top of every page.",
      "properties": {
        "text": {
          "type": "string"
        },
        "style": {
          "type": "object",
          "properties": {
            "font_size": {
              "type": "number",
              "description": "Font size in points."
            },
            "bold": {
              "type": "boolean",
              "description": "Whether the text is bold."
            },
            "color": {
              "type": "string",
              "description": "Text color as hex (e.g. \"#666666\")."
            },
            "align": {
              "type": "string",
              "enum": [
                "left",
                "center",
                "right"
              ],
              "description": "Horizontal alignment."
            }
          }
        }
      }
    },
    "document_footer": {
      "type": "object",
      "title": "Page Footer",
      "description": "Text painted at the bottom of every page (e.g. legal disclaimer).",
      "properties": {
        "text": {
          "type": "string"
        },
        "style": {
          "type": "object",
          "properties": {
            "font_size": {
              "type": "number",
              "description": "Font size in points."
            },
            "bold": {
              "type": "boolean",
              "description": "Whether the text is bold."
            },
            "color": {
              "type": "string",
              "description": "Text color as hex (e.g. \"#666666\")."
            },
            "align": {
              "type": "string",
              "enum": [
                "left",
                "center",
                "right"
              ],
              "description": "Horizontal alignment."
            }
          }
        }
      }
    },
    "watermark": {
      "type": "object",
      "title": "Watermark",
      "description": "Rotated background text painted on every page.",
      "properties": {
        "text": {
          "type": "string"
        },
        "opacity": {
          "type": "number",
          "description": "Opacity 0..1 (default 0.06)."
        },
        "rotation": {
          "type": "number",
          "description": "Rotation in degrees (default 45)."
        },
        "color": {
          "type": "string",
          "description": "Hex color (default \"#000000\")."
        },
        "font_size": {
          "type": "number",
          "description": "Watermark font size (default 60pt)."
        }
      }
    },
    "page_numbers": {
      "type": "boolean",
      "default": false,
      "title": "Show Page Numbers",
      "description": "If true, prints \"Página N de M\" on the bottom-right of every page."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "required": [
    "content"
  ],
  "properties": {
    "content": {
      "type": "string"
    },
    "input_type": {
      "type": "string"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "pdf_base64": {
      "type": "string",
      "description": "PDF binary base64-encoded (fits Link Loom envelope constraints)."
    },
    "filename": {
      "type": "string"
    },
    "size_bytes": {
      "type": "number",
      "description": "Raw PDF size in bytes (pre-base64)."
    },
    "input_type": {
      "type": "string",
      "description": "Echo of the input_type used."
    },
    "format": {
      "type": "string",
      "description": "Always 'pdf'."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "PDF",
    "description": "PDF generated successfully.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Conversion failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
