JavaでHTMLからPDFへ

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

IronPDF for Javaは、現代のブラウザに見られるのと同じレンダリングエンジンを使用して、ピクセル完璧なPDFドキュメントにHTMLコンテンツを変換します。 Javaアプリケーションは、追加のレンダリングソフトウェアやGUI環境を必要とせずに、HTML文字列、ローカルのHTMLファイル、またはライブのウェブページからPDFを生成できます。

このチュートリアルは、IronPDF for Javaで利用可能な3つのHTMLからPDFへの変換方法に加えて、インストール、ライセンス、および構成オプションをカバーしています。 すでにIronPDF for .NETを使用している開発者は、Java APIに馴染みがあります; 同等 for .NETチュートリアルは、HTMLからPDFへ for .NETチュートリアルで入手可能です。

ご注意IronPDF for JavaはJava 8以降を必要とし、Spring Boot、Java EE、Micronautなど主要なJVMベースのフレームワークと互換性があります。

クイックスタート:HTMLからPDFを生成する

次の例は、HTML文字列から1ページのPDFを作成し、それをディスクに保存します。 Maven(ステップ1)を使用してライブラリをインストールした後、必要なすべてのコードはこちらです:

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/quickstart-html-string.java
import com.ironsoftware.ironpdf.*;

// Apply your license key before any rendering call
License.setLicenseKey("YOUR-LICENSE-KEY");

// Render an HTML string to a PDF file
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1><p>Generated in Java.</p>");
pdf.saveAs("output.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/quickstart-html-string.java
import com.ironsoftware.ironpdf.*;

// Apply your license key before any rendering call
License.setLicenseKey("YOUR-LICENSE-KEY");

// Render an HTML string to a PDF file
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1><p>Generated in Java.</p>");
pdf.saveAs("output.pdf");
JAVA

今日あなたのプロジェクトでIronPDFを無料トライアルで使用開始。

最初のステップ:
green arrow pointer

目次


JavaプロジェクトにIronPDFをインストールする方法

IronPDF for JavaはMaven Centralリポジトリで利用可能です。 推奨されるインストール方法はMavenですが、ビルドシステムを使用しないプロジェクト用にはJARの手動インストールもサポートされています。

Maven依存関係としてインストール

プロジェクトの pom.xml ファイルの dependencies セクションに、以下のアーティファクトを追加してください:

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/maven-dependency.xml
<dependency>
  <groupId>com.ironsoftware</groupId>
  <artifactId>ironpdf</artifactId>
  <version>2024.9.1</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>2.0.5</version>
</dependency>
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/maven-dependency.xml
<dependency>
  <groupId>com.ironsoftware</groupId>
  <artifactId>ironpdf</artifactId>
  <version>2024.9.1</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>2.0.5</version>
</dependency>
XML

最初のアーティファクトはIronPDFを取り込みます。 The second is an SLF4J logging implementation. IronPDFはレンダリング中に診断メッセージを放出するためにSLF4Jを使用します; you can substitute it with Logback or Log4j 2, or omit logging entirely.

プロジェクトのルートディレクトリで mvn install を実行して、依存関係をダウンロードしてください。 バージョン番号を指定する前に、IronPDFの最新バージョンを確認してください。変更履歴にはすべての現在および過去のリリースがリストされています。

JARを手動でインストール

Mavenを使用しない開発者は、Maven Centralから直接IronPDFファットJARをダウンロードし、プロジェクトのクラスパスに追加できます。 ファットJARはすべての移動関連依存関係をバンドルします。

{t:(新しいプロジェクトにはMavenが推奨されるアプローチです。 JARインストールは手動での依存関係管理を必要とし、大規模プロジェクトではバージョンの競合を引き起こす可能性があります。)}

IronPDFパッケージをインポートする

すべてのPDFレンダリングおよび操作クラスは、com.ironsoftware.ironpdfパッケージ内に存在します。 IronPDFを使用する任意 for Javaソースファイルにこのインポート文を追加してください:

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/import-package.java
import com.ironsoftware.ironpdf.*;
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/import-package.java
import com.ironsoftware.ironpdf.*;
JAVA

ライセンスキーを設定する

ライセンスキーがない場合、IronPDFは各ページにタイル透かしの付いたPDFをレンダリングします。 透かしを削除するには、レンダリングメソッドを呼び出す前に、有効なライセンスキーを License.setLicenseKey に渡してください:

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/set-license-key.java
import com.ironsoftware.ironpdf.*;

// Set the license key before any rendering call
License.setLicenseKey("YOUR-LICENSE-KEY");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/set-license-key.java
import com.ironsoftware.ironpdf.*;

// Set the license key before any rendering call
License.setLicenseKey("YOUR-LICENSE-KEY");
JAVA

アプリケーションを起動する際、PDF生成ロジックが実行される前にこの呼び出しを配置してください。 無料トライアルを始めてトライアルキーを取得するか、ライセンスオプションを参照して商用利用する。

ログファイルパスを設定する

IronPDFは、アプリケーションの作業ディレクトリにあるIronPdfEngine.logという名前のログファイルに、レンダリングの診断情報を書き込みます。 ファイル名または保存場所を変更するには、Settings.setLogPath を呼び出してください:

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/set-log-path.java
import com.ironsoftware.ironpdf.*;
import java.nio.file.Paths;

// Configure logging before calling any rendering methods
Settings.setLogPath(Paths.get("logs/ironpdf.log"));
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/set-log-path.java
import com.ironsoftware.ironpdf.*;
import java.nio.file.Paths;

// Configure logging before calling any rendering methods
Settings.setLogPath(Paths.get("logs/ironpdf.log"));
JAVA

重要PDFの変換や操作を行う前に、Settings.setLogPathを呼び出してください。 レンダリングが開始された後の呼び出しは効果がありません。)}

