跳過到頁腳內容
使用 IRONPDF FOR JAVA

如何在 Java 中寫入 PDF 文件

本文將探討使用 IronPDF 以程式化方式創建 PDF 文件。

IronPDF for Java PDF Library

IronPDF 的 Java PDF 庫 允許開發人員在其 Java 應用中創建、編輯和處理 PDF 文件。 需要從應用程序數據中創建 PDF 文件的 Java 開發人員,會發現這個庫是一個很好的選擇,因為它提供了多樣化的功能。

IronPDF comes with features such as adding new HTML content, embedding HTML headers and footers, stamping and watermarking documents, creating password-protected PDF files, applying digital signatures to PDF files, enhancing documents with backgrounds and foregrounds, creating a full PDF file from XML documents, adding and editing annotations, and using outlines and bookmarks for better navigation. 讓我們更仔細地看看。

新增 HTML 內容

使用 IronPDF,開發人員可以輕鬆地在其 PDF 文件中新增 HTML 內容。 對於希望動態生成富 HTML 內容的 PDF 表單文檔的開發人員來說,這是一個很棒的功能。 該庫支持許多 HTML 元素,包括圖片、鏈接和表格等。 HTML 內容還可以使用 CSS 進行樣式設計,這使得創建具有專業外觀的 PDF 更加容易。

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

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

// Set a log path
Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

// Render the HTML as a PDF. Stored in myPdf as type PdfDocument.
PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("<h1>Hello World</h1> Made with IronPDF!");

// Save the PdfDocument to a file
myPdf.saveAs(Paths.get("html_saved.pdf"));
import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;

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

// Set a log path
Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

// Render the HTML as a PDF. Stored in myPdf as type PdfDocument.
PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("<h1>Hello World</h1> Made with IronPDF!");

// Save the PdfDocument to a file
myPdf.saveAs(Paths.get("html_saved.pdf"));
JAVA

如何在 Java 中寫入 PDF 文件,圖 1:輸出 PDF 輸出PDF

新增 HTML 頁眉和頁腳

頁眉和頁腳是許多 PDF 文件的重要組成部分,IronPDF 使得在您的文檔中輕鬆整合 HTML 頁眉和頁腳。 使用 IronPDF,開發人員可以在其 PDF 文件中添加自訂頁眉和頁腳,包括文字、圖片和頁碼。 此功能特別對於需要在其文件中添加品牌或版權信息的公司非常有用。

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

// Render a PDF from a URL
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

// Build a footer using HTML
HtmlHeaderFooter footer = new HtmlHeaderFooter();
footer.setMaxHeight(15); // millimeters
footer.setHtmlFragment("<center><i>{page} of {total-pages}</i></center>");
footer.setDrawDividerLine(true);
pdf.addHtmlFooter(footer);
List<PdfDocument> pdfs = new ArrayList<>();

// Build a header using an image asset
HtmlHeaderFooter header = new HtmlHeaderFooter();
header.setMaxHeight(20); // millimeters
header.setHtmlFragment("<img src=\"logo.png\" />");
header.setBaseUrl("./assets/");
pdf.addHtmlHeader(header);

try {
    pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
} catch (IOException e) {
    throw new RuntimeException(e);
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HtmlHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
import java.util.ArrayList;

// Render a PDF from a URL
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

// Build a footer using HTML
HtmlHeaderFooter footer = new HtmlHeaderFooter();
footer.setMaxHeight(15); // millimeters
footer.setHtmlFragment("<center><i>{page} of {total-pages}</i></center>");
footer.setDrawDividerLine(true);
pdf.addHtmlFooter(footer);
List<PdfDocument> pdfs = new ArrayList<>();

// Build a header using an image asset
HtmlHeaderFooter header = new HtmlHeaderFooter();
header.setMaxHeight(20); // millimeters
header.setHtmlFragment("<img src=\"logo.png\" />");
header.setBaseUrl("./assets/");
pdf.addHtmlHeader(header);

try {
    pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
} catch (IOException e) {
    throw new RuntimeException(e);
}
JAVA

如何在 Java 中寫入 PDF 文件,圖 2:輸出 PDF 輸出PDF

加印和浮水印

使用 IronPDF,開發人員可以在其 PDF 文件中添加加印和浮水印。 浮水印是顯示在文檔背景中的透明圖片或文字,而加印則在新文件中添加自訂消息或圖片。

這些功能對於需要保護其文件不被未授權使用或在其文件中添加自訂消息的公司來說非常優異。

package IronPDF.ironpdf_java;

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

public class Test {
    public static void main(String[] args) throws IOException {
        License.setLicenseKey("Your-License");

        // Load an existing PDF from the filesystem
        PdfDocument pdf = PdfDocument.fromFile(Paths.get("C:\\byteToPdf.pdf"));

        // Apply a watermark to the PDF
        pdf.applyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, VerticalAlignment.TOP, HorizontalAlignment.CENTER);

        // Save the watermarked PDF
        pdf.saveAs(Paths.get("assets/watermark.pdf"));
    }
}
package IronPDF.ironpdf_java;

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

public class Test {
    public static void main(String[] args) throws IOException {
        License.setLicenseKey("Your-License");

        // Load an existing PDF from the filesystem
        PdfDocument pdf = PdfDocument.fromFile(Paths.get("C:\\byteToPdf.pdf"));

        // Apply a watermark to the PDF
        pdf.applyWatermark("<h2 style='color:red'>SAMPLE</h2>", 30, VerticalAlignment.TOP, HorizontalAlignment.CENTER);

        // Save the watermarked PDF
        pdf.saveAs(Paths.get("assets/watermark.pdf"));
    }
}
JAVA

