JavaでPDFを編集する(完全チュートリアル)

This article was translated from English: Does it need improvement?
Translated
View the article in English

以下のチュートリアルでは、Java開発者がIronPDFを使用して既存のPDFドキュメントの内容と構造をどのように操作できるかについての概要を提供します。 以下には、IronPDFのHTML変換機能を使用してHTMLからレンダリングされたPDFドキュメント、および他のサードパーティアプリケーションやソフトウェアライブラリを使用して生成されたPDFが含まれます。

以下に日本語翻訳を提供します:

IronPDF for .NET のチュートリアル C#.NETおよびVB.NETでPDFドキュメントを編集する も利用可能です。

このチュートリアルは、読者が既にIronPDFの使い方を知っていることを前提としています。 HTMLコンテンツをPDFに変換する. このチュートリアルを続ける前に、HTMLからPDFへの変換機能に慣れていない場合は、最初にHTMLからPDFへの変換チュートリアルを読むことを検討してください。 (基本的なワークフローについてのリフレッシュが必要な場合).*


目次

  • ドキュメント構造の編集

    • PDFドキュメントの操作

    • ページの追加、コピー、および削除

    • PDFのマージと分割

    • PDFドキュメントのカスタムサイズを設定する

    • PDFの向きを設定
  • PDFのカスタム余白を設定する
  • PDFドキュメントを画像に変換

  • 背景と前景を追加

    • 背景としてPDFを追加
  • 前景としてPDFを追加
  • 画像とテキスト抽出

    • コンテンツの抽出
  • 画像を抽出
  • ドキュメントプロパティの編集

    • PDFメタデータの追加と使用

    • デジタル署名
  • PDFファイルを圧縮
  • PDFコンテンツを編集する

    • ヘッダーとフッターの追加

    • アウトラインとブックマーク

    • 注釈の追加および編集

    • スタンプと透かし

    • スタンパー概要

    • スタンパーの例

    • PDFにテキストをスタンプする

    • PDFに画像をスタンプする

    • PDFにバーコードをスタンプする

    • PDFにQRコードをスタンプする
  • PDFにウォーターマークを追加する
  • PDFでフォームの使用

    • フォームを作成および編集
  • 既存のフォームを記入
  • PDF を印刷のために送信

はじめに

Java用Mavenライブラリ(PDF)

でインストール マーヴェン

<dependency>
   <groupId>com.ironsoftware</groupId>
   <artifactId>ironpdf</artifactId>
   <version>2024.9.1</version>
</dependency>
または
Java PDF JAR(ジャバPDF JAR)

ダウンロード ジャー

  JARをダウンロード

プロジェクトに手動でインストールする

JavaプロジェクトにIronPDFライブラリを組み込むには、2つの方法があります。

  1. Mavenで構成されたJavaプロジェクトにIronPDFを依存関係として追加

  2. IronPDFのJARファイルをダウンロードして、プロジェクトのクラスパスに手動で追加してください。

    JavaプロジェクトでIronPDFをインストールするには、Javaプロジェクトのpom.xmlファイルの依存関係セクションに以下のアーティファクトを含めてください。

<dependency>
   <groupId>com.ironsoftware</groupId>
   <artifactId>com.ironsoftware</artifactId>
   <version>2024.9.1</version>
</dependency>

JARファイルを手動で管理したい開発者は IronPDFライブラリのJARファイルをダウンロードする クラスパスにプロジェクトを追加します。

IronPDFのJARファイルを直接ダウンロードする これ (Mavenリポジトリから).


チュートリアル内容

ドキュメント構造の編集

PDFドキュメントの操作

IronPDFは、特定のインデックスにPDFを追加する機能、範囲としてまたは個別にページをコピーする機能、および簡単にページを削除する機能を備えているため、PDFの管理が容易になります。 これらのすべてのタスクは背景でシームレスに処理されます。

ページを追加

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;

PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PdfDocument coverPagePdf = PdfDocument.renderHtmlAsPdf("<h1>Cover Page</h1><hr>");
PDF.prependPdf(coverPagePdf);
PDF.saveAs(Paths.get("report_with_cover.pdf"));
JAVA

ページをコピー

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;

PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PDF.copyPages(0,1).saveAs("report_highlight.pdf");
JAVA

ページを削除

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;

PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PDF.removePages(PageSelection.lastPage()).saveAs(Paths.get("assets/lastPageRemove.pdf"));
JAVA

表紙を添付

import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;  
import java.nio.file.Paths;

// Create a Sample Cover Page using RenderHtmlAsPdf
PdfDocument coverPage = PdfDocument.renderHtmlAsPdf("<h1>This is a Cover Page</h1>");
PdfDocument webpage = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf/");

// Set the page number of the PDF document to be created to 2.
HeaderFooterOptions headerFooterOptions = new HeaderFooterOptions();
headerFooterOptions.setFirstPageNumber(1);
TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("");
footer.setCenterText("Page {page}");
footer.setRightText("");
webpage.addTextFooter(footer, headerFooterOptions);

// Convert a web page's content to a PDF document.
// Merge the cover page with the web page and save the new PDF to the filesystem.
try {
    PdfDocument.merge(coverPage, webpage).saveAs(Paths.get("assets/cover_page_pdf.pdf"));
} catch (IOException e) {
    throw new RuntimeException(e);
}
JAVA

以下についてさらに詳しく知る PDFドキュメントに表紙を追加する.

PDFのマージと分割

IronPDF Javaは、使いやすいAPIを利用して、複数のPDFを1つに結合したり、既存のPDFを分割したりするプロセスを簡素化します。

複数の既存のPDFドキュメントを1つのPDFドキュメントに結合する

import com.ironsoftware.ironpdf.PdfDocument;  
import java.io.IOException;  
import java.nio.file.Paths;

String htmlA = "<p> [PDF_A] </p>"
        + "<p> [PDF_A] 1st Page </p>"
        + "<div style = 'page-break-after: always;' ></div>"
        + "<p> [PDF_A] 2nd Page</p>";
String htmlB = "<p> [PDF_B] </p>"
        + "<p> [PDF_B] 1st Page </p>"
        + "<div style = 'page-break-after: always;' ></div>"
        + "<p> [PDF_B] 2nd Page</p>";

PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);
PdfDocument merged = PdfDocument.merge(pdfA, pdfB);

merged.saveAs(Paths.get("assets/merged.pdf"));
JAVA

PDFを分割してページを抽出

import com.ironsoftware.ironpdf.PdfDocument;  
import java.io.IOException;  
import java.nio.file.Paths;
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PdfDocument copied = PDF.copyPage(0);
copied.saveAs("assets/Split.pdf");
JAVA

PDFドキュメントのカスタムサイズを設定する

IronPDFは、開発者が従来のA4サイズを超えた非標準の寸法でPDFドキュメントを作成できるようにします。 (8½インチ x 11インチ または 21.59 cm x 27.94 cm).

import com.ironsoftware.ironpdf.*;  
import com.ironsoftware.ironpdf.render.*;  
import java.io.IOException;  
import java.nio.file.Paths;

String html = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>";  

ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();  
renderOptions.setPaperSize(PaperSize.Custom);  

/*  
 * Setting page sizes using different measuring units: 
 * 1. setCustomPaperWidth( width ) / setCustomPaperHeight( height ): for inches 
 * 2. setCustomPaperSizeInCentimeters( width, height ): for centimeters. 
 * 3. setCustomPaperSizeInMillimeters( width, height ): for millimeters 
 * 4. setCustomPaperSizeInPixelsOrPoints( width, height ): for pixels/points 
 */
renderOptions.setCustomPaperSizeInCentimeters(13.97, 13.97);  
PdfDocument.renderHtmlAsPdf(html, renderOptions).saveAs(Paths.get("assets/CustomPaperSize.pdf"));
JAVA

以下について詳しく知る: PDFのカスタムサイズ.

PDFの向きを設定

IronPDF for Java は、新規および既存のPDFのページの向きを変更することができます。 デフォルトでは、IronPDFで作成される新しいPDFは縦向きに設定されていますが、開発者はChromePdfRenderOptionsインスタンスを使用してコンテンツを変換することで変更できます。 (HTML、RTF、URLなど) PDFに変換。