JavaでHTML文字列をPDFに変換する方法

PdfDocument.renderHtmlAsPdf は、HTML 文字列を PdfDocument オブジェクトに変換します。このオブジェクトは、ディスクに保存したり、他の処理メソッドに渡したりすることができます。 このメソッドは、<body>要素を含むページ全体のマークアップを含め、W3C準拠のHTMLをすべて受け付けます。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/html-string-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Convert a simple HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
// Save the resulting PDF to a file
pdf.saveAs("htmlstring_to_pdf.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/html-string-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Convert a simple HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
// Save the resulting PDF to a file
pdf.saveAs("htmlstring_to_pdf.pdf");
JAVA
PDF output showing a rendered H1 heading generated from an HTML string using PdfDocument.renderHtmlAsPdf

PdfDocument.renderHtmlAsPdfメソッドは、HTMLマークアップをPDFにレンダリングし、すべてのW3C準拠のスタイリングや構造を保持します。

このメソッドは PdfDocument インスタンスを返します。 saveAs を呼び出して PDF をディスクに書き込むか、getBinaryData を使用して、ストリーミングや保存用の生の PDF バイト列を取得します。

renderHtmlAsPdf は、標準に準拠したブラウザと同様に、すべての HTML、CSS、および JavaScript コンテンツを処理します。 結果として得られるPDFは、Chromeで閲覧した際のページの見た目を正確に反映します。

このメソッドの詳細については、IronPDF Java例のページHTML文字列をPDFに変換するコード例を参照してください。

HTML文字列でローカルアセットを読み込む方法

HTML は、相対パスで外部アセット(スタイルシート、画像、スクリプト)を参照することがよくあります。 renderHtmlAsPdf は、これらの参照を解決するためのベースパスを設定するオプションの 2 番目の引数を受け付けます。 基本パスは、ローカルディレクトリまたは URL を指すことができます。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/html-string-local-assets.java
import com.ironsoftware.ironpdf.*;

// HTML with references to local stylesheets and images
String html = "<html>"
    + "<head>"
    +   "<title>Invoice</title>"
    +   "<link rel='stylesheet' type='text/css' href='style.css'>"
    + "</head>"
    + "<body>"
    +   "<div class='content'>"
    +     "<h1>Invoice #1001</h1>"
    +     "<img src='logo.png' alt='Company Logo'/>"
    +   "</div>"
    + "</body>"
    + "</html>";

// The second argument resolves relative asset paths
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html, "C:/invoices/");
pdf.saveAs("invoice.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/html-string-local-assets.java
import com.ironsoftware.ironpdf.*;

// HTML with references to local stylesheets and images
String html = "<html>"
    + "<head>"
    +   "<title>Invoice</title>"
    +   "<link rel='stylesheet' type='text/css' href='style.css'>"
    + "</head>"
    + "<body>"
    +   "<div class='content'>"
    +     "<h1>Invoice #1001</h1>"
    +     "<img src='logo.png' alt='Company Logo'/>"
    +   "</div>"
    + "</body>"
    + "</html>";

// The second argument resolves relative asset paths
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(html, "C:/invoices/");
pdf.saveAs("invoice.pdf");
JAVA
PDF output displaying an invoice with styled layout, logo image, and CSS formatting applied from local assets

基本パスが指定されている場合、renderHtmlAsPdf は、そのディレクトリから相対アセット参照を解決し、完全にスタイリングされたPDFを生成します。

基本パス引数は、絶対ファイルシステムパスとURL文字列の両方で機能します。 これにより、renderHtmlAsPdfは、ディスク上に保存されている、またはWebサーバーから提供されるテンプレートからPDFを生成するのに適しています。

ヒントWindows スタイルのバックスラッシュ (C:\invoices\) を使用するパスは、クロスプラットフォームの互換性を確保するため、スラッシュに変換するか、Paths.get() を使用してください。

どうすればJavaでURLをPDFに変換できますか?

PdfDocument.renderUrlAsPdf は、指定された URL のライブ Web ページを取得し、それを PDF としてレンダリングします。 このメソッドは、レンダリング前にすべての外部CSS、JavaScript、および画像を含む完全なページをロードします。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/url-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Render a live web page as a PDF document
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
pdf.saveAs("url_to_pdf.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/url-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Render a live web page as a PDF document
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
pdf.saveAs("url_to_pdf.pdf");
JAVA
PDF output of the Wikipedia article on PDF format, showing the page layout and content rendered by PdfDocument.renderUrlAsPdf

PdfDocument.renderUrlAsPdf メソッドは、ウェブページの完全なレンダリング状態をキャプチャし、JavaScriptでレンダリングされたコンテンツを含みます。

renderUrlAsPdf は、レンダリングされたページのキャプチャを行う前に JavaScript の実行が完了するのを待ちます。つまり、動的に生成されたコンテンツ(チャートや AJAX 経由で読み込まれたデータなど)が出力 PDF に反映されます。

.NETの同等の実装や追加のURLからPDFへのオプションについては、URLをPDFに変換するコード例を参照してください。

どうすればJavaでHTMLファイルをPDFに変換できますか?

PdfDocument.renderHtmlFileAsPdf は、ローカルの HTML ファイルを読み込み、PDF としてレンダリングします。 HTMLファイルで参照されるすべての相対パス(スタイルシート、画像、スクリプト)は、HTMLファイルのディレクトリを基準に解決されます。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/html-file-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Convert a local HTML file to PDF
// IronPDF resolves relative asset paths from the HTML file's directory
PdfDocument pdf = PdfDocument.renderHtmlFileAsPdf("C:/invoices/TestInvoice1.html");
pdf.saveAs("htmlfile_to_pdf.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/html-file-to-pdf.java
import com.ironsoftware.ironpdf.*;

// Convert a local HTML file to PDF
// IronPDF resolves relative asset paths from the HTML file's directory
PdfDocument pdf = PdfDocument.renderHtmlFileAsPdf("C:/invoices/TestInvoice1.html");
pdf.saveAs("htmlfile_to_pdf.pdf");
JAVA

このアプローチは、テンプレート化されたドキュメント生成に効果的に機能します。例えば、請求書テンプレート、レポート、または関連するCSSおよび画像アセットと共に保存された証明書などです。 IronPDFは、すべてのCSSのレイアウトルールを保持し、ブラウザと同じ精度でファイルをレンダリングします。

ご注意HTMLファイルパスは絶対でなければなりません。 renderHtmlFileAsPdf に渡される相対パスは JVM の作業ディレクトリを基準に解決されるため、サーバー環境では予期しない結果が生じる可能性があります。)]

PDF出力設定をカスタマイズするにはどうすればよいですか?

PdfRenderOptions クラスは、ページのレイアウトとレンダリング動作を制御します。 PdfRenderOptions インスタンスを作成し、必要なプロパティを設定して、いずれかのレンダリングメソッドに渡します。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/render-options.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;

// Configure rendering options before generating the PDF
PdfRenderOptions options = new PdfRenderOptions();
// Set the zoom level (100 = normal size)
options.setZoom(100);
// Wait for JavaScript to finish before rendering
options.setJavaScriptTimeout(5000);
// Enable printing of background colors and images
options.setPrintBackground(true);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf(
    "<h1>Customized PDF</h1>",
    options
);
pdf.saveAs("customized.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/render-options.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;

// Configure rendering options before generating the PDF
PdfRenderOptions options = new PdfRenderOptions();
// Set the zoom level (100 = normal size)
options.setZoom(100);
// Wait for JavaScript to finish before rendering
options.setJavaScriptTimeout(5000);
// Enable printing of background colors and images
options.setPrintBackground(true);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf(
    "<h1>Customized PDF</h1>",
    options
);
pdf.saveAs("customized.pdf");
JAVA

PdfRenderOptions クラスは、DPI、ビューポートの幅、用紙の向き、およびタイムアウト値を制御するための追加のプロパティを提供します。 利用可能なオプションの完全なリストについては、PDF生成設定コード例を参照してください。

どうすればPDFにヘッダーとフッターを追加できますか?

IronPDFは、テキストベースおよびHTMLベースの両方のヘッダーとフッターをサポートしています。 テキストヘッダーは、ページ番号やドキュメントタイトルなどの共通値のための事前定義されたマージフィールドを使用します; HTMLヘッダーは、完全にカスタマイズされたレイアウトのための任意のHTMLマークアップを受け入れます。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/headers-footers.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.headerfooter.*;

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Annual Report</h1><p>Content goes here.</p>");

// Create a text-based header using merge fields
TextHeaderFooter header = new TextHeaderFooter();
header.setCenterText("Annual Report");
header.setRightText("{page} of {total-pages}");
header.setFont(com.ironsoftware.ironpdf.font.FontTypes.Helvetica);
header.setFontSize(10.0);

// Create a text-based footer
TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("Confidential");
footer.setRightText("Generated by IronPDF");

pdf.addTextHeaders(header);
pdf.addTextFooters(footer);

pdf.saveAs("report_with_headers.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/headers-footers.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.headerfooter.*;

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Annual Report</h1><p>Content goes here.</p>");

// Create a text-based header using merge fields
TextHeaderFooter header = new TextHeaderFooter();
header.setCenterText("Annual Report");
header.setRightText("{page} of {total-pages}");
header.setFont(com.ironsoftware.ironpdf.font.FontTypes.Helvetica);
header.setFontSize(10.0);

// Create a text-based footer
TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("Confidential");
footer.setRightText("Generated by IronPDF");

pdf.addTextHeaders(header);
pdf.addTextFooters(footer);

pdf.saveAs("report_with_headers.pdf");
JAVA

{page} および {total-pages} のマージフィールドは、レンダリング時に現在のページ番号と総ページ数に置き換えられます。 会社ロゴを含むフッターなど、より高度なレイアウトについては、TextHeaderFooter の代わりに HtmlHeaderFooter を使用してください。

HTMLベースのヘッダーとフッターの詳細については、ヘッダーとフッターを追加するコード例を参照してください。

ヒントヘッダーとフッターはページ余白内にレンダリングされます。 ページコンテンツと重ならないようにヘッダーまたはフッターを適用する前に、上部または下部マージンを増やしてください。

カスタムマージンとページサイズを設定するにはどうすればよいですか?

ページサイズと余白は、PDFがレンダリングされる前に PdfRenderOptions オブジェクトで設定されます。 IronPDFは標準的な用紙サイズ(A4、レター、リーガル)および完全にカスタムな寸法をサポートします。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/margins-page-size.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;
import com.ironsoftware.ironpdf.page.*;

PdfRenderOptions options = new PdfRenderOptions();
// Set margins in millimeters: top, right, bottom, left
options.setMarginTop(25);
options.setMarginRight(20);
options.setMarginBottom(25);
options.setMarginLeft(20);
// Use A4 paper size
options.setPaperSize(PaperSize.A4);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Formatted Document</h1>", options);
pdf.saveAs("formatted_document.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/margins-page-size.java
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;
import com.ironsoftware.ironpdf.page.*;

PdfRenderOptions options = new PdfRenderOptions();
// Set margins in millimeters: top, right, bottom, left
options.setMarginTop(25);
options.setMarginRight(20);
options.setMarginBottom(25);
options.setMarginLeft(20);
// Use A4 paper size
options.setPaperSize(PaperSize.A4);

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Formatted Document</h1>", options);
pdf.saveAs("formatted_document.pdf");
JAVA

サポートされている用紙サイズと単位の完全なリストについては、カスタム用紙サイズコード例およびカスタムマージンコード例を参照してください。

どうすればPDFに透かしを追加できますか?

PdfDocument.applyWatermark は、ドキュメント内のすべてのページにテキストまたは画像の透かしを適用します。 透かしは、デフォルトではページコンテンツの下にある別のレイヤーに表示されますが、falseに設定されている場合は、ページコンテンツの上に表示されます。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/add-watermark.java
import com.ironsoftware.ironpdf.*;

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Confidential Document</h1>");

// Apply an HTML watermark; supports full CSS styling
String watermarkHtml = "<h1 style='color: rgba(200, 0, 0, 0.2); transform: rotate(-45deg); font-size: 60px;'>DRAFT</h1>";
// Second argument: opacity (0-100), third: rotation (degrees), fourth: stamp behind content
pdf.applyWatermark(watermarkHtml, 50, 45, true);

pdf.saveAs("draft_watermarked.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/add-watermark.java
import com.ironsoftware.ironpdf.*;

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Confidential Document</h1>");

// Apply an HTML watermark; supports full CSS styling
String watermarkHtml = "<h1 style='color: rgba(200, 0, 0, 0.2); transform: rotate(-45deg); font-size: 60px;'>DRAFT</h1>";
// Second argument: opacity (0-100), third: rotation (degrees), fourth: stamp behind content
pdf.applyWatermark(watermarkHtml, 50, 45, true);

pdf.saveAs("draft_watermarked.pdf");
JAVA

HTMLアプローチは、フォント、サイズ、色、透明度を含む透かしのスタイリングを正確に制御することができます。 繰り返しタイルパターンや画像ベースのスタンプなどの高度な透かし設定については、透かしのハウツーガイドを参照してください。

どうすればJavaでPDFからテキストを抽出できますか?

PdfDocument.extractAllText は、PDF に埋め込まれたテキストコンテンツを読み取り、それを単一の String として返します。 この方法は、ドキュメントのすべてのページから選択可能なテキストを抽出します。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/extract-text.java
import com.ironsoftware.ironpdf.*;

// Load an existing PDF from disk
PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("report.pdf"));

// Extract all embedded text from the document
String text = pdf.extractAllText();
System.out.println(text);
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/extract-text.java
import com.ironsoftware.ironpdf.*;

// Load an existing PDF from disk
PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("report.pdf"));

// Extract all embedded text from the document
String text = pdf.extractAllText();
System.out.println(text);
JAVA

テキスト抽出は、テキストが選択可能なグリフとして保存されているPDFで機能します。画像ベースのスキャンであるPDFの場合、IronPDFをOCRライブラリと組み合わせてレンダリングされたページ画像からテキストを抽出することを検討してください。

他のオプションについては、ページごとのテキスト抽出を含め、PDFからテキストを抽出するコード例を参照してください。

どうすればJavaでPDFから画像を抽出できますか?

PdfDocument.extractAllImages は、PDF に埋め込まれた画像ごとに 1 つずつ、BufferedImage オブジェクトのリストを返します。 返された画像は、直接ディスクに保存するか、下流の画像処理ロジックに渡すことができます。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/extract-images.java
import com.ironsoftware.ironpdf.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import javax.imageio.ImageIO;

// Load an existing PDF
PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("document.pdf"));

// Extract all embedded images
List<BufferedImage> images = pdf.extractAllImages();
for (int i = 0; i < images.size(); i++) {
    ImageIO.write(images.get(i), "PNG", new File("extracted_image_" + i + ".png"));
}
System.out.println("Extracted " + images.size() + " image(s).");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/extract-images.java
import com.ironsoftware.ironpdf.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import javax.imageio.ImageIO;

// Load an existing PDF
PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("document.pdf"));

// Extract all embedded images
List<BufferedImage> images = pdf.extractAllImages();
for (int i = 0; i < images.size(); i++) {
    ImageIO.write(images.get(i), "PNG", new File("extracted_image_" + i + ".png"));
}
System.out.println("Extracted " + images.size() + " image(s).");
JAVA

他の抽出オプションについては、特定のページから画像を抽出することを含め、PDFから画像を抽出するコード例を参照してください。

どうすればPDFファイルを圧縮できますか?

PdfDocument.compressImages は、埋め込まれた画像を低画質で再エンコードすることで、PDFファイルのサイズを縮小します。 この方法は、1(最小品質、最小ファイルサイズ)から100(最大品質)までの品質値を受け入れます。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/compress-pdf.java
import com.ironsoftware.ironpdf.*;

// Load a large PDF with embedded images
PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("large_report.pdf"));

