当前位置: 首页 > Skill >

Pdf Report Generator

Pdf Report Generator

1.0.0 2026.11.27 浏览:431
获取Skill文件查看使用说明
作者:江辰许可证:
本文目录展开

PDF Report Generator — Markdown转PDF

Convert structured Markdown reports into print-ready A4 PDF documents with Chinese font support, automatic headers/footers, and page numbers. Designed to work hand-in-hand with the daily-market-report skill.

When to Use

Scenario Trigger
End-of-day market report → PDF After daily-market-report generates a Markdown summary
Trade journal / weekly review export Convert structured notes to PDF
Investment memo generation Produce clean A4 printouts for offline review
Any Markdown → formatted PDF General-purpose conversion

Prerequisites

The pdfkit library is already installed at:

C:UsersTania.openclawworkspace.tmp-reportnode_modulespdfkit

No additional installs needed. The skill uses this existing dependency.

Chinese Font

For Chinese text rendering, pdfkit requires a TrueType font file. Recommended:

  • Noto Sans SC (free, open-source): Download from Google Fonts
  • Source Han Sans (思源黑体): Another good open-source option
  • Microsoft YaHei (微软雅黑): Available on Windows at C:WindowsFontsmsyh.ttc

Place the font file in the skill's assets/ directory or reference it from a known path. Example:

# Option 1: Place in assets/
cp /path/to/NotoSansSC-Regular.ttf skills/pdf-report-generator/assets/

# Option 2: Use Windows system font (no copy needed)
# Just reference C:WindowsFontsmsyh.ttc in the script

Workflow: Markdown → PDF

Step 1: Parse Markdown content

The input is a Markdown string. Key structural elements to handle:

