我们在WEB浏览器中用PDF.JS展示PDF文件,让客户在网页中添加注释;
现在的方式是用户PDF页面中选择一小段字符,然后我们用选中的字符和PDF的页码通过Aspose.Pdf中的TextFragmentAbsorber来检索指定页码中是否存在这一段字符,从而获取这段字符的坐标。
这是现在使用的代码:
public bool AddPDFAnnotation(string filepath, int pageindex, string Annotation, string dw)
{
try
{
License license = new License();
license.SetLicense("Aspose.Pdf.lic");
//open document
Document pdfDocument = new Document(filepath);
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(dw);
pdfDocument.Pages[pageindex].Accept(textFragmentAbsorber);
PageCollection pages = pdfDocument.Pages;
pages.Accept(textFragmentAbsorber);
// textFragmentAbsorber.TextFragments[0].Rectangle;
if (textFragmentAbsorber.TextFragments.Count == 0)
{
return false;
}
//create annotation
TextAnnotation textAnnotation = new TextAnnotation(pdfDocument.Pages[pageindex], textFragmentAbsorber.TextFragments[1].Rectangle);// new Aspose.Pdf.Rectangle(200, 200, 200, 200));
textAnnotation.Title = "注释标题";
textAnnotation.Subject = "注释主题";
textAnnotation.State = AnnotationState.Accepted;
textAnnotation.Contents = Annotation;
textAnnotation.Open = true;
textAnnotation.Icon = TextIcon.Key;
Border border = new Border(textAnnotation);
border.Width = 5;
border.Dash = new Dash(1, 1);
textAnnotation.Border = border;
textAnnotation.Rect = textFragmentAbsorber.TextFragments[1].Rectangle;// new Aspose.Pdf.Rectangle(200, 100, 100, 100);
//add annotation in the annotations collection of the page
pdfDocument.Pages[pageindex].Annotations.Add(textAnnotation);
////save output file
pdfDocument.Save(filepath);
return true;
}
catch (Exception ex)
{
// Loger.Error(ex, " ");
return false;
}
}
但是上面的代码有缺陷,一旦用户选择的内容包含空格、特殊符号或者选中的字符太长了,就会出现TextFragmentAbsorber 检索不到PDF内容,导致获取不到坐标的情况;
希望你们可以提供一个解决方式给我们来处理这个问题;
或者可以告诉我如何在PDF.JS显示的PDF文件中获取到精确的坐标来对应PDF文件的有效坐标来添加注释;
拜托了,谢谢!
这个是客户生产的PDF文件格式:
32543-8.pdf (446.6 KB)
微信截图_20210507224424.jpg (148.0 KB)