// Compress images to 60% quality to reduce file size
pdf.compressImages(60);

pdf.saveAs("large_report_compressed.pdf");
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/compress-pdf.java
import com.ironsoftware.ironpdf.*;

// Load a large PDF with embedded images
PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("large_report.pdf"));

// Compress images to 60% quality to reduce file size
pdf.compressImages(60);

pdf.saveAs("large_report_compressed.pdf");
JAVA

画像圧縮は、写真や高解像度のグラフィックを含むPDFのサイズを削減するための最も効果的な方法です。 埋め込まれたフォントの除去など、その他のファイルサイズ削減戦略については、PDF圧縮コード例を参照してください。

ヒント 40から70の間の品質値は、ほとんどのPDFユースケースでファイルサイズ削減と画質のバランスをうまく保ちます。

どうすればPDFをプログラム的に印刷できますか?

PdfDocument.print は、標準の Java 印刷 API を使用して、PDF をシステムのデフォルトプリンターに送信します。 この方法は、印刷ダイアログを表示するかどうかを制御するブール値を受け入れます。

//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/print-pdf.java
import com.ironsoftware.ironpdf.*;

PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("document.pdf"));

// Print silently to the default printer (no dialog shown)
pdf.print(false);
//:path=/static-assets/pdf/content-code-examples/tutorials/generate-pdfs/print-pdf.java
import com.ironsoftware.ironpdf.*;