Markdown Element PDF Rendering
# H1 Large bold header
## H2 Medium bold header
### H3 Small bold header
Plain text Body paragraph
` table
**bold** Bold text
- list Bullet point
> quote Indented italic
--- Horizontal rule
`code` Monospace
🟢 / 🔴 Color markers

Step 2: Generate PDF via Node.js script

Create and run a Node.js script that uses pdfkit. Script location: skills/pdf-report-generator/scripts/generate_pdf.js

Core Script Template

const PDFDocument = require('pdfkit');
const fs = require('fs');

// === CONFIG ===
const FONT_PATH = 'C:/Windows/Fonts/msyh.ttc';     // Chinese font
const FONT_BOLD_PATH = 'C:/Windows/Fonts/msyhbd.ttc'; // Bold variant (optional)
const PAGE_WIDTH = 595.28;   // A4 width (points)
const PAGE_HEIGHT = 841.89;  // A4 height (points)
const MARGIN = 72;           // 1 inch margins
const HEADER_Y = 40;
const FOOTER_Y = PAGE_HEIGHT - 30;
const CONTENT_TOP = 72;
const CONTENT_BOTTOM = PAGE_HEIGHT - 72;

// === HELPERS ===
function addHeader(doc, text) {
  doc.fontSize(8).font(FONT_PATH)
     .text(text, MARGIN, HEADER_Y, { align: 'left' });
  doc.moveTo(MARGIN, HEADER_Y + 14)
     .lineTo(PAGE_WIDTH - MARGIN, HEADER_Y + 14)
     .stroke('#cccccc');
}

function addFooter(doc, pageNum) {
  doc.fontSize(8).font(FONT_PATH)
     .text(`第 ${pageNum} 页`, MARGIN, FOOTER_Y, { align: 'center' });
}

function renderTable(doc, headers, rows, startY) {
  // Column widths: equal distribution
  const colCount = headers.length;
  const colWidth = (PAGE_WIDTH - 2 * MARGIN) / colCount;
  let y = startY;

  // Header row
  doc.fontSize(9).font(FONT_BOLD_PATH || FONT_PATH);
  headers.forEach((h, i) => {
    doc.text(h, MARGIN + i * colWidth + 2, y + 2, {
      width: colWidth - 4, align: 'center'
    });
  });
  y += 20;

  // Draw header line
  doc.moveTo(MARGIN, y).lineTo(PAGE_WIDTH - MARGIN, y).stroke();

  // Data rows
  doc.fontSize(9).font(FONT_PATH);
  for (const row of rows) {
    row.forEach((cell, i) => {
      doc.text(String(cell), MARGIN + i * colWidth + 2, y + 2, {
        width: colWidth - 4, align: 'center'
      });
    });
    y += 18;

    doc.moveTo(MARGIN, y).lineTo(PAGE_WIDTH - MARGIN, y)
       .stroke('#eeeeee');
  }

  return y; // Return next Y position
}

// === MAIN ===
function generatePDF(markdownContent, outputPath, title) {
  const doc = new PDFDocument({
    size: 'A4',
    margins: { top: MARGIN, bottom: MARGIN, left: MARGIN, right: MARGIN },
    info: {
      Title: title || 'Market Report',
      Author: 'OpenClaw 虾哥',
      Producer: 'OpenClaw pdf-report-generator',
    }
  });

  const stream = fs.createWriteStream(outputPath);
  doc.pipe(stream);

  let pageNum = 1;
  addHeader(doc, title || '市场报告');
  addFooter(doc, pageNum);

  // --- Parse and render markdown ---
  const lines = markdownContent.split('n');
  let y = CONTENT_TOP;

  for (const line of lines) {
    // Check if we need a new page
    if (y > CONTENT_BOTTOM - 30) {
      doc.addPage();
      pageNum++;
      addHeader(doc, title || '市场报告');
      addFooter(doc, pageNum);
      y = CONTENT_TOP;
    }

    // H1
    if (line.startsWith('# ')) {
      doc.fontSize(18).font(FONT_BOLD_PATH || FONT_PATH)
         .fillColor('#1a1a2e');
      y = doc.text(line.slice(2), MARGIN, y + 16, {
        continued: false
      }).y + 6;
    }
    // H2
    else if (line.startsWith('## ')) {
      doc.fontSize(14).font(FONT_BOLD_PATH || FONT_PATH)
         .fillColor('#16213e');
      y = doc.text(line.slice(3), MARGIN, y + 12, {
        continued: false
      }).y + 4;
    }
    // H3
    else if (line.startsWith('### ')) {
      doc.fontSize(12).font(FONT_BOLD_PATH || FONT_PATH)
         .fillColor('#0f3460');
      y = doc.text(line.slice(4), MARGIN, y + 10, {
        continued: false
      }).y + 2;
    }
    // Horizontal rule
    else if (line.startsWith('---')) {
      doc.moveTo(MARGIN, y + 4)
         .lineTo(PAGE_WIDTH - MARGIN, y + 4)
         .stroke('#cccccc');
      y += 12;
    }
    // Empty line
    else if (line.trim() === '') {
      y += 8;
    }
    // Regular text / bullet / table row
    else {
      doc.fontSize(10).font(FONT_PATH).fillColor('#333333');
      y = doc.text(line, MARGIN, y + 2, {
        width: PAGE_WIDTH - 2 * MARGIN,
        lineGap: 2
      }).y + 2;
    }

    doc.fillColor('#000000');
  }

  doc.end();

  return new Promise((resolve, reject) => {
    stream.on('finish', () => resolve(outputPath));
    stream.on('error', reject);
  });
}

// Export for use as module
module.exports = { generatePDF };

// CLI usage
if (require.main === module) {
  const args = process.argv.slice(2);
  const mdFile = args[0];
  const outFile = args[1] || 'report.pdf';
  const title = args[2] || '市场报告';

  const md = fs.readFileSync(mdFile, 'utf-8');
  generatePDF(md, outFile, title).then(() => {
    console.log(`PDF generated: ${outFile}`);
  });
}

CLI Usage

# From workspace root:
node skills/pdf-report-generator/scripts/generate_pdf.js input.md output.pdf "市场日报"

Step 3: Verify output

  • Open generated PDF and check:
    • Chinese characters render correctly
    • Headers/footers appear on every page
    • Page numbers increment properly
    • Tables align correctly
    • Color markers (🟢🔴) display
    • No content overflow at page boundaries

Integration with daily-market-report

After daily-market-report produces a Markdown string, call this skill:

  1. Save the Markdown to a temp file (e.g., .tmp-report/latest.md)
  2. Run the Node.js script with the file
  3. Delete the temp Markdown file
  4. Return the PDF file path to the user

Quick Function (Python → Node bridge)

import subprocess
import tempfile
import os

def markdown_to_pdf(markdown_content, output_path, title="市场报告"):
    """Convert Markdown string to PDF file."""
    # Write temp markdown
    with tempfile.NamedTemporaryFile(
        mode='w', suffix='.md', delete=False, encoding='utf-8'
    ) as f:
        f.write(markdown_content)
        md_path = f.name

    try:
        # Call Node.js generator
        subprocess.run([
            'node',
            'skills/pdf-report-generator/scripts/generate_pdf.js',
            md_path, output_path, title
        ], check=True, cwd=os.getenv('OPENCLAW_WORKSPACE', '.'))
        return output_path
    finally:
        os.unlink(md_path)

Resources

assets/

Place Chinese TrueType font files here for portable use:

  • NotoSansSC-Regular.ttf — Main Chinese font
  • NotoSansSC-Bold.ttf — Bold variant (optional)
  • NotoSansSC-Light.ttf — Light variant (optional)

If no font file is in assets/, the script falls back to C:WindowsFontsmsyh.ttc.

scripts/

  • generate_pdf.js — Main PDF generation script (see template above)

Notes

  • A4 size: 210mm × 297mm (595.28 × 841.89 points)
  • Standard margin: 72pt (1 inch) all sides
  • Chinese font rendering requires a TTF/TTC with CJK glyphs
  • pdfkit doesn't support CSS — all styling is programmatic
  • For table-heavy reports, consider reducing font size to 8-9pt
  • The script handles page breaks automatically by tracking Y position
  • Color markers: 🟢↔green, 🔴↔red, can be mapped to fill colors

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,033
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,018
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,016
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,012
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,012
Skill 文件
  • SKILL.md
    • PDF Report Generator — Markdown转PDF
    • When to Use
    • Prerequisites
      • Chinese Font
    • Workflow: Markdown → PDF
      • Step 1: Parse Markdown content
      • Step 2: Generate PDF via Node.js script
        • Core Script Template
        • CLI Usage
      • Step 3: Verify output
    • Integration with daily-market-report
      • Quick Function (Python → Node bridge)
    • Resources
      • assets/
      • scripts/
    • Notes
  • 项目或源文件

相关 Skill

更多
file-to-pdf file-to-pdf 将各类文件批量转换为 PDF 格式。支持 Office 文档(Word/Excel/PowerPoint)、图片(JPG/PNG/BMP/GIF/WebP/TIFF)、HTML 网页、Markdown 文件和纯文本文件。当用户要求将文件转为 PDF、导出 PDF、把图片合并成 PDF、或批量转换文档格式时触发此技能。This skill should be used when users ask to convert files to PDF, export to PDF, merge images into a PDF, or batch convert documents to PDF format.
PDF 结构化抽取·带证据溯源 PDF 结构化抽取·带证据溯源 从图片型、扫描型、混合型或原生文本 PDF 中提取可审计的结构化字段,并把字段证据确定性映射回原始 PDF 页码、页标签、bbox、原文和证据截图。用于合同、报告、手册、表单、研究资料等需要自定义 JSON Schema 和逐字段溯源的 PDF 抽取任务;默认以 MinerU 为主解析器、Docling 为必装交叉复核器,PaddleOCR 为可选补充解析器。
自动从中间空白处切割A3试卷a3-pdf-splitter 自动从中间空白处切割A3试卷a3-pdf-splitter 智能A3试卷PDF切分工具,自动识别空白位置将A3试卷PDF转换为A4格式。适用场景:切分A3试卷、A3转A4、PDF切分、试卷打印、拆分试卷PDF。
PDF Utils PDF Utils PDF Utils 支持对图像型 PDF 进行 OCR 识别、从文本或 OCR 结果中提取 arXiv ID,以及合并、拆分、渲染等可脚本化的 PDF 处理任务。
PDF 智能阅读助手 Pro PDF 智能阅读助手 Pro PDF文档智能阅读助手 — 提取文本/表格/图片,OCR识别扫描件,结合LLM进行智能总结、关键信息提取、问答。支持加密PDF、大文件分页、批量处理、Markdown导出。轻量OCR优先,路径安全校验。