JavaでPDFファイルを作成する方法
JavaでのPDFファイル作成は、ビジネスアプリケーションにおける一般的な要件です:請求書やレポートのオンデマンド生成、証明書、領収書、監査ログの作成。 IronPDF for Javaは、完全なChromiumレンダリングエンジンを使用してHTMLをPDFに変換します。つまり、HTML5、CSS3、およびJavaScriptコンテンツは、書式の損失なく忠実にレンダリングされます。
このガイドでは、HTML文字列から、ローカルHTMLファイルから、ライブURLからの3つのPDF作成方法をカバーしています。 それはページ形式の設定、パスワード保護、およびSpring Bootの統合もカバーします。
クイックスタート: JavaでHTMLからPDFを作成する
- IronPDF を
pom.xmlに追加します:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/maven-dependency.xml
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/maven-dependency.xml
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
- ライブラリをインポートしてPDFを作成します:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/quickstart.java
import com.ironsoftware.ironpdf.*;
import java.nio.file.Paths;
// Set your license key (remove watermarks in production)
License.setLicenseKey("Your-License-Key");
// Convert HTML string to PDF and save
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello, IronPDF!</h1>");
pdf.saveAs(Paths.get("output.pdf"));
JavaでPDFファイルを作成する方法
- MavenまたはGradleを通じてIronPDF Javaライブラリをインストールする
com.ironsoftware.ironpdf.*をインポートし、ライセンスキーを設定します- PDFをメモリ内で作成するには、HTML文字列を用いて
PdfDocument.renderHtmlAsPdf()を呼び出します - ローカルHTMLファイルをPDFに変換するには
PdfDocument.renderHtmlFileAsPdf()を使用します - 完成した文書をディスクに書き込むには
pdf.saveAs()を呼び出します
Java用IronPDFとは何で、なぜ使うべきか?
IronPDF for Javaは、Chromiumレンダリングエンジンを基に構築されたPDF生成および操作ライブラリです。Chromeが通常どおりHTMLをレンダリングするため、複雑なレイアウト、カスタムフォント、CSSアニメーション、JavaScript生成コンテンツ、埋め込まれた画像をマニュアルでレイアウトコードを書くことなく処理します。
このライブラリは単一の依存として完全なPDFライフサイクルをカバーします。 開発者はスクラッチから文書を作成したり、既存のHTMLコンテンツを変換したり、ファイルを結合または分割したり、ウォーターマークを追加したり、パスワードで暗号化したり、テキストや画像を抽出したり、記入可能なフォームを生成したりと、一貫したAPIを通じてさまざまな操作が可能です。 HTMLを多用するワークフローの場合、IronPDFはApache PDFBoxのような低レベルのPDFライブラリが要求する手動によるページレイアウト計算を回避します。
iTextのように多くの商業利用にはAGPLオープンソースライセンスが必要な場合とは異なり、IronPDFは商業フレンドリーのライセンスを提供し、複雑なライセンスコンプライアンスレビューは必要ありません。 IronPDF for JavaはMavenアーティファクトとして提供され、Windows、Linux、macOSで動作します。 それはSpring Boot、Jakarta EE、およびスタンドアロン for Javaアプリケーションと統合します。 このライブラリはAWS、Azure、Google Cloudでのサーバーデプロイメントもサポートします。
JavaでIronPDFを使用するための前提条件は何ですか?
必要なJavaバージョンとビルドツールは何ですか?
IronPDF for JavaはJDK 8以降を必要とします。 推奨される最小は、製品動作用にJDK 11 (LTS)です。 OracleダウンロードページからJDKをダウンロードするか、Eclipse TemurinなどのOpenJDKディストリビューションを使用します。
Maven (3.6+)とGradle (7.0+)の両方がサポートされています。 Mavenは、エンタープライズJavaプロジェクトのより一般的な選択です。
MavenプロジェクトにIronPDFを追加する方法は?
プロジェクトの pom.xml を開き、次の依存関係を <dependencies> ブロック内に追加します:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/maven-full.xml
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/maven-full.xml
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>2024.9.1</version>
</dependency>
保存後に mvn install を実行するか、IDE が依存関係を自動的に解決するようにします。 Maven CentralからIronPDFをダウンロードするため、プライベートリポジトリの構成は不要です。
GradleプロジェクトにIronPDFを追加する方法は?
dependencies ブロックに次の行をあなたの build.gradle ファイルに追加してください。
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/gradle-dependency.gradle
implementation 'com.ironsoftware:ironpdf:2024.9.1'
ライブラリを取得するために gradle build を実行します。 Maven Centralで最新の公開バージョンを確認してください。
必要なインポートと構成は何ですか?
以下のインポートステートメントをJavaソースファイルの先頭に追加します:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/imports.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.render.PaperOrientation;
import com.ironsoftware.ironpdf.render.PaperSize;
import com.ironsoftware.ironpdf.security.SecurityOptions;
import com.ironsoftware.ironpdf.security.SecurityManager;
import java.io.IOException;
import java.nio.file.Paths;
PDF の生成前に main メソッドまたはアプリケーションの起動時にライセンスキーを設定してください:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/license-setup.java
License.setLicenseKey("Your-License-Key");
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/license-setup.java
License.setLicenseKey("Your-License-Key");
注意: 有効なライセンスキーがないと、PDFにはトライアルウォーターマークが生成されます。 ライセンスを購入するか、無料トライアルを開始することでこれを削除します。 Javaでライセンスキーを使用するを参照して、追加の構成オプションをご確認ください。
JavaでHTML文字列からPDFを作成する方法は?
任意の HTML 文字列を直接 PdfDocument.renderHtmlAsPdf() に渡します。 IronPDF は、メモリ上で完成したドキュメントを表す PdfDocument インスタンスを返します。 それを書き込むには saveAs() を呼び出します。
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/html-string-to-pdf.java
// HTML content with inline CSS
String htmlContent = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";
// Render HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlContent);
// Save to disk
pdf.saveAs(Paths.get("html.pdf"));
renderHtmlAsPdf() はフル HTML5 および CSS3 仕様をサポートしており、Web フォント、Flexbox、グリッドレイアウト、JavaScript 実行を含みます。 以下の例はカスタムスタイルを持つ複数行のHTMLテンプレートを使用しています:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/html-string-styled.java
// Multi-line HTML with CSS styling using a text block (Java 13+)
String styledHtml = """
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #2563eb; border-bottom: 2px solid #e5e7eb; padding-bottom: 8px; }
.summary { background: #f3f4f6; padding: 16px; border-radius: 4px; }
</style>
</head>
<body>
<h1>Invoice #1042</h1>
<div class="summary">
<p>Amount due: $1,250.00</p>
<p>Due date: 2024-06-01</p>
</div>
</body>
</html>
""";
PdfDocument invoice = PdfDocument.renderHtmlAsPdf(styledHtml);
invoice.saveAs(Paths.get("invoice.pdf"));
上記の請求書例はJava 13以降で利用可能なJavaテキストブロックを使用して、よりクリーンな複数行のHTMLを提供します。 古い Java バージョンの場合、renderHtmlFileAsPdf() を使用して HTML 文字列を手動で連結するかファイルから読み込みます。 JavaScriptレンダリングを含むHTMLからPDFへの変換全般を見るには、Java向けHTMLからPDFへのチュートリアルをご確認ください。
JavaでローカルHTMLファイルからPDFを作成する方法は?
ローカルファイルシステムに保存された HTML ファイルを変換するために PdfDocument.renderHtmlFileAsPdf() を使用します。 パスを文字列として渡します; 相対パスは現在の作業ディレクトリに対して解決します:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/html-file-to-pdf.java
// Convert a local HTML file to PDF
PdfDocument filePdf = PdfDocument.renderHtmlFileAsPdf("invoice-template.html");
// Save the converted document
filePdf.saveAs(Paths.get("invoice_output.pdf"));
IronPDFは、参照されたすべてのアセット(外部CSSファイル、ローカル画像、JavaScriptライブラリ)をHTMLファイルのディレクトリに対して相対的に解決します。 これにより、リンクされたスタイルシートと一緒に完全なHTMLテンプレートを構築し、資産パスを変更することなくIronPDFを通じて実行できます。
メソッドは String パスと java.nio.file.Path オブジェクトの両方を受け入れます。 作業ディレクトリの曖昧さを避けるため、本番使用では絶対パスを使用することをお勧めします。 HTMLファイルからPDFへの例で完全な作業デモを参照してください。
JavaでウェブページのURLからPDFを作成する方法は?
PdfDocument.renderUrlAsPdf() はライブURLを取得し、それを Chromium を使ってレンダリングしてPDFを返します。 これはダッシュボードのスナップショットをキャプチャしたり、ホストされたレシートページからPDFレシートを生成したり、ウェブコンテンツをアーカイブしたりするのに便利です:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/url-to-pdf.java
// Render a live web page to PDF
PdfDocument webPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
webPdf.saveAs(Paths.get("ironpdf-homepage.pdf"));
HTTP認証に保護されたページには、ChromePdfRenderOptions を通して認証情報を渡します:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/url-to-pdf-auth.java
// Configure render options with login credentials
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setAuthUsername("username");
renderOptions.setAuthPassword("password");
// Render authenticated page to PDF
PdfDocument securedPdf = PdfDocument.renderUrlAsPdf("https://your-internal-app.com/report", renderOptions);
securedPdf.saveAs(Paths.get("internal-report.pdf"));
URLからPDFへのコード例をご覧ください。 クッキーやフォームベースの認証を使用した複雑なログインフローの詳細については、ウェブサイトのログイン処理をご確認ください。
ページサイズ、向き、余白をコントロールする方法は?
出力PDFの物理レイアウトをカスタマイズするには、ChromePdfRenderOptions を使用します。 設定済みのオプションを任意のレンダーメソッドの第2引数として渡します。 最も一般的な設定は、ページの向き、紙のサイズ、および余白です:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/pdf-formatting.java
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
// Set landscape orientation (default is portrait)
renderOptions.setPaperOrientation(PaperOrientation.LANDSCAPE);
// Use US Letter paper size (default is A4)
renderOptions.setPaperSize(PaperSize.LETTER);
// Set margins in millimeters (top, right, bottom, left)
renderOptions.setMarginTop(15);
renderOptions.setMarginRight(15);
renderOptions.setMarginBottom(15);
renderOptions.setMarginLeft(15);
// Include background colors and images
renderOptions.setPrintHtmlBackgrounds(true);
// Apply options when rendering
PdfDocument report = PdfDocument.renderHtmlAsPdf("<h1>Quarterly Report</h1>", renderOptions);
report.saveAs(Paths.get("report.pdf"));
ChromePdfRenderOptions は上記の設定に加えて DPI、JavaScript 実行タイムアウト、ズームファクター、CSS メディアタイプを含む30以上の設定を公開しています。 完全なリストについては PDF 生成設定 を参照してください。PaperSize enum にないカスタム用紙サイズについては、カスタムPDF用紙サイズを参照してください。
JavaでPDFにパスワード保護を追加する方法は?
SecurityOptions は読み取りおよび所有者のパスワードとアクセス権限フラグを制御します。 ドキュメントのSecurityManagerに SecurityOptions を保存前に渡します:
:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/password-protect-basic.java
// Create security settings with a user-facing password
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setUserPassword("shareable");
// Apply security to the document
PdfDocument urlPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
SecurityManager securityManager = urlPdf.getSecurity();
securityManager.setSecurityOptions(securityOptions);
// Save the password-protected document
urlPdf.saveAs(Paths.get("protected.pdf"));
より厳密に制御するためには、オーナーパスワードを設定し、特定の操作を制限します:
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/password-protect-advanced.java
SecurityOptions advancedSecurity = new SecurityOptions();
// User password: required to open the file
advancedSecurity.setUserPassword("user-open-pass");
// Owner password: required to change security settings
advancedSecurity.setOwnerPassword("owner-admin-pass");
// Restrict editing operations
advancedSecurity.setAllowPrint(false);
advancedSecurity.setAllowCopy(false);
advancedSecurity.setAllowEditContent(false);
advancedSecurity.setAllowEditAnnotations(false);
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/password-protect-advanced.java
SecurityOptions advancedSecurity = new SecurityOptions();
// User password: required to open the file
advancedSecurity.setUserPassword("user-open-pass");
// Owner password: required to change security settings
advancedSecurity.setOwnerPassword("owner-admin-pass");
// Restrict editing operations
advancedSecurity.setAllowPrint(false);
advancedSecurity.setAllowCopy(false);
advancedSecurity.setAllowEditContent(false);
advancedSecurity.setAllowEditAnnotations(false);
PDFを開くとき、リーダーはパスワードを要求します:
正しいパスワードを入力すると、PDFが開き、すべてのコンテンツが表示されます:
セキュリティとメタデータ設定で権限フラグの完全なリストをご覧ください。
Spring BootアプリケーションでPDFを生成する方法は?
IronPDFはSpring Bootと直接統合します。 どのコントローラーメソッドからでもバイト配列のHTTPレスポンスとしてPDFを返します; このパターンは、オンデマンドのレポート生成、請求書のダウンロード、データのエクスポートに適しています。
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/spring-boot-controller.java
import com.ironsoftware.ironpdf.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
@RequestMapping("/api/pdf")
public class PdfController {
@GetMapping("/invoice/{id}")
public ResponseEntity<byte[]> generateInvoice(@PathVariable String id) throws IOException {
// Build HTML dynamically using the invoice ID
String html = """
<html><body>
<h1>Invoice #%s</h1>
<p>Amount due: $500.00</p>
</body></html>
""".formatted(id);
// Render and return as PDF download
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);
byte[] pdfBytes = pdf.getBinaryData();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("attachment", "invoice-" + id + ".pdf");
return ResponseEntity.ok().headers(headers).body(pdfBytes);
}
}
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/spring-boot-controller.java
import com.ironsoftware.ironpdf.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
@RequestMapping("/api/pdf")
public class PdfController {
@GetMapping("/invoice/{id}")
public ResponseEntity<byte[]> generateInvoice(@PathVariable String id) throws IOException {
// Build HTML dynamically using the invoice ID
String html = """
<html><body>
<h1>Invoice #%s</h1>
<p>Amount due: $500.00</p>
</body></html>
""".formatted(id);
// Render and return as PDF download
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html);
byte[] pdfBytes = pdf.getBinaryData();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("attachment", "invoice-" + id + ".pdf");
return ResponseEntity.ok().headers(headers).body(pdfBytes);
}
}
getBinaryData() メソッドは PDF をバイト配列として返し、Spring Boot はこれをクライアントに直接ストリームします。 一時ファイルはディスクに書き込まれません。 高スループットのデプロイのためには、License.setLicenseKey() を@PostConstruct メソッドやアプリケーションの起動リスナー内でインスタンス化する方が、リクエストごとにインスタンス化するよりも優れています。
Java PDF作成の次のステップは?
このガイドでは、IronPDFを使用したJavaにおけるPDF生成の4つのアプローチ、HTML文字列レンダリング、ローカルファイル変換、URLキャプチャ、およびSpring BootのHTTPレスポンスストリーミングを示しました。 すべてのメソッドは同じ PdfDocument API、ChromePdfRenderOptions をフォーマット制御用に、SecurityOptions をアクセス保護用に共有しています。
IronPDF for Javaは、ウォーターマークの追加とスタンプ、複数のPDFファイルの結合、PDFを個々のページに分割する、デジタル署名の追加、JavaScriptチャートをPDFとしてレンダリングする、およびプログラム的にPDFを印刷することをサポートします。
無料トライアルを開始することでウォーターマークなしでPDFを生成するか、ライセンスオプションを表示してプロジェクトに合ったプランを選択することができます。 より深く探求する準備ができましたか? IronPDF for Javaのチュートリアルページをチェックしてください。
よくある質問
JavaでHTML文字列からPDFを作成するにはどうすればよいですか?
HTML文字列をPdfDocument.renderHtmlAsPdf()に渡します。このメソッドはメモリ内にPdfDocumentオブジェクトを返します。ディスクに書き込むには、pdf.saveAs(Paths.get("output.pdf"))を呼び出してください。IronPDFは完全なHTML5、CSS3、およびJavaScriptをサポートしています。
IronPDFが必要とするJavaバージョンは何ですか?
IronPDF for JavaはJDK 8以上を必要とします。JDK 11 LTSが本番環境でのデプロイのために推奨される最小です。
MavenプロジェクトにIronPDFを追加するにはどうすればよいですか?
pom.xmlの<dependencies>セクション内にgroupId com.ironsoftwareとartifactId ironpdfを持つ依存関係ブロックを追加し、それからmvn installを実行します。
JavaでローカルHTMLファイルからPDFを作成する方法は?
PdfDocument.renderHtmlFileAsPdf()をHTMLファイルのパスと共に呼び出してください。IronPDFは、ファイルのディレクトリに関連するCSS、画像、JavaScriptを自動で解決します。
JavaでURLからPDFを作成できますか?
はい。ターゲットURLを指定してPdfDocument.renderUrlAsPdf()を呼び出してください。IronPDFはChromiumを使用してページを取得し、PdfDocumentを返します。HTTP認証が必要なページの場合は、ChromePdfRenderOptionsを使って認証情報を渡してください。
JavaでIronPDFを使用してPDFにパスワードを設定する方法は?
SecurityOptionsオブジェクトを作成し、パスワードと共にsetUserPassword()を呼び出し、saveAs()を呼び出す前に、オプションをurlPdf.getSecurity().setSecurityOptions()に渡してください。
Spring BootアプリケーションでIronPDFを使用する方法は?
PDF生成ロジックを@RestControllerメソッドに注入してください。PdfDocument.renderHtmlAsPdf()を呼び出し、pdf.getBinaryData()を使用してバイト配列を取得し、MediaType.APPLICATION_PDFと共にResponseEntity<byte[]>として返してください。
JavaでIronPDFのページサイズと向きを設定する方法は?
ChromePdfRenderOptionsオブジェクトを作成し、setPaperSize()とsetPaperOrientation()を呼び出し、任意のレンダリングメソッドの2番目の引数として渡してください。用紙の向きを設定する前にサイズを設定して、順序の衝突を避けてください。
IronPDFはLinuxとmacOSでJava版を利用できますか?
はい。IronPDF for JavaはWindows、Linux、およびmacOSで動作します。また、AWS、Azure、Google Cloud上でのクラウドデプロイメントにも対応しており、外部のPDFビューアーやレンダリングエンジンは必要ありません。
ライセンスキーなしでは、PDFにウォーターマークが付きますか?
はい。有効なライセンスキーがない場合、IronPDFは生成されたすべてのドキュメントにトライアルウォーターマークを追加します。アプリケーション起動時にLicense.setLicenseKey()を呼び出し、有効なキーを設定して削除してください。