import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.edit.PageSelection;  
import com.ironsoftware.ironpdf.page.PageRotation;  
import com.ironsoftware.ironpdf.render.*;  
import java.io.IOException;  
import java.nio.file.Paths;

// Use the setPaperOrientation method to set rendered PDFs in portrait or landscape orientation.  
// Note: This will only work for newly-created PDFs!  
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();  
renderOptions.setPaperOrientation(PaperOrientation.LANDSCAPE);  
PdfDocument newPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com", renderOptions);  
newPdf.saveAs(Paths.get("assets/LandscapePdf.pdf"));  

// Use the rotatePage/rotateAllPages methods to adjust the page orientation for existing PDFs  
PdfDocument existingPdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));  

// Get the orientation of the first page of the existing PDF document.  
PageRotation firstPageRotation = existingPdf.getPagesInfo().get(0).getPageRotation();  
System.out.println(firstPageRotation);  

// Rotate the first page of the document only 90 degrees clockwise.  
existingPdf.rotatePage(PageRotation.CLOCKWISE_90, PageSelection.firstPage());  

// Rotate all pages of the document clockwise.  
existingPdf.rotateAllPages(PageRotation.CLOCKWISE_270);  

existingPdf.saveAs(Paths.get("assets/ExistingPdfRotated.pdf"));
JAVA

詳細情報をご希望の場合は、IronPDFのウェブサイトセクションをご覧ください。 PDFの向きを設定する.

PDFのカスタム余白を設定する

IronPDFは、すべての面にデフォルトのマージンとして25mmを設定して新しいPDFを作成します。 (上、下、左、右). ただし、開発者はIronPDFを使用して、デザイン要件を満たすために各余白を特定の測定値でカスタマイズできます。

import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;  
import java.io.IOException;  
import java.nio.file.Paths;

// Set Margins (in millimeters)  
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();  
renderOptions.setMarginTop(40);  
renderOptions.setMarginLeft(20);  
renderOptions.setMarginRight(20);  
renderOptions.setMarginBottom(40);  

PdfDocument.renderHtmlFileAsPdf("assets/wikipedia.html", renderOptions).saveAs(Paths.get("assets/MyContent.pdf"));
JAVA

IronPDFの詳細については、IronPDFのウェブサイトをご覧ください PDFドキュメントのカスタムマージンの設定.

PDFドキュメントを画像に変換

IronPDFは、ロードされたPDFファイルのページ、変換されたソースコンテンツ、またはヘッダー、フッター、余白などが含まれた修正済みPDFを、ファイルシステムに保存された画像、データベースに格納された画像、またはネットワークを介して送信される画像にエクスポートすることができます。

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.image.ToImageOptions;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/composite.pdf"));

// Extract all the pages from the PDF file.
List<BufferedImage> extractedImages = pdf.toBufferedImages();

// With the ToImageOptions object, specify maximum image dimensions for each
// extracted image, as well as their DPI
ToImageOptions rasterOptions = new ToImageOptions();
rasterOptions.setImageMaxHeight(100);
rasterOptions.setImageMaxWidth(100);

// Call the toBufferedImage method along with a PageSelection object to choose the pages from which to
// extract the images
//
// Available PageSelection methods include: allPages, lastPage, firstPage, singlePage(int pageIndex),
// and pageRange(int startingPage, int endingPage)
List<BufferedImage> sizedExtractedImages = pdf.toBufferedImages(rasterOptions, PageSelection.allPages());

// Save all the extracted images to a file location
int i = 1;
for (BufferedImage extractedImage : sizedExtractedImages) {
    String fileName = "assets/images/" + i++ + ".png";
    ImageIO.write(extractedImage, "PNG", new File(fileName));
}
JAVA

背景と前景の追加

IronPDFは、addBackgroundおよびaddForegroundメソッドを提供します PDFに特定の背景または前景の要素を追加する. これらのメソッドにより、開発者はあるPDFの内容を別のPDFの背景または前景として組み込むことができ、共通のデザインテンプレートに基づいたPDFのコレクションを効率的に生成することができます。

背景としてPDFを追加

import com.ironsoftware.ironpdf.*;  
import java.io.IOException;  
import java.nio.file.Paths;

