# Convert to PDF

> 通用的字符串转 PDF 转换器。它接受纯文本、Markdown 或 HTML，生成 PDF 二进制并以 base64 编码放入信封（Link Loom 信封不在节点之间传输原始 Buffer）。

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

- 标识: `data.convert.to.pdf`
- 类别: 数据
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

通用的字符串转 PDF 转换器。它接受纯文本、Markdown 或 HTML，生成 PDF 二进制并以 base64 编码放入信封（Link Loom 信封不在节点之间传输原始 Buffer）。

**支持的输入类型**
- `text`：原样渲染，普通换行。
- `markdown`：使用 `marked` 解析；渲染标题、段落、粗体/斜体/代码、有序/无序列表、引用块、链接和水平分隔线。
- `html`：使用 `htmlparser2` 解析；渲染 `h1..h6`、`p`、`strong/b`、`em/i`、`code/pre`、`ul/ol/li`、`blockquote`、`a`、`hr`、`br`。不支持的标签按文本渲染。图片（`<img>`）会被丢弃；如有需要，请作为单独附件传递。

**页面装饰（均为可选）**
- `metadata`：在正文上方渲染为键值块的对象（例如邮件的 From/To/Subject/Date；文档的 Contract/Client/Date）。
- `document_header`：绘制在每页顶部的文本（例如机构页眉）。
- `document_footer`：绘制在每页底部的文本（例如法律页脚）。
- `watermark`：可配置不透明度的旋转背景文字。
- `page_numbers`：在每页右下角添加“Página N de M”。

**设计约束**
- 纯粹的输入 → 输出。不下载 blob，无外部 I/O，不访问 Cosmos/Mongo。可完全隔离测试。
- 可复用于任何 `string → PDF` 场景（邮件正文、合同、手册、日志）。不与任何特定业务领域耦合。
- 使用 pdfkit（纯 JS，无需 chromium）。快速轻量，适合信封传输。

## 配置

- `content` (string, 必填): 要转换为 PDF 的源内容（纯文本、Markdown 或 HTML）。
- `input_type` (string, 可选): 如何解析内容字符串。 默认值: `text`. 可选值: `text`, `markdown`, `html`.
- `filename` (string, 可选): 生成的 PDF 的逻辑文件名（用于元数据，并在输出中回显）。 默认值: `document.pdf`.
- `page_size` (string, 可选): 默认值: `A4`. 可选值: `A4`, `Letter`.
- `page_margin` (number, 可选): 统一页边距，单位为点（72pt = 1in）。 默认值: `40`.
- `metadata` (object, 可选): 在正文上方渲染为小表格的键值对。
- `document_header` (object, 可选): 绘制在每页顶部的文本。
  - `text` (string, 可选)
  - `style` (object, 可选)
    - `font_size` (number, 可选): 字号，单位为点。
    - `bold` (boolean, 可选): 文本是否加粗。
    - `color` (string, 可选): 文本颜色，十六进制格式（例如“#666666”）。
    - `align` (string, 可选): 水平对齐方式。 可选值: `left`, `center`, `right`.
- `document_footer` (object, 可选): 绘制在每页底部的文本（例如法律免责声明）。
  - `text` (string, 可选)
  - `style` (object, 可选)
    - `font_size` (number, 可选): 字号，单位为点。
    - `bold` (boolean, 可选): 文本是否加粗。
    - `color` (string, 可选): 文本颜色，十六进制格式（例如“#666666”）。
    - `align` (string, 可选): 水平对齐方式。 可选值: `left`, `center`, `right`.
- `watermark` (object, 可选): 绘制在每页上的旋转背景文字。
  - `text` (string, 可选)
  - `opacity` (number, 可选): 不透明度 0..1（默认 0.06）。
  - `rotation` (number, 可选): 旋转角度（默认 45）。
  - `color` (string, 可选): 十六进制颜色（默认“#000000”）。
  - `font_size` (number, 可选): 水印字号（默认 60pt）。
- `page_numbers` (boolean, 可选): 为 true 时，在每页右下角打印“Página N de M”。 默认值: `false`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `out` (默认): PDF 生成成功。
- `error`: 转换失败。

## 输入契约

- `content` (string, 必填)
- `input_type` (string, 可选)

## 输出契约

- `pdf_base64` (string, 可选): 以 base64 编码的 PDF 二进制（符合 Link Loom 信封约束）。
- `filename` (string, 可选)
- `size_bytes` (number, 可选): 原始 PDF 大小，单位为字节（base64 编码前）。
- `input_type` (string, 可选): 回显所使用的 input_type。
- `format` (string, 可选): 始终为 'pdf'。

