本文介绍如何使用 Java 在 PDF 中插入评论。它提供了建立环境所需的所有信息、步骤列表和可运行的示例代码以使用 Java 将注释添加到 PDF。它将引导您添加和自定义文本注释,然后将其添加到所选 PDF 页面的注释集合中,然后再将其保存在磁盘上。
使用 Java 向 PDF 添加注释的步骤
- 建立环境添加Aspose.PDF for Java添加注解
- 使用 Document 类对象创建或加载 PDF 以添加注释
- 创建TextAnnotation类对象的对象并设置其属性
- 创建边框对象并将其添加到注释对象
- 将注释添加到所选页面的注释集合中
- 保存生成的带有注释的 PDF 文件
上述步骤描述了如何使用 Java 向 PDF 添加注释,其中提供了环境配置,然后创建 PDF 文件,然后创建文本注释并将其添加到 PDF 文件。所有必要的类都已确定,例如 TextAnnotation 类用于创建评论,Border 类用于在评论周围创建边框。在最后一步中,使用 Page 类的 getAnnotations().add() 方法将此注释添加到注释集合中。
使用 Java 在 PDF 中添加注释的代码
import com.aspose.pdf.AnnotationState; | |
import com.aspose.pdf.Border; | |
import com.aspose.pdf.Dash; | |
import com.aspose.pdf.Document; | |
import com.aspose.pdf.License; | |
import com.aspose.pdf.Page; | |
import com.aspose.pdf.Rectangle; | |
import com.aspose.pdf.TextAnnotation; | |
import com.aspose.pdf.TextFragment; | |
import com.aspose.pdf.TextIcon; | |
public class AsposeProjects { | |
public static void main(String[] args) throws Exception {//main function to annotate a PDF in Java | |
// Load a license | |
License lic= new License(); | |
lic.setLicense("Aspose.Total.lic"); | |
// Initialize document object | |
Document pdfDocument = new Document(); | |
// Add a page | |
Page targetPage = pdfDocument.getPages().add(); | |
// Add some sample text to the new page | |
targetPage.getParagraphs().add(new TextFragment("Here are the sample contents of the PDF")); | |
// Create annotation | |
TextAnnotation annotation = new TextAnnotation(pdfDocument.getPages().get_Item(1), new Rectangle(220, 420, 420, 620)); | |
annotation.setTitle("Title of the annotation"); | |
annotation.setSubject("Subject of the annotation"); | |
annotation.setState(AnnotationState.Accepted); | |
annotation.setContents("Contents of the annotation"); | |
annotation.setOpen(true); | |
annotation.setIcon(TextIcon.Key); | |
Border border = new Border(annotation); | |
border.setWidth(6); | |
border.setDash(new Dash(1, 1)); | |
annotation.setBorder(border); | |
// Add an annotation | |
pdfDocument.getPages().get_Item(1).getAnnotations().add(annotation); | |
// Save output file | |
pdfDocument.save("AnnotatedPdf.pdf"); | |
System.out.println("Done"); | |
} | |
} |
上述示例演示了使用 Java* 在 PDF 中*插入注释的过程。 TextAnnotation 类用于设置不同的属性,而您可以设置其他属性以及设置文本水平和垂直对齐方式、回复类型、不透明度、边距和超链接等等。我们还设置了注释的边框,但您可以根据需要设置其矩形、高度、颜色和边距。
在本文中,我们学习了使用 Java 在 PDF 中放置评论的过程。如果您想了解向 PDF 添加水印的过程,请参阅 如何使用Java为PDF添加水印 上的文章。