// Load background PDFs from the filesystem (or create them programmatically)  
PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));  

// Render content (HTML, URL, etc) as a PDF Document  
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf");  

// Add the background PDFs to the newly-rendered document.  
pdf.addBackgroundPdf(backgroundPdf);  

pdf.saveAs(Paths.get("assets/BackgroundPdf.pdf"));
JAVA

前景としてPDFを追加

import com.ironsoftware.ironpdf.*;  
import java.io.IOException;  
import java.nio.file.Paths;

// Load foreground PDFs from the filesystem (or create them programmatically)  
PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));  

// Render content (HTML, URL, etc) as a PDF Document  
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf");  

// Add the foreground PDFs to the newly-rendered document.  
pdf.addForegroundPdf(foregroundPdf);  

pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
JAVA

画像とテキスト抽出

IronPDFの包括的なPDF作成および編集機能には、次の機能が含まれます。 コンテンツを抽出 そのコンテンツ抽出方法により詳細に。

extractAllText メソッドはすべての PdfDocument オブジェクトで利用可能であり、PDF ドキュメント内のすべてのテキストを含む文字列を返します。 さらに、extractAllImages メソッドは、PDF に埋め込まれたすべての画像のコレクションを返します。これらの画像はそれぞれ BufferedImage オブジェクトの形式で提供されます。 画像を生のバイトとして取得するには、extractAllRawImages メソッドを使用してください。

コンテンツの抽出

PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://unsplash.com/");
String text = pdf.extractAllText();
System.out.println("Text extracted from the website: " + text);
JAVA

画像を抽出

PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://unsplash.com/");
try {
    List<BufferedImage> images = pdf.extractAllImages();
    System.out.println("Number of images extracted from the website: " + images.size());

    int i = 0;
    for (BufferedImage image : images) {
        ImageIO.write(image, "PNG", Files.newOutputStream(Path.of("assets/extracted_" + ++i + ".png")));
    }
} catch(Exception exception) {
    System.out.println("Failed to extract images from the website");
    exception.printStackTrace();
}
JAVA

ドキュメントプロパティの編集

PDFメタデータの追加と使用

IronPDFは、 PDFメタデータを修正する セキュリティ機能には、PDFを読み取り専用、印刷不可能、パスワード保護、および暗号化することが含まれます。 IronPDF for Javaでは、MetadataManagerを使用してPDFのメタデータにアクセスし、編集することができます。 MetadataManager クラスは、メタデータの内容に直接アクセスできるようにし、開発者が同じ名前のゲッターおよびセッターを通じて一般的なメタデータのプロパティを簡単に読み取り、編集できるようにします。

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.security.PdfPrintSecurity;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;

// Open an encrypted file (or create a new one from HTML)
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/encrypted.pdf"), "password");

// Edit file metadata
MetadataManager metadata = pdf.getMetadata();
metadata.setAuthor("Satoshi Nakamoto");
metadata.setKeywords("SEO, Friendly");
metadata.setModifiedDate(new Date().toString());

// Edit file security settings
// The code below makes the PDF read only and disallows users to copy, paste, and print
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setAllowUserCopyPastContent(false);
securityOptions.setAllowUserAnnotations(false);
securityOptions.setAllowUserPrinting(PdfPrintSecurity.FULL_PRINT_RIGHTS);
securityOptions.setAllowUserFormData(false);
securityOptions.setOwnerPassword("top-secret");
securityOptions.setUserPassword("sharable");

// Change or set the document encryption password
SecurityManager securityManager = pdf.getSecurity();
securityManager.removePasswordsAndEncryption();
securityManager.makePdfDocumentReadOnly("secret-key");

securityManager.setSecurityOptions(securityOptions);
pdf.saveAs(Paths.get("assets/secured.pdf"));
JAVA

デジタル署名

IronPDF for Javaは、.pfxまたは.p12形式のX509Certificate2デジタル証明書を使用して、新規または既存のPDFファイルのセキュアな署名を可能にします。 PDFにデジタル署名を行うことにより、ファイルの真正性が保証され、証明書の適切な検証なしには変更することができません。 これはドキュメントの信頼性を高めます。