PdfDocument pdf = PdfDocument.fromFile(java.nio.file.Paths.get("document.pdf"));

// Print silently to the default printer (no dialog shown)
pdf.print(false);
JAVA

trueprint メソッドに渡すと、システムの印刷ダイアログが表示され、ユーザーはジョブを送信する前にプリンターを選択したり、印刷設定を構成したりすることができます。

次のステップ

このチュートリアルでは、IronPDF for JavaのHTMLからPDFへの変換の中核メソッドとインストール、構成、一般的なドキュメント処理操作について説明しました。

さらに詳しく知りたい場合は:

  1. ここではカバーされていない追加のレンダリングシナリオについて、完全なHTMLからPDF for Javaコード例を参照してください。
  2. IronPDF for Javaのドキュメントを読んで、デプロイメント、スレッドセーフティ、サーバー構成を理解してください。
  3. IronPDF Java APIリファレンス全体を探索して、詳細なメソッドシグネチャおよびパラメーターの説明を確認してください。

無料トライアルを開始して,透かしなしのPDFを生成するか,プロジェクトに適したプランを見つけるためにライセンスオプションを表示します。


チュートリアル クイックアクセス

Java開発用のIntelliJ IDEA IDEロゴ

このチュートリアルをJavaソースコードとしてダウンロードする

