Jak zapisać plik PDF w Java
This article will explore IronPDF for creating PDF documents programmatically.
IronPDF for Java PDF Library
The Java PDF Library by IronPDF allows developers to create, edit, and manipulate PDF documents in their Java applications. Java developers who need to create PDF files from their applications' data will find this library to be an excellent choice because it offers a diverse set of functionalities.
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. Let's take a closer look.
Add New HTML Content
With IronPDF, developers can easily add new HTML content to their PDF documents. This is a great feature for developers who want to dynamically generate their PDF form documents with rich HTML content. The library supports many HTML elements, including images, links, and tables, among others. HTML content can also be styled using CSS, making it easy to create professional-looking PDFs.
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"));
Wynik w formacie PDF
Add HTML Headers and Footers
Headers and footers are essential components of many PDF documents, and IronPDF makes it easy to integrate HTML headers and footers into your documents. With IronPDF, developers can add custom headers and footers, including text, images, and page numbers, to their PDF documents. This feature is particularly useful for businesses that need to add branding or copyright information to their documents.
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);
}
Wynik w formacie PDF
Stamp & Watermark
Using IronPDF, developers can add stamps and watermarks to their PDF documents. Watermarks are transparent images or text that appear in the document's background, while stamps add a custom message or image to a new document.
These features are great for businesses that need to protect their documents from unauthorized use or to add a custom message to their documents.
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"));
}
}
Wynik w formacie PDF
Backgrounds & Foregrounds
IronPDF also allows developers to implement custom backgrounds and foregrounds in their PDF documents. Foregrounds are used to add custom text or images on top of a document, while backgrounds add a custom image or color to the background. Business owners who want their documents or PDF forms to have custom branding or graphics will find this feature particularly useful.
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"));
}
}
Add & Edit Annotations
Annotations are a great way to add additional information to PDF documents, such as notes, comments, or highlights. With IronPDF, developers can easily manage annotations effectively by adding and editing them in their PDF documents.
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"));
}
}
Output File
Outlines & Bookmarks
Developers can enhance PDF documents using bookmarks with IronPDF. Spis treści zapewnia ogólny przegląd zawartości dokumentu, a zakładki umożliwiają szybki dostęp do konkretnych sekcji. W przypadku dużych lub złożonych dokumentów funkcja ta pozwala użytkownikom szybko przejść do wybranych sekcji.
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"));
}
}
Podsumowanie
W tym artykule omówiono różne funkcje IronPDF, takie jak możliwość dodawania adnotacji, zakładek, treści HTML, kolorów tła i pierwszego planu oraz nagłówków i stopek do dokumentów PDF. Artykuł zawiera szczegółowe instrukcje dotyczące wdrażania tych funkcji przy użyciu IronPDF, ułatwiając programistom tworzenie profesjonalnie wyglądających dokumentów PDF, które spełniają ich konkretne potrzeby.
Niezależnie od tego, czy tworzysz aplikację internetową, czy aplikację desktopową, IronPDF pomoże Ci usprawnić proces generowania dokumentów PDF, oszczędzając czas i wysiłek, a jednocześnie zapewniając doskonały wygląd dokumentów.
The IronPDF licensing information starts from $799. IronPDF oferuje również bezpłatną wersję próbną, umożliwiającą programistom przetestowanie biblioteki i ocenę jej możliwości przed podjęciem decyzji o zakupie. W okresie próbnym użytkownicy mają dostęp do wszystkich funkcji biblioteki, w tym do wsparcia technicznego i aktualizacji. Po okresie próbnym użytkownicy mogą zdecydować się na zakup licencji, aby nadal korzystać z biblioteki. Ceny IronPDF różnią się w zależności od liczby programistów korzystających z biblioteki oraz rodzaju licencji.
Często Zadawane Pytania
How can I create PDF documents programmatically in Java?
You can use IronPDF for Java to programmatically create PDF documents. The library offers a wide range of features to generate high-quality PDFs, including support for HTML content, headers, footers, and more.
What methods are available for adding HTML content to a PDF?
IronPDF allows developers to use the RenderHtmlAsPdf method to add HTML content directly into a PDF. This method supports various HTML elements and CSS for styling.
Can I include digital signatures in my PDF documents?
Yes, IronPDF supports adding digital signatures to PDF documents, ensuring document authenticity and security.
How can I protect my PDF documents with passwords?
IronPDF provides functionality to create password-protected PDFs, allowing you to secure sensitive information within your documents.
Is it possible to add custom backgrounds and foregrounds to PDFs?
IronPDF enables developers to add custom backgrounds and foregrounds to PDFs, which can include branding elements or decorative graphics.
How can outlines and bookmarks improve document navigation in PDFs?
IronPDF allows the addition of outlines and bookmarks, which help users quickly navigate to specific sections of a PDF and provide an organized overview of the document structure.
What options are available for annotating PDF documents?
With IronPDF, you can add various annotations such as notes, comments, and highlights, enhancing the interactivity and usability of your PDF documents.
What are the licensing options for using IronPDF in Java applications?
IronPDF oferuje kilka opcji licencyjnych, w tym bezpłatną wersję próbną do celów ewaluacyjnych. Licencje różnią się w zależności od liczby programistów i konkretnych potrzeb projektu.





