JavaでHTMLからPDFへ
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チュートリアルで入手可能です。
クイックスタート: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");
今日あなたのプロジェクトでIronPDFを無料トライアルで使用開始。
目次
- JavaプロジェクトにIronPDFをインストールする方法
- HTML文字列をJavaでPDFに変換する方法
- HTML文字列でローカルアセットを読み込む方法
- JavaでURLをPDFに変換する方法
- JavaでHTMLファイルをPDFに変換する方法
- PDF出力設定をカスタマイズする方法
- PDFにヘッダーとフッターを追加する方法
- カスタムマージンとページサイズを設定する方法
- PDFに透かしを追加する方法
- JavaでPDFからテキストを抽出する方法
- JavaでPDFから画像を抽出する方法
- PDFファイルを圧縮する方法
- プログラムでPDFを印刷する方法
- 次のステップ
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>
最初のアーティファクトは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.*;
ライセンスキーを設定する
ライセンスキーがない場合、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");
アプリケーションを起動する際、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"));
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");
このメソッドは 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");
基本パス引数は、絶対ファイルシステムパスとURL文字列の両方で機能します。 これにより、renderHtmlAsPdfは、ディスク上に保存されている、またはWebサーバーから提供されるテンプレートからPDFを生成するのに適しています。
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");
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");
このアプローチは、テンプレート化されたドキュメント生成に効果的に機能します。例えば、請求書テンプレート、レポート、または関連するCSSおよび画像アセットと共に保存された証明書などです。 IronPDFは、すべてのCSSのレイアウトルールを保持し、ブラウザと同じ精度でファイルをレンダリングします。
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");
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");
{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");
サポートされている用紙サイズと単位の完全なリストについては、カスタム用紙サイズコード例およびカスタムマージンコード例を参照してください。
どうすれば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");
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);
テキスト抽出は、テキストが選択可能なグリフとして保存されている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).");
他の抽出オプションについては、特定のページから画像を抽出することを含め、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");
画像圧縮は、写真や高解像度のグラフィックを含むPDFのサイズを削減するための最も効果的な方法です。 埋め込まれたフォントの除去など、その他のファイルサイズ削減戦略については、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);
true を print メソッドに渡すと、システムの印刷ダイアログが表示され、ユーザーはジョブを送信する前にプリンターを選択したり、印刷設定を構成したりすることができます。
次のステップ
このチュートリアルでは、IronPDF for JavaのHTMLからPDFへの変換の中核メソッドとインストール、構成、一般的なドキュメント処理操作について説明しました。
さらに詳しく知りたい場合は:
- ここではカバーされていない追加のレンダリングシナリオについて、完全なHTMLからPDF for Javaコード例を参照してください。
- IronPDF for Javaのドキュメントを読んで、デプロイメント、スレッドセーフティ、サーバー構成を理解してください。
- IronPDF Java APIリファレンス全体を探索して、詳細なメソッドシグネチャおよびパラメーターの説明を確認してください。
無料トライアルを開始して,透かしなしのPDFを生成するか,プロジェクトに適したプランを見つけるためにライセンスオプションを表示します。
チュートリアル クイックアクセス
このチュートリアルをJavaソースコードとしてダウンロードする
このチュートリアルの完全なHTMLからPDFへ for Javaソースコードは、zipped IntelliJプロジェクトとしてダウンロードできます。
ダウンロードこのチュートリアルをGitHubで探索
このプロジェクトのソースコードは、IntelliJ IDEAプロジェクトとしてGitHubにあり、EclipseやNetBeansを含む他の一般的なJava IDEにインポートすることができます。
GitHub上 for Java HTML to PDF/AAPIリファレンスを見る
すべてのネームスペース、クラス、メソッド、およびライブラリで利用可能な列挙型をカバーするIronPDF Java APIリファレンスを探索してください。
APIリファレンスを見るよくある質問
IronPDF for Javaは何に使われるのですか?
IronPDF for Javaは、Javaアプリケーション内でHTMLコンテンツをPDFドキュメントに変換します。HTML文字列、ローカルHTMLファイル、ライブウェブページURLの変換をサポートし、ヘッダーやフッターの追加、透かし、水印、テキスト抽出、画像抽出、ファイル圧縮のツールも提供します。
JavaプロジェクトにIronPDFをインストールするにはどうすればよいですか?
pom.xmlに二つのMaven依存関係を追加します:com.ironsoftware:ironpdfとorg.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にとってファイルサイズと画像の忠実度の良好なバランスを提供します。