このチュートリアルの完全なHTMLからPDFへ for Javaソースコードは、zipped IntelliJプロジェクトとしてダウンロードできます。

ダウンロード

このチュートリアルをGitHubで探索

このプロジェクトのソースコードは、IntelliJ IDEAプロジェクトとしてGitHubにあり、EclipseやNetBeansを含む他の一般的なJava IDEにインポートすることができます。

GitHub上 for Java HTML to PDF/A
ソースコードリポジトリのGitHubロゴ
IronPDF Java APIリファレンスドキュメントアイコン

APIリファレンスを見る

すべてのネームスペース、クラス、メソッド、およびライブラリで利用可能な列挙型をカバーするIronPDF Java APIリファレンスを探索してください。

APIリファレンスを見る

よくある質問

IronPDF for Javaは何に使われるのですか?

IronPDF for Javaは、Javaアプリケーション内でHTMLコンテンツをPDFドキュメントに変換します。HTML文字列、ローカルHTMLファイル、ライブウェブページURLの変換をサポートし、ヘッダーやフッターの追加、透かし、水印、テキスト抽出、画像抽出、ファイル圧縮のツールも提供します。

JavaプロジェクトにIronPDFをインストールするにはどうすればよいですか?

pom.xmlに二つのMaven依存関係を追加します:com.ironsoftware:ironpdforg.slf4j:slf4j-simple、そしてmvn installを実行します。あるいは、Maven Centralからfat JARをダウンロードし、プロジェクトのクラスパスに追加します。

