この記事では、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に透かしを追加する方法 の記事を参照してください。