You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PDFtron便签注释顶部添加标签(非文本分组方式)

在PDFtron的Sticky Annotation顶部添加标签(无需分组文本)

要实现无需额外添加文本注释并分组的方式给Sticky Annotation(便签注释)顶部添加标签,可以通过重写便签注释的绘制逻辑来实现,直接在渲染便签时同步绘制顶部标签。

实现代码

// 确保在PDFtron文档加载完成后执行
instance.Core.documentViewer.addEventListener('documentLoaded', () => {
  // 保存StickyAnnotation原有的draw方法
  const originalStickyDraw = instance.Core.Annotations.StickyAnnotation.prototype.draw;

  // 重写draw方法,自定义绘制逻辑
  instance.Core.Annotations.StickyAnnotation.prototype.draw = function(ctx, pageMatrix) {
    const labelHeight = 18; // 自定义标签高度
    const labelBgColor = new instance.Core.Annotations.Color(240, 240, 240); // 标签背景色
    const labelTextColor = new instance.Core.Annotations.Color(0, 0, 0); // 标签文本颜色
    const labelPadding = 4; // 标签内边距

    // 计算标签的绘制区域
    const labelRect = new instance.Core.Annotations.Rect(
      this.X,
      this.Y - labelHeight,
      this.X + this.Width,
      this.Y
    );

    // 绘制标签背景矩形
    ctx.fillStyle = labelBgColor.toHexString();
    ctx.fillRect(labelRect.x1, labelRect.y1, labelRect.width(), labelRect.height());

    // 绘制标签文本(使用注释的Subject属性作为标签内容)
    ctx.fillStyle = labelTextColor.toHexString();
    ctx.font = '12px Arial';
    ctx.textAlign = 'left';
    ctx.textBaseline = 'middle';
    const textPositionY = labelRect.y1 + labelHeight / 2;
    ctx.fillText(this.Subject || '便签', labelRect.x1 + labelPadding, textPositionY);

    // 临时调整便签的Y坐标,让便签主体在标签下方绘制
    const originalY = this.Y;
    this.Y += labelHeight;

    // 调用原draw方法绘制便签主体
    originalStickyDraw.call(this, ctx, pageMatrix);

    // 恢复原Y坐标,避免影响注释的实际位置属性
    this.Y = originalY;
  };
});

关键说明

  • 直接修改StickyAnnotation的原型绘制方法,所有新增或已存在的便签注释都会自动应用该标签样式,无需在添加注释时额外处理
  • 标签内容直接复用注释的Subject属性,也可根据需求替换为其他字段(如自定义属性)
  • 可通过调整labelHeight、labelBgColor、font等参数自定义标签样式
  • 仅在渲染时临时偏移便签位置,注释的实际坐标属性不会被修改,不影响后续的交互、保存和导出

内容的提问来源于stack exchange,提问作者gilbertdim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 00:45:17