JavaでHTML文字列をPDFに変換するにはどうすればよいですか?

PdfDocument.renderHtmlAsPdf(htmlString)をHTMLマークアップで呼び出します。このメソッドはPdfDocumentオブジェクトを返します。pdf.saveAs("output.pdf")を呼び出してディスクに書き込みます。

JavaでURLをPDFに変換するにはどうすればよいですか?

PdfDocument.renderUrlAsPdf("https://example.com")を呼び出します。IronPDFがページを取得し、JavaScriptが実行されるのを待ってから、完全に読み込まれたページをPDFとしてレンダリングします。

JavaでローカルHTMLファイルをPDFに変換するにはどうすればよいですか?

PdfDocument.renderHtmlFileAsPdf("C:/path/to/file.html")を呼び出します。絶対ファイルパスを使用します。IronPDFはHTMLファイルのディレクトリから相対CSSと画像参照を自動的に解決します。

IronPDF for Javaは生成されたPDFに透かしを追加しますか?

ライセンスキーがなければ、IronPDFはすべての生成されたPDFにタイル状の透かしを追加します。レンダリング呼び出しの前に、有効なライセンスキーをLicense.setLicenseKey("YOUR-KEY")で設定して透かしを削除します。

IronPDFが必要とするJavaバージョンは何ですか?