サイン証明書を無料で作成する方法をお探しの場合は、Adobe Reader がサポートします。 次の手順に従ってください Adobe デジタル ID チュートリアル.

従来のデジタル署名プロセスに加えて、IronPDF for Java は手書きの署名画像や会社のスタンプ画像を使用してPDFに署名するオプションも提供しています。 これにより、企業はドキュメントをパーソナライズし、追加のセキュリティ層を追加することが容易になります。

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.signature.Signature;
import com.ironsoftware.ironpdf.signature.SignatureManager;
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));

File path = new File("assets/Ironpdf.pfx");
byte [] certificate = new byte [(int)path.length()];

Signature signature = new Signature(certificate,"1234");

SignatureManager manager = PDF.getSignature();

manager.SignPdfWithSignature(signature);
JAVA

PDFファイルを圧縮

IronPDFは、PdfDocumentクラスのcompressImagesメソッドを使用してPDFファイルのサイズを削減し、大きな画像を含むPDFを簡単に圧縮することができます。 この最適化により、PDFをメールや他の通信チャネルで送信する際に、ストレージスペースとコストの大幅な節約が可能になります。

import com.ironsoftware.ironpdf.*;
import java.io.IOException;  
import java.nio.file.Paths;

PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/document.pdf"));  

// Valid image compression values range from 1 to 100, where 100 represents 100% of the  
// original image quality.  
pdf.compressImages(60);  
pdf.saveAs(Paths.get("assets/document_compressed.pdf"));  

// The second, optional parameter can scale down the image resolution according to its visible  
// size in the PDF document. Note that this may cause distortion with some image configurations  
pdf.compressImages(90, true);  
pdf.saveAs(Paths.get("assets/document_scaled_compressed.pdf"));
JAVA

PDFコンテンツの編集

ヘッダーとフッターを追加

IronPDFは次の機能を提供します カスタムHTMLヘッダーとフッターを追加する ChromeRenderOptionsクラスおよびHtmlHeaderFooterクラスを使用してPDFに変換します。 IronPDFは、有効にします カスタムテキストのヘッダーおよびフッター TextHeaderFooter クラスを通じてPDFに追加され、ヘッダー/フッターの左、右、または中央の領域にテキストを指定できます。 これには、のような組み込みのテンプレートタグの使用が含まれます{日付}, {時間}、および {ページ}、または任意のカスタムテキスト。

HTMLヘッダーとフッター

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HtmlHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;

PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Build a footer using HTML
// Merge Fields are: {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
HtmlHeaderFooter footer = new HtmlHeaderFooter();
footer.setMaxHeight(15); // millimeters
footer.setHtmlFragment("<center><i>{page} of {total-pages}</i></center>");
footer.setDrawDividerLine(true);
pdf.addHtmlFooter(footer);
List<PdfDocument> pdfs = new ArrayList<>();

// Build a header using an image asset
// Note the use of BaseUrl to set a relative path to the assets
HtmlHeaderFooter header = new HtmlHeaderFooter();
header.setMaxHeight(20); // millimeters
header.setHtmlFragment("<img src=\"logo.png\" />");
header.setBaseUrl("./assets/");
pdf.addHtmlHeader(header);
try {
    pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
} catch (IOException e) {
    throw new RuntimeException(e);
}
JAVA

テキストヘッダーとフッター

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.font.FontTypes;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;

// Initialize HeaderFooterOptions object.
HeaderFooterOptions options = new HeaderFooterOptions();
PdfDocument pdf = PdfDocument.renderUrlAsPdf("http://www.google.com");

// Add a header to every page easily
// Mergeable fields are:
// {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
options.setFirstPageNumber(1); // use 2 if a coverpage  will be appended
TextHeaderFooter textHeader = new TextHeaderFooter();
textHeader.setDrawDividerLine(true);
textHeader.setCenterText("{url}");
textHeader.setFont(FontTypes.getHelvetica());
textHeader.setFontSize(12);
pdf.addTextHeader(textHeader, options);

// Add a footer too
TextHeaderFooter textFooter = new TextHeaderFooter();
textFooter.setDrawDividerLine(true);
textFooter.setFont(FontTypes.getArial());
textFooter.setFontSize(10);
textFooter.setLeftText("{date} {time}");
textFooter.setRightText("{page} of {total-pages}");
pdf.addTextFooter(textFooter, options);

