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

Angular组件中使用GcPdfViewer创建自定义图章问题求助

Angular中GcPdfViewer添加本地图片图章的可行示例

组件模板(pdf-stamp.component.html)

<div #viewerContainer style="width: 100%; height: 800px;"></div>

组件类代码(pdf-stamp.component.ts)

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { GcPdfViewer } from '@grapecity/gcpdfviewer';

@Component({
  selector: 'app-pdf-stamp',
  templateUrl: './pdf-stamp.component.html',
  styleUrls: ['./pdf-stamp.component.css']
})
export class PdfStampComponent implements AfterViewInit {
  @ViewChild('viewerContainer') viewerContainer!: ElementRef;
  private viewer!: GcPdfViewer;

  ngAfterViewInit(): void {
    // 初始化GcPdfViewer,确保worker路径正确
    this.viewer = new GcPdfViewer(this.viewerContainer.nativeElement, {
      workerSrc: 'assets/gcpdfviewer.worker.js',
      restoreViewStateOnLoad: false
    });

    // 加载目标PDF文件(替换为你的PDF路径)
    this.viewer.loadDocument('assets/sample.pdf').then(() => {
      // PDF加载完成后,加载本地图片创建图章
      this.addCustomImageStamp('assets/stamp.png');
    });
  }

  private addCustomImageStamp(imagePath: string): void {
    const stampImage = new Image();
    stampImage.crossOrigin = 'anonymous';
    
    stampImage.onload = () => {
      // 创建图章注解,用类型断言解决TS类型缺失报错
      const stampAnnotation = this.viewer.addAnnotation('stamp', {
        pageIndex: 0,
        rect: [100, 100, stampImage.width / 2, stampImage.height / 2], // 调整图章位置与尺寸
        image: stampImage,
        author: '自定义图章',
        subject: '图片图章'
      } as any);

      // 刷新视图显示图章
      this.viewer.refresh();
    };

    stampImage.src = imagePath;
  }
}

关键注意事项

  • 依赖与资源配置:确保已安装@grapecity/gcpdfviewer,并将node_modules中的gcpdfviewer.worker.js复制到assets目录,同时在angular.json的assets配置中包含该文件、目标PDF和图章图片。
  • 类型报错处理:使用as any类型断言可快速解决"Type is missing properties"报错。若需更严谨的类型检查,可在项目根目录的src/typings.d.ts中扩展类型定义:
declare module '@grapecity/gcpdfviewer' {
  interface AnnotationProperties {
    image?: HTMLImageElement;
  }
}
  • 执行时机:必须等待PDF加载完成后再添加图章,避免因页面未初始化导致的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 21:32:24