IronPDF for JavaはJava 8以上が必要です。Spring Boot、Java EE、Micronaut、その他のJVMベースのフレームワークと互換性があります。

JavaでIronPDFを使用してPDFにページ番号を追加するにはどうすればよいですか?

TextHeaderFooterインスタンスを作成し、setRightText("{page} of {total-pages}")を呼び出します。オブジェクトをpdf.addTextFooters(footer)に渡します。マージフィールドはレンダリング時に実際のページ番号に置き換えられます。

IronPDF for JavaはPDFからテキストを抽出できますか?

はい。PdfDocument.fromFile(Paths.get("file.pdf"))でPDFをロードし、pdf.extractAllText()を呼び出してすべての選択可能なテキストコンテンツをStringとして取得します。

JavaでPDFのファイルサイズを縮小するにはどうすればよいですか?

品質が1から100までの整数であるpdf.compressImages(quality)を呼び出します。60の値は、ほとんどのPDFにとってファイルサイズと画像の忠実度の良好なバランスを提供します。

Darrius Serrant
フルスタックソフトウェアエンジニア(WebOps)

Darrius Serrantは、マイアミ大学でコンピュータサイエンスの学士号を取得し、Iron SoftwareでフルスタックWebOpsマーケティングエンジニアとして働いています。若い頃からコーディングに惹かれ、コンピューティングを神秘的かつアクセス可能なものとし、創造性と問題解決のための完璧な媒体と考えていました。

Iron Softwareでは、新しいものを創造することと、複雑なコンセプトをより理解しやすくすることを楽しんでいます。Resident Developerの一人として、次世代に専門知識を共有するために、学生を教えることにも志願しました。

Darriusにとって、その仕事は価値があり、実際の影響があるため、満足感があります。

準備はできましたか?
バージョン: 2026.5 just released
Still Scrolling Icon

まだスクロールしていますか?

すぐに証拠が欲しいですか?
サンプルを実行するHTML が PDF に変換されるのを確認します。