この記事は、Java を使用して PDF に画像を挿入する方法 を支援します。 IDE 構成の詳細、アプリケーションを作成するための段階的なプロセス、および Java を使用して PDF に画像を追加するための実行可能なサンプル コードを提供します。また、プロセスをカスタマイズして、PNG、JPEG などの任意の形式で画像をレンダリングし、PDF ページの目的の位置に画像を配置するためのさまざまなオプションについても学習します。
Java を使用して PDF に画像を挿入する手順
- Aspose.PDF for Java を使用して画像を挿入するための環境を確立します
- ソース PDF ファイルを読み込み、最初の page にアクセスして画像を追加し、グラフィックスの状態を保存します
- 画像のストリームを作成し、読み込まれた PDF の画像コレクション リソースに追加します。
- 画像の目的の長方形の位置を使用して、Matrix オブジェクトをインスタンス化します
- 画像描画オプションを定義し、Do() メソッドを使用して画像を描画します
- 画像と PDF ストリームを閉じる前に、グラフィック状態を復元し、出力 PDF を保存します。
これらの手順では、Java を使用して PDF に画像を追加する方法 について説明します。最初に、読み込まれた PDF ファイルからページ参照が取得され、次に画像ストリームが作成されます。この画像は、選択したページの画像コレクションに追加され、変換マトリックスは、ターゲット画像の位置四角形を使用して宣言されます。最後に、画像は Do() メソッドを使用してレンダリングされ、結果の PDF ファイルがディスクに保存されます。
Java を使用して PDF に写真を追加するコード
import com.aspose.pdf.*; | |
import com.aspose.pdf.operators.*; | |
public class AsposeTest { | |
public static void main(String[] args) throws Exception {//Main function to add image to a PDF using Java | |
// Instantiate the license | |
License lic = new License(); | |
lic.setLicense("Aspose.Total.lic"); | |
// Load the source PDF file | |
Document srcDocument = new Document("sample.pdf"); | |
// Get a reference to the target page | |
Page pdfPage = srcDocument.getPages().get_Item(1); | |
// Create stream for the image | |
java.io.FileInputStream streamForImage = new java.io.FileInputStream(new java.io.File("logo.png")); | |
// Add the stream of image to the collection of images in the selected page | |
pdfPage.getResources().getImages().add(streamForImage); | |
// Save the current state of the graphics for later use | |
pdfPage.getContents().add(new GSave()); | |
// Instantiate the Matrix object using the desired rectangular area | |
Rectangle rect = new Rectangle(50, 750, 100, 800); | |
Matrix matrix = new Matrix(new double[] { rect.getURX() - rect.getLLX(), 0, 0, | |
rect.getURY() - rect.getLLY(), rect.getLLX(), rect.getLLY() }); | |
// Define how image must be placed | |
pdfPage.getContents().add(new ConcatenateMatrix(matrix)); | |
XImage pdfXimage = pdfPage.getResources().getImages().get_Item(pdfPage.getResources().getImages().size()); | |
// Draw image using the Do operator | |
pdfPage.getContents().add(new Do(pdfXimage.getName())); | |
// Restore the graphics state | |
pdfPage.getContents().add(new GRestore()); | |
// Save the resultant PDF | |
srcDocument.save("updated_document.pdf"); | |
// Close image stream | |
streamForImage.close(); | |
// Close the PDF | |
srcDocument.close(); | |
System.out.println("Done"); | |
} | |
} |
このコードは、Java を使用して PDF に画像を追加する プロセスを示しています。 Document クラスを使用して PDF をロードし、Page クラス オブジェクトを使用してターゲット PDF ページへの参照を保持し、FileInputStream オブジェクトを使用してターゲット画像を保持し、rectangle クラスを使用してページ上の画像位置を記述し、Matrix オブジェクトを定義します。画像の描画、および画像をレンダリングする Do() メソッド。グラフィックスの状態は、この操作を開始する前に保存され、操作が完了すると復元されることに注意してください。
この記事では、Java を使用して PDF に写真を追加するプロセスを見てきました。 PDF に透かしを追加するプロセスを知りたい場合は、Javaを使用してPDFに透かしを追加する方法 の記事を参照してください。