JavaでPDFファイルを作成する方法 Copy for LLMsCopy for LLMs Copy page as Markdown for LLMs
# JavaでPDFファイルを作成する方法
JavaでのPDFファイル作成は、ビジネスアプリケーションにおける一般的な要件です:請求書やレポートのオンデマンド生成、証明書、領収書、監査ログの作成。 IronPDF for Javaは、完全なChromiumレンダリングエンジンを使用してHTMLをPDFに変換します。つまり、HTML5、CSS3、およびJavaScriptコンテンツは、書式の損失なく忠実にレンダリングされます。
このガイドでは、HTML文字列から、ローカルHTMLファイルから、ライブURLからの3つのPDF作成方法をカバーしています。 それはページ形式の設定、パスワード保護、およびSpring Bootの統合もカバーします。
*as-heading:2(クイックスタート: JavaでHTMLからPDFを作成する)*
1. IronPDF を `pom.xml` に追加します:
```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>
```
2. ライブラリをインポートしてPDFを作成します:
```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"));
```
<div class="hsg-featured-snippet">
<h3>JavaでPDFファイルを作成する方法</h3>
<ol>
<li><a class="js-modal-open" data-modal-id="download-modal" href="#download-modal">MavenまたはGradleを通じてIronPDF Javaライブラリをインストールする</a></li>
<li><code>com.ironsoftware.ironpdf.*</code>をインポートし、ライセンスキーを設定します</li>
<li>PDFをメモリ内で作成するには、HTML文字列を用いて<code>PdfDocument.renderHtmlAsPdf()</code>を呼び出します</li>
<li>ローカルHTMLファイルをPDFに変換するには<code>PdfDocument.renderHtmlFileAsPdf()</code>を使用します</li>
<li>完成した文書をディスクに書き込むには<code>pdf.saveAs()</code>を呼び出します</li>
</ol>
</div>
## 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](https://ironpdf.com/java/get-started/aws/)、[Azure](https://ironpdf.com/java/get-started/azure/)、[Google Cloud](https://ironpdf.com/java/get-started/google-cloud/)でのサーバーデプロイメントもサポートします。
[[i:(IronPDFは内部でChromiumを使用してレンダリングします。 Chrome内で正しく見えるのと同じHTMLは、PDFでも同じ出力を生成し、ブラウザからPDFへのフォーマットの驚きはありません。)]]
## JavaでIronPDFを使用するための前提条件は何ですか?
### 必要なJavaバージョンとビルドツールは何ですか?
IronPDF for Javaは**JDK 8以降**を必要とします。 推奨される最小は、製品動作用にJDK 11 (LTS)です。 <a href="https://www.oracle.com/java/technologies/javase-downloads.html" target="_blank" rel="nofollow noopener noreferrer">Oracleダウンロードページ</a>からJDKをダウンロードするか、<a href="https://adoptium.net/" target="_blank" rel="nofollow noopener noreferrer">Eclipse Temurin</a>などのOpenJDKディストリビューションを使用します。
**Maven** (3.6+)と**Gradle** (7.0+)の両方がサポートされています。 Mavenは、エンタープライズJavaプロジェクトのより一般的な選択です。
### MavenプロジェクトにIronPDFを追加する方法は?
プロジェクトの `pom.xml` を開き、次の依存関係を `<dependencies>` ブロック内に追加します:
```xml
//: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` ファイルに追加してください。
```groovy
//: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` を実行します。 <a href="https://central.sonatype.com/artifact/com.ironsoftware/ironpdf" target="_blank" rel="nofollow noopener noreferrer">Maven Central</a>で最新の公開バージョンを確認してください。
### 必要なインポートと構成は何ですか?
以下のインポートステートメントをJavaソースファイルの先頭に追加します:
```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` メソッドまたはアプリケーションの起動時にライセンスキーを設定してください:
```java
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/license-setup.java
License.setLicenseKey("Your-License-Key");
```
**注意:** 有効なライセンスキーがないと、PDFにはトライアルウォーターマークが生成されます。 [ライセンスを購入する](/java/licensing/)か、[無料トライアルを開始する](#trial-license)ことでこれを削除します。 [Javaでライセンスキーを使用する](https://ironpdf.com/java/get-started/license-keys/)を参照して、追加の構成オプションをご確認ください。
## JavaでHTML文字列からPDFを作成する方法は?
任意の HTML 文字列を直接 `PdfDocument.renderHtmlAsPdf()` に渡します。 IronPDF は、メモリ上で完成したドキュメントを表す `PdfDocument` インスタンスを返します。 それを書き込むには `saveAs()` を呼び出します。
```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テンプレートを使用しています:
```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へのチュートリアル](https://ironpdf.com/java/tutorials/html-to-pdf/)をご確認ください。
[[t:(短いHTML文字列を渡すと、IronPDFはコンテンツを最小限のHTMLドキュメントに自動的にラップします。 ヘッドタグ、メタチャセット、CSSリセットを完全に制御するには、完全な`<!DOCTYPE html>`ドキュメントを渡します。)]]
## JavaでローカルHTMLファイルからPDFを作成する方法は?
ローカルファイルシステムに保存された HTML ファイルを変換するために `PdfDocument.renderHtmlFileAsPdf()` を使用します。 パスを文字列として渡します; 相対パスは現在の作業ディレクトリに対して解決します:
```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への例](https://ironpdf.com/java/examples/file-to-pdf/)で完全な作業デモを参照してください。
## JavaでウェブページのURLからPDFを作成する方法は?
`PdfDocument.renderUrlAsPdf()` はライブURLを取得し、それを Chromium を使ってレンダリングしてPDFを返します。 これはダッシュボードのスナップショットをキャプチャしたり、ホストされたレシートページから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` を通して認証情報を渡します:
```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へのコード例](https://ironpdf.com/java/examples/converting-a-url-to-a-pdf/)をご覧ください。 クッキーやフォームベースの認証を使用した複雑なログインフローの詳細については、[ウェブサイトのログイン処理](https://ironpdf.com/java/examples/ironpdf-website-and-system-logins/)をご確認ください。
## ページサイズ、向き、余白をコントロールする方法は?
出力PDFの物理レイアウトをカスタマイズするには、`ChromePdfRenderOptions` を使用します。 設定済みのオプションを任意のレンダーメソッドの第2引数として渡します。 最も一般的な設定は、ページの向き、紙のサイズ、および余白です:
```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 生成設定](https://ironpdf.com/java/examples/pdf-generation-settings/) を参照してください。`PaperSize` enum にないカスタム用紙サイズについては、[カスタムPDF用紙サイズ](https://ironpdf.com/java/examples/custom-pdf-paper-size/)を参照してください。
[[n:(常にPaperSizeをPaperOrientationの前に設定してください。 オリエンテーションを先に設定すると、PaperSizeが適用されたときにいくつかのビルドで上書きされる可能性があります。 推奨される順序は、サイズ、次にオリエンテーション、次に余白です。)]]
## JavaでPDFにパスワード保護を追加する方法は?
`SecurityOptions` は読み取りおよび所有者のパスワードとアクセス権限フラグを制御します。 ドキュメントの`SecurityManager`に `SecurityOptions` を保存前に渡します:
```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"));
```
より厳密に制御するためには、オーナーパスワードを設定し、特定の操作を制限します:
```java
//: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を開くとき、リーダーはパスワードを要求します:
<div class="content-img-align-center">
<div class="center-image-wrapper">
<a rel="nofollow" href="/static-assets/ironpdf-java/howto/java-create-pdf/java-create-pdf-1.webp" target="_blank"><img src="/static-assets/ironpdf-java/howto/java-create-pdf/java-create-pdf-1.webp" alt="ユーザーパスワードが設定された IronPDF 生成の Java PDF を開いたときに表示されるパスワード入力ダイアログ" class="img-responsive add-shadow" /></a>
<p class="content__image-caption">PDFリーダーは、文書がユーザーパスワードで保護されている場合、パスワードプロンプトを表示します。</p>
</div>
</div>
正しいパスワードを入力すると、PDFが開き、すべてのコンテンツが表示されます:
<div class="content-img-align-center">
<div class="center-image-wrapper">
<a rel="nofollow" href="/static-assets/ironpdf-java/howto/java-create-pdf/java-create-pdf-2.webp" target="_blank"><img src="/static-assets/ironpdf-java/howto/java-create-pdf/java-create-pdf-2.webp" alt="正しいパスワードを入力した後に PDF ビューアで開かれた IronPDF Java の PDF ドキュメント。ドキュメントの全内容が表示されている" class="img-responsive add-shadow" /></a>
<p class="content__image-caption">正しいパスワードが提供されると、文書は正常にレンダリングされます。</p>
</div>
</div>
[セキュリティとメタデータ設定](https://ironpdf.com/java/examples/security-and-metadata/)で権限フラグの完全なリストをご覧ください。
## Spring BootアプリケーションでPDFを生成する方法は?
IronPDFはSpring Bootと直接統合します。 どのコントローラーメソッドからでもバイト配列のHTTPレスポンスとしてPDFを返します; このパターンは、オンデマンドのレポート生成、請求書のダウンロード、データのエクスポートに適しています。
```java
//: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` メソッドやアプリケーションの起動リスナー内でインスタンス化する方が、リクエストごとにインスタンス化するよりも優れています。
[[t:(ライセンスキーをアプリケーション起動時に一度設定し、@PostConstructメソッドまたはApplicationRunnerを使用します。 毎回リクエストでLicense.setLicenseKey()を呼び出すことは不要なオーバーヘッドを追加します。)]]
## Java PDF作成の次のステップは?
このガイドでは、IronPDFを使用したJavaにおけるPDF生成の4つのアプローチ、HTML文字列レンダリング、ローカルファイル変換、URLキャプチャ、およびSpring BootのHTTPレスポンスストリーミングを示しました。 すべてのメソッドは同じ `PdfDocument` API、`ChromePdfRenderOptions` をフォーマット制御用に、`SecurityOptions` をアクセス保護用に共有しています。
IronPDF for Javaは、[ウォーターマークの追加とスタンプ](https://ironpdf.com/java/how-to/custom-watermark/)、[複数のPDFファイルの結合](https://ironpdf.com/java/how-to/java-merge-pdf-tutorial/)、[PDFを個々のページに分割する](https://ironpdf.com/java/examples/split-pdfs/)、[デジタル署名の追加](https://ironpdf.com/java/examples/pdf-signatures/)、[JavaScriptチャートをPDFとしてレンダリングする](https://ironpdf.com/java/examples/js-charts-to-pdf/)、および[プログラム的にPDFを印刷する](https://ironpdf.com/java/how-to/java-print-pdf-tutorial/)ことをサポートします。
[無料トライアルを開始する](#trial-license)ことでウォーターマークなしでPDFを生成するか、[ライセンスオプションを表示してプロジェクトに合ったプランを選択する](#licensing)ことができます。 より深く探求する準備ができましたか? [IronPDF for Javaのチュートリアルページ](https://ironpdf.com/java/tutorials/html-to-pdf/)をチェックしてください。
Ask ChatGPT about this page
Ask Gemini about this page
Ask Perplexity about this page
JavaでのPDFファイル作成は、ビジネスアプリケーションにおける一般的な要件です:請求書やレポートのオンデマンド生成、証明書、領収書、監査ログの作成。 IronPDF for Javaは、完全なChromiumレンダリングエンジンを使用してHTMLをPDFに変換します。つまり、HTML5、CSS3、およびJavaScriptコンテンツは、書式の損失なく忠実にレンダリングされます。
このガイドでは、HTML文字列から、ローカルHTMLファイルから、ライブURLからの3つのPDF作成方法をカバーしています。 それはページ形式の設定、パスワード保護、およびSpring Bootの統合もカバーします。
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>
XML
ライブラリをインポートしてPDFを作成します:
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" ));
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
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 でのサーバーデプロイメントもサポートします。
IronPDFは内部でChromiumを使用してレンダリングします。 Chrome内で正しく見えるのと同じHTMLは、PDFでも同じ出力を生成し、ブラウザからPDFへのフォーマットの驚きはありません。
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>
XML
保存後に 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'
//:path=/static-assets/pdf/content-code-examples/how-to/java-create-pdf-tutorial/gradle-dependency.gradle
implementation 'com.ironsoftware:ironpdf:2024.9.1'
Text
ライブラリを取得するために gradle build を実行します。 Maven Central で最新の公開バージョンを確認してください。
必要なインポートと構成は何ですか?
以下のインポートステートメントを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 ;
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;
Java
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");
Java
注意: 有効なライセンスキーがないと、PDFにはトライアルウォーターマークが生成されます。 ライセンスを購入する か、無料トライアルを開始する ことでこれを削除します。 Javaでライセンスキーを使用する を参照して、追加の構成オプションをご確認ください。
JavaでHTML文字列からPDFを作成する方法は?
任意の HTML 文字列を直接 PdfDocument.renderHtmlAsPdf() に渡します。 IronPDF は、メモリ上で完成したドキュメントを表す PdfDocument インスタンスを返します。 それを書き込むには saveAs() を呼び出します。
// 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" ));
// 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"));
Java
renderHtmlAsPdf() はフル HTML5 および CSS3 仕様をサポートしており、Web フォント、Flexbox、グリッドレイアウト、JavaScript 実行を含みます。 以下の例はカスタムスタイルを持つ複数行のHTMLテンプレートを使用しています:
// 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" ));
// 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
上記の請求書例はJava 13以降で利用可能なJavaテキストブロックを使用して、よりクリーンな複数行のHTMLを提供します。 古い Java バージョンの場合、renderHtmlFileAsPdf() を使用して HTML 文字列を手動で連結するかファイルから読み込みます。 JavaScriptレンダリングを含むHTMLからPDFへの変換全般を見るには、Java向けHTMLからPDFへのチュートリアル をご確認ください。
短いHTML文字列を渡すと、IronPDFはコンテンツを最小限のHTMLドキュメントに自動的にラップします。 ヘッドタグ、メタチャセット、CSSリセットを完全に制御するには、完全な<!DOCTYPE html>ドキュメントを渡します。
JavaでローカルHTMLファイルからPDFを作成する方法は?
ローカルファイルシステムに保存された HTML ファイルを変換するために PdfDocument.renderHtmlFileAsPdf() を使用します。 パスを文字列として渡します; 相対パスは現在の作業ディレクトリに対して解決します:
// 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" ));
// 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"));
Java
IronPDFは、参照されたすべてのアセット(外部CSSファイル、ローカル画像、JavaScriptライブラリ)をHTMLファイルのディレクトリに対して相対的に解決します。 これにより、リンクされたスタイルシートと一緒に完全なHTMLテンプレートを構築し、資産パスを変更することなくIronPDFを通じて実行できます。
メソッドは String パスと java.nio.file.Path オブジェクトの両方を受け入れます。 作業ディレクトリの曖昧さを避けるため、本番使用では絶対パスを使用することをお勧めします。 HTMLファイルからPDFへの例 で完全な作業デモを参照してください。
JavaでウェブページのURLからPDFを作成する方法は?
PdfDocument.renderUrlAsPdf() はライブURLを取得し、それを Chromium を使ってレンダリングしてPDFを返します。 これはダッシュボードのスナップショットをキャプチャしたり、ホストされたレシートページからPDFレシートを生成したり、ウェブコンテンツをアーカイブしたりするのに便利です:
// Render a live web page to PDF
PdfDocument webPdf = PdfDocument .renderUrlAsPdf( "https://ironpdf.com" );
webPdf.saveAs( Paths .get( "ironpdf-homepage.pdf" ));
// Render a live web page to PDF
PdfDocument webPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
webPdf.saveAs(Paths.get("ironpdf-homepage.pdf"));
Java
HTTP認証に保護されたページには、ChromePdfRenderOptions を通して認証情報を渡します:
// 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" ));
// 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"));
Java
URLからPDFへのコード例 をご覧ください。 クッキーやフォームベースの認証を使用した複雑なログインフローの詳細については、ウェブサイトのログイン処理 をご確認ください。
ページサイズ、向き、余白をコントロールする方法は?
出力PDFの物理レイアウトをカスタマイズするには、ChromePdfRenderOptions を使用します。 設定済みのオプションを任意のレンダーメソッドの第2引数として渡します。 最も一般的な設定は、ページの向き、紙のサイズ、および余白です:
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 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"));
Java
ChromePdfRenderOptions は上記の設定に加えて DPI、JavaScript 実行タイムアウト、ズームファクター、CSS メディアタイプを含む30以上の設定を公開しています。 完全なリストについては PDF 生成設定 を参照してください。PaperSize enum にないカスタム用紙サイズについては、カスタムPDF用紙サイズ を参照してください。
常にPaperSizeをPaperOrientationの前に設定してください。 オリエンテーションを先に設定すると、PaperSizeが適用されたときにいくつかのビルドで上書きされる可能性があります。 推奨される順序は、サイズ、次にオリエンテーション、次に余白です。
JavaでPDFにパスワード保護を追加する方法は?
SecurityOptions は読み取りおよび所有者のパスワードとアクセス権限フラグを制御します。 ドキュメントのSecurityManagerに SecurityOptions を保存前に渡します:
// 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" ));
// 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"));
Java
より厳密に制御するためには、オーナーパスワードを設定し、特定の操作を制限します:
//: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);
Java
PDFを開くとき、リーダーはパスワードを要求します:
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);
}
}
Java
getBinaryData() メソッドは PDF をバイト配列として返し、Spring Boot はこれをクライアントに直接ストリームします。 一時ファイルはディスクに書き込まれません。 高スループットのデプロイのためには、License.setLicenseKey() を@PostConstruct メソッドやアプリケーションの起動リスナー内でインスタンス化する方が、リクエストごとにインスタンス化するよりも優れています。
ライセンスキーをアプリケーション起動時に一度設定し、@PostConstructメソッドまたはApplicationRunnerを使用します。 毎回リクエストでLicense.setLicenseKey()を呼び出すことは不要なオーバーヘッドを追加します。
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のチュートリアルページ をチェックしてください。
よくある質問 HTML文字列をPdfDocument.renderHtmlAsPdf()に渡します。このメソッドはメモリ内にPdfDocumentオブジェクトを返します。ディスクに書き込むには、pdf.saveAs(Paths.get("output.pdf"))を呼び出してください。IronPDFは完全なHTML5、CSS3、およびJavaScriptをサポートしています。
IronPDF for JavaはJDK 8以上を必要とします。JDK 11 LTSが本番環境でのデプロイのために推奨される最小です。
pom.xmlの<dependencies>セクション内にgroupId com.ironsoftwareとartifactId ironpdfを持つ依存関係ブロックを追加し、それからmvn installを実行します。
PdfDocument.renderHtmlFileAsPdf()をHTMLファイルのパスと共に呼び出してください。IronPDFは、ファイルのディレクトリに関連するCSS、画像、JavaScriptを自動で解決します。
はい。ターゲットURLを指定してPdfDocument.renderUrlAsPdf()を呼び出してください。IronPDFはChromiumを使用してページを取得し、PdfDocumentを返します。HTTP認証が必要なページの場合は、ChromePdfRenderOptionsを使って認証情報を渡してください。
SecurityOptionsオブジェクトを作成し、パスワードと共にsetUserPassword()を呼び出し、saveAs()を呼び出す前に、オプションをurlPdf.getSecurity().setSecurityOptions()に渡してください。
PDF生成ロジックを@RestControllerメソッドに注入してください。PdfDocument.renderHtmlAsPdf()を呼び出し、pdf.getBinaryData()を使用してバイト配列を取得し、MediaType.APPLICATION_PDFと共にResponseEntity<byte[]>として返してください。
ChromePdfRenderOptionsオブジェクトを作成し、setPaperSize()とsetPaperOrientation()を呼び出し、任意のレンダリングメソッドの2番目の引数として渡してください。用紙の向きを設定する前にサイズを設定して、順序の衝突を避けてください。
はい。IronPDF for JavaはWindows、Linux、およびmacOSで動作します。また、AWS、Azure、Google Cloud上でのクラウドデプロイメントにも対応しており、外部のPDFビューアーやレンダリングエンジンは必要ありません。
はい。有効なライセンスキーがない場合、IronPDFは生成されたすべてのドキュメントにトライアルウォーターマークを追加します。アプリケーション起動時にLicense.setLicenseKey()を呼び出し、有効なキーを設定して削除してください。
テクニカルライター
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。
...
詳しく読む