## 在表达式中

后续节点可通过 `$("Convert to PDF").item.json.<路径>` 读取此节点输出中的内容（请把 `Convert to PDF` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Convert to PDF").item.json.pdf_base64` (string) = `"JVBERi0xLjMKJf////8KNyAwIG9iago8PAovVHlwZSAv…"`: 以 base64 编码的 PDF 二进制（符合 Link Loom 信封约束）。
- `$("Convert to PDF").item.json.filename` (string) = `"case-summary.pdf"`
- `$("Convert to PDF").item.json.size_bytes` (number) = `18432`: 原始 PDF 大小，单位为字节（base64 编码前）。
- `$("Convert to PDF").item.json.input_type` (string) = `"markdown"`: 回显所使用的 input_type。
- `$("Convert to PDF").item.json.format` (string) = `"pdf"`: 始终为 'pdf'。


## 工作原理

使用 PDFKit 将纯文本、Markdown 或 HTML 渲染为 PDF，并以 base64 返回；可选标题、数据块、页眉、页脚、水印和页码。

1. 解析配置。`content` 取自配置，或取自输入 payload 中的 `content`；为空时节点失败。
2. 读取版式：`input_type`（默认 `text`，不区分大小写）、`filename`（默认 `document.pdf`）、`page_size`（默认 `A4`）和 `page_margin`（默认 50 磅）。有页眉时上边距增加 30 磅；有页脚或页码时下边距增加 30 磅。
3. 在正文前按顺序绘制可选块：`title`（含 `subtitle`）、`traceability` 和 `metadata`。只要存在其中任意一个，正文前会加一个固定的粗体标签。
4. 绘制正文：`text` 原样输出；`markdown` 经 marked 词法分析（标题、段落、粗体、斜体、行内代码、链接、列表、代码块、引用、分隔线）；`html` 经 htmlparser2（`h1`–`h6`、`p`、`pre`、`blockquote`、`li`、`hr`、`br`、`b`/`strong`、`i`/`em`、`code`、`a`）。
5. 在每一页绘制水印、`document_header`、`document_footer`，开启 `page_numbers` 时还会在右下角绘制页码。
6. 通过 `out` 返回 `{ pdf_base64, filename, size_bytes, input_type, format: "pdf" }`。

## 在工作流中

### 节点

```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"
}
```

## 输出端口 (代码中的行为)

### `out`

PDF 已生成。`size_bytes` 是 base64 编码前的原始大小。

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

### `error`

`content` 为空或 PDFKit 出错。

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

## 代码中的行为

- `page_margin`: 代码默认值为 50 磅，而非 schema 中的 40。非数值会回退为 50。
- `title`: 未声明。居中粗体标题（14 磅），可附 `subtitle`（同样未声明），下方加一条横线。
- `traceability`: 未声明。键值对对象，以小号等宽字体块绘制；空值或 null 会被跳过。`metadata` 用法相同，但使用常规字体。
- `watermark`: 代码默认值：`opacity` 0.06、`rotation` -30 度、`font_size` 40、`color` `#000000`（schema 描述写的是 45 度和 60 磅）。
- `document_header`: `text` 加 `style`（`align`、`color`、`font_size` 默认 8、`bold`）。过长文本以省略号截断：页眉一行，`document_footer` 两行。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `content is required` | `error` | 配置和 payload 中都没有 `content`。请映射它，例如 `{{ $json.summary_markdown }}`。 |
| `Cannot read properties of undefined (reading '0')` | `error` | `page_size` 不是 PDFKit 支持的尺寸。请使用 `A4` 或 `Letter`。 |

## 说明与限制

- 使用 PDF 标准字体 Helvetica 和 Courier：超出其拉丁字符集的字符（例如中文、日文或 emoji）无法正确显示。
- 固定标签为西班牙语："Trazabilidad"、"Encabezados del correo"、"Contenido del correo" 和 "Página N de M"。
- 图片会被忽略，Markdown 表格不会绘制，HTML 表格会被展平为普通段落。
- 整个 PDF 保存在内存中，并以 base64 形式放在 payload 里（约为原大小的 4/3）。输入 payload 会被结果替换。
- worker 不设置 `ok`（示例中显示为 `true`）；引擎只按 `port` 路由。


## 契约（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
  }
]
```