try {
    pdf.saveAs(Paths.get("assets/text_headers_footers.pdf"));
} catch (IOException e) {
    System.out.println("Failed to save PDF");
    throw new RuntimeException(e);
}
JAVA

アウトラインとブックマーク

BookmarkManagerを使用すると、開発者は階層構造を作成できます PDF内のブックマーク文書内の異なるセクションに簡単に移動できるようにします。 新しいブックマークを追加するために、開発者はタイトルとページ番号を指定してaddメソッドを使用できます。 ブックマークは、他のブックマークの中にネストすることもでき、より整理された構造を作成できます。

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.Bookmark;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

// Load an existing PDF from the file system (or create a new one from HTML)
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/book.pdf"));

// Add top-level bookmarks to pages of the PDF using their page indices
BookmarkManager bookmarks = pdf.getBookmark();
bookmarks.addBookMarkAtEnd("Author's Note", 2);
bookmarks.addBookMarkAtEnd("Table of Contents", 3);
bookmarks.addBookMarkAtEnd("Summary", 10);
bookmarks.addBookMarkAtEnd("References", 12);

// Retrieve a reference to the Summary bookmark so that we can add a sublist of bookmarks to it.
List<Bookmark> bookmarkList = bookmarks.getBookmarks();
Bookmark bookmark = bookmarkList.get(2);
bookmark.AddChildBookmark("Conclusion", 11);

// Save the PDF to the filesystem
pdf.saveAs(Paths.get("assets/bookmarked.pdf"));
JAVA

注釈の追加および編集

IronPDFでは、「付箋」スタイルのノートを追加できます 特定のページへの注釈 AnnotationManagerクラスとAnnotationOptionsクラスを使用してPDFを注釈します。 開発者は、テキストおよび (x、y) AnnotationOptions コンストラクタに引数として座標を渡し、その後 AnnotationManageraddTextAnnotation メソッドを使用して、注釈を目的のページに追加します。

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.annotation.AnnotationIcon;
import com.ironsoftware.ironpdf.annotation.AnnotationManager;
import com.ironsoftware.ironpdf.annotation.AnnotationOptions;
import java.io.IOException;
import java.nio.file.Paths;

// Create a new PDF or load an existing one from the filesystem
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));

// Create an annotation to be placed at a specific location on a page.
AnnotationOptions annotation = new AnnotationOptions(
        "This is a major title",                                // Title of the annotation
        "This is the long 'sticky note' comment content...",    // Content of the annotation
        150,                                                    // x-axis coordinate location
        250                                                     // y-axis coordinate location
);
annotation.setIcon(AnnotationIcon.HELP);
annotation.setOpacity(0.9);
annotation.setPrintable(false);
annotation.setHidden(false);
annotation.setOpen(true);
annotation.setReadonly(true);
annotation.setRotateable(true);

// Add the annotation to a specific page of the PDF
AnnotationManager annotationManager = pdf.getAnnotation();
annotationManager.addTextAnnotation(annotation, 0);

// Save the PDF with the modifications
pdf.saveAs(Paths.get("assets/annotated.pdf"));
JAVA

スタンプと透かし

IronPDF for Javaは、PDFにスタンプやウォーターマークを追加するための広範な機能を提供する強力なAPIを備えています。 使いやすいインターフェイスのおかげで、開発者はPDFに画像やHTMLスタンプを簡単に追加することができます。 会社のロゴ、機密通知、または一意の識別子を追加する必要がある場合でも、IronPDFが対応します。 APIを使用すると、PDFに視覚的に魅力的なスタンプを簡単に追加でき、プロフェッショナルで個性的な仕上がりを実現します。

PDFにテキストをスタンプする

import java.io.IOException;
import java.nio.file.Paths;

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.TextStamper;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
TextStamper stamper1 = new TextStamper();
stamper1.setText("Hello World! Stamp One Here!");
stamper1.setFontFamily("Bungee Spice");
stamper1.setUseGoogleFont(true);

stamper1.setFontSize(100);
stamper1.setBold(true);
stamper1.setItalic(false);
stamper1.setVerticalAlignment(VerticalAlignment.TOP);