如何在 Java 中寫入 PDF 文件,圖 3:輸出 PDF 輸出PDF

背景和前景

IronPDF 也允許開發人員在其 PDF 文件中實現自訂背景和前景。 前景被用於在文件上方添加自訂文字或圖片,而背景則在背景中添加自訂圖片或顏色。 想要其文件或 PDF 表單具有自訂品牌或圖像的企業主,將會發現這一功能特別有用。

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

public class BackgroundForegroundExample {

    public static void main(String[] args) throws IOException {
        // Load background and foreground PDFs from the filesystem
        PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));
        PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));

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

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

        // Save the document with background and foreground
        pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
    }
}
import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;

public class BackgroundForegroundExample {

    public static void main(String[] args) throws IOException {
        // Load background and foreground PDFs from the filesystem
        PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));
        PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));

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

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

        // Save the document with background and foreground
        pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
    }
}
JAVA

添加和編輯註解

註解是一種在 PDF 文件中添加附加信息的好方法,例如筆記、評論或高亮標示。 使用 IronPDF,開發人員可以輕鬆地效地管理註解,通過添加和編輯它們來提升其 PDF 文件。

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

public class AnnotationExample {

    public static void main(String[] args) throws IOException {
        // Load an existing PDF from the file system
        PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));

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

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

        // Save the PDF with the modifications
        pdf.saveAs(Paths.get("assets/annotated.pdf"));
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.annotation.AnnotationIcon;
import com.ironsoftware.ironpdf.annotation.AnnotationManager;
import com.ironsoftware.ironpdf.annotation.AnnotationOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class AnnotationExample {

    public static void main(String[] args) throws IOException {
        // Load an existing PDF from the file system
        PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));

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

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

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

如何在 Java 中寫入 PDF 文件,圖 4:輸出文件 輸出文件

大綱和書籤

開發人員可以使用書籤增強 PDF 文件與 IronPDF。 大綱提供了對文檔內容的高層次概述,而書籤則提供對特定部分的快速訪問。 對於大型或複雜的文件,此功能使用戶能夠快速導航至所需的章節。

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

public class BookmarkExample {

    public static void main(String[] args) throws IOException {
        // Load an existing PDF from the file system
        PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/book.pdf"));

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

        List<Bookmark> bookmarkList = bookmarks.getBookmarks();
        Bookmark bookmark = bookmarkList.get(2);

        // Add a child bookmark
        bookmark.addChildBookmark("Conclusion", 11);

        // Save the PDF to the filesystem
        pdf.saveAs(Paths.get("assets/bookmarked.pdf"));
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.Bookmark;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

public class BookmarkExample {

    public static void main(String[] args) throws IOException {
        // Load an existing PDF from the file system
        PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/book.pdf"));

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

        List<Bookmark> bookmarkList = bookmarks.getBookmarks();
        Bookmark bookmark = bookmarkList.get(2);

        // Add a child bookmark
        bookmark.addChildBookmark("Conclusion", 11);

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

總結

這篇文章探討了 IronPDF 的各種功能,例如添加註解、書籤、HTML 內容、背景和前景色、頁眉和頁腳到 PDF 文件的能力。 文章提供了使用 IronPDF 實現這些功能的分步指導,使開發人員能夠輕鬆創建滿足其特定需求的專業外觀的 PDF 文件。

無論您是在構建 Web 應用還是桌面應用,IronPDF 都可以幫助您簡化生成 PDF 文件的過程,為節省時間和精力,同時確保您的文件擁有出色的外觀。

IronPDF 授權信息從 $799 開始。 IronPDF 也提供免費試用,讓開發人員在做出購買決定前,測試庫並評估其能力。 在試用期間,使用者可以獲取所有庫的功能,包括支持和更新。 試用期結束後,使用者可以選擇購買授權以繼續使用該庫。 IronPDF 的定價會根據使用該庫的開發者數量和授權類型的不同而有所差異。

常見問題解答

我如何在 Java 中以編程方式創建 PDF 文檔?

您可以使用 IronPDF for Java 以編程方式創建 PDF 文檔。該庫提供廣泛的功能來生成高質量的 PDF,包括支持 HTML 內容、頁眉、頁腳等。

有哪些方法可將 HTML 內容添加到 PDF?

IronPDF 允許開發人員使用 RenderHtmlAsPdf 方法直接將 HTML 內容添加到 PDF 中。此方法支持各種 HTML 元素和 CSS 樣式。

我可以在我的 PDF 文檔中包括數字簽名嗎?

是的,IronPDF 支持在 PDF 文檔中添加數字簽名,以確保文件的真實性和安全性。

如何使用密碼保護我的 PDF 文檔?

IronPDF 提供創建帶密碼保護的 PDF 的功能,允許您在文件中保護敏感信息。

是否可以向 PDF 添加自定義背景和前景?

IronPDF 使開發人員能夠向 PDF 添加自定義背景和前景,可以包括品牌元素或裝飾性圖形。

大綱和書籤如何提高 PDF 中的文件導航?

IronPDF 允許添加大綱和書籤,幫助用戶快速導航到 PDF 的特定部分,並提供文檔結構的有序概述。

有什麼選項可以用來對 PDF 文檔進行註釋?

使用 IronPDF,您可以添加各種註釋,如備註、評論和高亮,以增強 PDF 文檔的互動性和可用性。

在 Java 應用中使用 IronPDF 的許可選項是什麼?

IronPDF 提供多種許可選項,包括用於評估目的的免費試用。許可證根據開發人員人數和項目的具體需求而有所不同。

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。