使用C#给PDF文档添加注释的实现代码

2019-12-30 16:17:49王冬梅

添加自由文本注释

同样,给文档添加自由文本注释也相对简单。

步骤1:新建一个PDF文档对象,并添加一个新页面。


PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();

步骤2:初始化一个PdfFreeTextAnnotation,然后自定义注释的文本。


RectangleF rect = new RectangleF(0, 40, 150, 50);
PdfFreeTextAnnotation textAnnotation = new PdfFreeTextAnnotation(rect);
textAnnotation.Text = "Free text annotation ";

步骤3:设置注释的属性,包括字体、填充颜色、边框颜色和透明度。


PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 10);
PdfAnnotationBorder border = new PdfAnnotationBorder(1f);
textAnnotation.Font = font;
textAnnotation.Border = border;
textAnnotation.BorderColor = Color. Purple;
textAnnotation.LineEndingStyle = PdfLineEndingStyle.Circle;
textAnnotation.Color = Color. Pink;
textAnnotation.Opacity = 0.8f;

步骤4:添加注释到页面。


page.AnnotationsWidget.Add(textAnnotation); 

步骤5:保存并重新打开文档。


doc.SaveToFile("FreeTextAnnotation.pdf", FileFormat.PDF);
System.Diagnostics.Process.Start("FreeTextAnnotation.pdf");

这是添加自由文本注释的效果图:

C#,PDF,添加注释

全部代码:


PdfDocument doc = new PdfDocument();
      PdfPageBase page = doc.Pages.Add();
      
      RectangleF rect = new RectangleF(0, 40, 150, 50);
      PdfFreeTextAnnotation textAnnotation = new PdfFreeTextAnnotation(rect);
      textAnnotation.Text = "Free text annotation ";
    
      PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 10);
      PdfAnnotationBorder border = new PdfAnnotationBorder(1f);
      textAnnotation.Font = font;
      textAnnotation.Border = border;
      textAnnotation.BorderColor = Color. Purple;
      textAnnotation.LineEndingStyle = PdfLineEndingStyle.Circle;
      textAnnotation.Color = Color.Pink;
      textAnnotation.Opacity = 0.8f;
      
      page.AnnotationsWidget.Add(textAnnotation);
      doc.SaveToFile("FreeTextAnnotation.pdf", FileFormat.PDF);
      System.Diagnostics.Process.Start("FreeTextAnnotation.pdf");

之前我也分享过如何在C#里面给PPT添加注释,也许对你有帮助。谢谢浏览!

 
注:相关教程知识阅读请移步到c#教程频道。