PDF.applyStamp(stamper1);
JAVA

PDFに画像をスタンプする

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.stamp.ImageStamper;

PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
ImageStamper imageStamper = new ImageStamper(Paths.get("assets/logo.png"));
// Apply to every page, one page, or some pages
PDF.applyStamp(imageStamper);
PDF.applyStamp(imageStamper, PageSelection.singlePage(2));
PDF.applyStamp(imageStamper, PageSelection.pageRange(0, 2));
JAVA

PDFにバーコードをスタンプする

import java.io.IOException;
import java.nio.file.Paths;

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
BarcodeStamper barcodeStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39);

barcodeStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
barcodeStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);

PDF.applyStamp(barcodeStamp);
JAVA

PDFにQRコードをスタンプする

import java.io.IOException;
import java.nio.file.Paths;

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
BarcodeStamper QRStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode);
QRStamp.setHeight(50);
QRStamp.setWidth(50);
QRStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
QRStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
PDF.applyStamp(QRStamp);
JAVA

PDFにウォーターマークを追加する

import java.io.IOException;
import java.nio.file.Paths;

import com.ironsoftware.ironpdf.PdfDocument;

PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
String html = "<h1> Example Title <h1/>";
int watermarkOpacity = 30;
PDF.applyWatermark(html, watermarkOpacity);
JAVA

PDFでフォームを使用する

IronPDF Javaは、開発者に対してPDFドキュメントのフォームテキストフィールドに値を設定および取得するための簡単かつ効率的な方法を提供します。 FormManagerクラスを使用すると、開発者はsetFieldValueメソッドを呼び出して、目的のテキストフィールドの名前と入力する値を指定するだけで済みます。

フォームフィールドの値を取得するために、開発者は関連する名前またはインデックスを使用して、FormManagerFormField オブジェクトのコレクションを直接アクセスできます。 このレベルのフォームフィールド制御により、開発者は動的でインタラクティブなPDFフォームを簡単に扱うことができます。

フォームを作成および編集

import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;  
import java.io.IOException;  
import java.nio.file.*;

// #1 Use Case: Create a PDF Form from HTML Form Markup  
Path outputLocation = Paths.get("assets/BasicForm.pdf");  
String formHTML = "<html>"  
  + "<body>"  
  + "<h2>Editable PDF  Form</h2>"  
  + "<form>"  
  + "First name: <br> <input type='text' name='firstname' value=''> <br>"  
  + "Last name: <br> <input type='text' name='lastname' value=''>"  
  + "</form>"  
  + "</body>"  
  + "</html>";  

ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();  
renderOptions.setCreatePdfFormsFromHtml(true);  
PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);  

// #2 Use Case: Writing Values to the PDF Form  
PdfDocument form = PdfDocument.fromFile(outputLocation);  

// Set the value of the firstname input field.  
form.getForm().setFieldValue("firstname", "Minnie");  

// Set the value of the lastname input field.  
form.getForm().setFieldValue("lastname", "Mouse");  

// Save the changes to the PDF Form.  
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
JAVA

既存のフォームを記入

import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;  
import java.io.IOException;  
import java.nio.file.*;

PdfDocument form = PdfDocument.fromFile("assets/pdfform.pdf");  

// Set the value of the firstname input field.  
form.getForm().setFieldValue("firstname", "Minnie");  

// Set the value of the lastname input field.  
form.getForm().setFieldValue("lastname", "Mouse");  

// Save the changes to the PDF Form.  
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
JAVA

印刷用にPDFを送信

IronPDFの印刷メソッドは、開発者が簡単に PDF印刷を統合する アプリケーションに統合します。 プリントメソッドを呼び出すだけで、オペレーティングシステムの印刷ダイアログが開き、プリンター、用紙サイズ、部数などの印刷設定を調整するオプションがユーザーに提供されます。

import com.ironsoftware.ironpdf.PdfDocument;
import java.awt.print.PrinterException;

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Created with IronPDF!</h1>");
try {
    pdf.print();
} catch(PrinterException exception) {
    System.out.println("Failed to print PDF");
    exception.printStackTrace();
}
JAVA