Jak tworzyć pliki PDF w Java
Tworzenie plików PDF w Java jest proste przy użyciu biblioteki IronPDF, która konwertuje HTML do PDF za pomocą metod takich jak renderHtmlAsPdf() dla ciągów HTML, renderHtmlFileAsPdf() dla plików HTML oraz renderUrlAsPdf() dla stron internetowych.
Szybki Start: Utwórz swój pierwszy plik PDF w Java
-
Dodaj zależność IronPDF do swojego pliku pom.xml:
<dependency> <groupId>com.ironsoftware</groupId> <artifactId>ironpdf</artifactId> <version>1.0.0</version> </dependency><dependency> <groupId>com.ironsoftware</groupId> <artifactId>ironpdf</artifactId> <version>1.0.0</version> </dependency>XML -
Importuj klasy z IronPDF:
import com.ironsoftware.ironpdf.*;import com.ironsoftware.ironpdf.*;JAVA - Utwórz PDF z HTML:
```java :title=Quickstart
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("");
pdf.saveAs(Paths.get("output.pdf"));
Jak tworzyć plik PDF w Java
- Zainstaluj bibliotekę IronPDF Java
- Utwórz plik PDF z ciągu HTML za pomocą metody
renderHtmlAsPdf - Użyj metody
renderHtmlFileAsPdf, aby utworzyć plik PDF z pliku HTML - Utwórz PDF z URL-u za pomocą metody
renderUrlAsPdf - Eksportuj pliki PDF zabezpieczone hasłem do wybranego katalogu
Tworzenie PDF-ów programowo w Java umożliwia automatyczne generowanie dokumentów dla faktur, raportów i innych dokumentów biznesowych na żądanie.
Ten przewodnik omawia użycie IronPDF do tworzenia plików PDF programowo w aplikacjach Java.
Czym jest biblioteka IronPDF Java PDF?
IronPDF to biblioteka Java do tworzenia dokumentów PDF z HTML. Dostarcza funkcji do tworzenia i personalizacji PDF-ów, w tym:
- Dodawania tekstu, obrazów i innych typów treści
- Wybierania czcionek, kolorów oraz kontrolowania układu i formatowania
IronPDF jest zbudowany na .NET Framework, co umożliwia użycie w aplikacjach zarówno .NET, jak i Java. Biblioteka obsługuje zaawansowane funkcje, takie jak własne znaki wodne, kompresja PDF oraz tworzenie formularzy.
IronPDF radzi sobie również z zadaniami związanymi z PDF, w tym konwersją formatów plików, ekstrakcją tekstu i danych oraz szyfrowaniem hasłem. Można łączyć wiele PDF-ów lub dzielić je wedle potrzeb.
Jak utworzyć dokumenty PDF w aplikacji Java?
Jakie wymagania wstępne są potrzebne?
Aby używać IronPDF w projekcie Maven, upewnij się, że te wymagania są spełnione:
- Java Development Kit (JDK): Wymagany do kompilacji i uruchamiania aplikacji Java. Download from Oracle website.
- Maven: Wymagany do pobierania bibliotek projektowych. Pobierz z strony Apache Maven.
- Biblioteka IronPDF: Dodaj do projektu Maven jako zależność w pliku pom.xml:
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.ironsoftware</groupId>
<artifactId>ironpdf</artifactId>
<version>1.0.0</version>
</dependency>
Dla projektów Gradle, dodaj IronPDF używając:
implementation 'com.ironsoftware:ironpdf:1.0.0'
Jakie kroki podjąć przed napisaniem kodu?
Najpierw dodaj to oświadczenie importu do swojego pliku źródłowego Java:
import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.*;
Dla określonej funkcjonalności, importuj dodatkowe klasy:
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.security.SecurityOptions;
import com.ironsoftware.ironpdf.security.SecurityManager;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.security.SecurityOptions;
import com.ironsoftware.ironpdf.security.SecurityManager;
Następnie skonfiguruj IronPDF z ważnym kluczem licencyjnym w metodzie main:
License.setLicenseKey("Your license key");
License.setLicenseKey("Your license key");
Uwaga: Klucze licencyjne usuwają znaki wodne. Kup klucz licencyjny lub Uzyskaj darmową wersję próbną. Bez licencji, PDF-y generują się ze znakami wodnymi. Zobacz używanie kluczy licencyjnych dla szczegółów.
Jak utworzyć pliki PDF z ciągu HTML w Java?
Użyj renderHtmlAsPdf(), aby konwertować ciągi HTML do PDF. Ta metoda obsługuje renderowanie HTML5, CSS3 i JavaScript.
Przekaż ciąg HTML do renderHtmlAsPdf. IronPDF konwertuje go do instancji PdfDocument:
// HTML content to be converted to PDF
String htmlString = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";
// Convert HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString);
// Save the PDF document to a file
pdf.saveAs(Paths.get("html.pdf"));
// HTML content to be converted to PDF
String htmlString = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";
// Convert HTML string to PDF
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString);
// Save the PDF document to a file
pdf.saveAs(Paths.get("html.pdf"));
Tworzy to "html.pdf" zawierający zawartość HTML.
Dołącz złożony HTML z stylami CSS:
// HTML with CSS styling
String styledHtml = """
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
h1 { color: #2563eb; }
.content { margin: 20px; padding: 15px; background-color: #f3f4f6; }
</style>
</head>
<body>
<div class="content">
<h1>Styled PDF Document</h1>
<p>This PDF was created from HTML with custom CSS styling.</p>
</div>
</body>
</html>
""";
PdfDocument styledPdf = PdfDocument.renderHtmlAsPdf(styledHtml);
styledPdf.saveAs(Paths.get("styled.pdf"));
// HTML with CSS styling
String styledHtml = """
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
h1 { color: #2563eb; }
.content { margin: 20px; padding: 15px; background-color: #f3f4f6; }
</style>
</head>
<body>
<div class="content">
<h1>Styled PDF Document</h1>
<p>This PDF was created from HTML with custom CSS styling.</p>
</div>
</body>
</html>
""";
PdfDocument styledPdf = PdfDocument.renderHtmlAsPdf(styledHtml);
styledPdf.saveAs(Paths.get("styled.pdf"));
Dla zaawansowanych konwersji, zobacz tutorial HTML do PDF.
Jak utworzyć pliki PDF z stron HTML w Java?
Utwórz PDF z lokalnych plików HTML:
// Convert HTML file to PDF
PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");
// Save the PdfDocument to a file
myPdf.saveAs(Paths.get("html_file_saved.pdf"));
// Convert HTML file to PDF
PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");
// Save the PdfDocument to a file
myPdf.saveAs(Paths.get("html_file_saved.pdf"));
Metoda renderHtmlFileAsPdf akceptuje ścieżkę pliku jako obiekt String lub Path.
IronPDF renderuje elementy HTML wraz z CSS i JavaScript dokładnie tak, jak robią to przeglądarki. Obejmuje to zewnętrzne pliki CSS, obrazy i biblioteki JavaScript. Zobacz pliki HTML na PDF dla szczegółów.
Użyj saveAs, aby zapisać PDF w określonym miejscu.
Jak utworzyć pliki PDF z URL-u w Java?
Użyj renderUrlAsPdf(), aby utworzyć PDF z stron internetowych:
// Convert a URL to PDF
PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Convert a URL to PDF
PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
Dla stron wymagających uwierzytelnienia, podaj dane uwierzytelniające:
// Create render options with login credentials
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setAuthUsername("username");
renderOptions.setAuthPassword("password");
// Convert secured URL to PDF
PdfDocument securedPdf = PdfDocument.renderUrlAsPdf("https://secure-site.com", renderOptions);
securedPdf.saveAs(Paths.get("secured.pdf"));
// Create render options with login credentials
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setAuthUsername("username");
renderOptions.setAuthPassword("password");
// Convert secured URL to PDF
PdfDocument securedPdf = PdfDocument.renderUrlAsPdf("https://secure-site.com", renderOptions);
securedPdf.saveAs(Paths.get("secured.pdf"));
Zobacz Przykład konwersji URL-u na PDF dla szczegółów. Dla złożonej autoryzacji, zobacz Zalogowania do stron i systemów.
Jak formatować pliki PDF?
Użyj ChromePdfRenderOptions, aby określić formatowanie PDF. Skonfiguruj orientację strony, rozmiar i marginesy. Przekaż opcje jako drugi argument do metod renderowania:
// Create render options with custom settings
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
// Set page orientation to landscape
renderOptions.setPaperOrientation(PaperOrientation.LANDSCAPE);
// Set custom paper size (Letter size)
renderOptions.setPaperSize(PaperSize.LETTER);
// Set custom margins (in millimeters)
renderOptions.setMarginTop(10);
renderOptions.setMarginRight(10);
renderOptions.setMarginBottom(10);
renderOptions.setMarginLeft(10);
// Enable background images and colors
renderOptions.setPrintHtmlBackgrounds(true);
// Apply options to PDF generation
PdfDocument formattedPdf = PdfDocument.renderHtmlAsPdf("<h1>Formatted PDF</h1>", renderOptions);
formattedPdf.saveAs(Paths.get("formatted.pdf"));
// Create render options with custom settings
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
// Set page orientation to landscape
renderOptions.setPaperOrientation(PaperOrientation.LANDSCAPE);
// Set custom paper size (Letter size)
renderOptions.setPaperSize(PaperSize.LETTER);
// Set custom margins (in millimeters)
renderOptions.setMarginTop(10);
renderOptions.setMarginRight(10);
renderOptions.setMarginBottom(10);
renderOptions.setMarginLeft(10);
// Enable background images and colors
renderOptions.setPrintHtmlBackgrounds(true);
// Apply options to PDF generation
PdfDocument formattedPdf = PdfDocument.renderHtmlAsPdf("<h1>Formatted PDF</h1>", renderOptions);
formattedPdf.saveAs(Paths.get("formatted.pdf"));
Zobacz więcej opcji w Ustawieniach generowania PDF. Odkryj niestandardowe rozmiary papieru i niestandardowe marginesy.
Jak chronić hasłem pliki PDF?
Użyj SecurityOptions, aby zabezpieczyć PDF-y hasłem:
// Create security options and set user password
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setUserPassword("shareable");
// Create security options and set user password
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setUserPassword("shareable");
Ustaw zaawansowane opcje bezpieczeństwa:
// Advanced security settings
SecurityOptions advancedSecurity = new SecurityOptions();
advancedSecurity.setUserPassword("user123");
advancedSecurity.setOwnerPassword("owner456");
// Restrict permissions
advancedSecurity.setAllowPrint(false);
advancedSecurity.setAllowCopy(false);
advancedSecurity.setAllowEditContent(false);
advancedSecurity.setAllowEditAnnotations(false);
// Advanced security settings
SecurityOptions advancedSecurity = new SecurityOptions();
advancedSecurity.setUserPassword("user123");
advancedSecurity.setOwnerPassword("owner456");
// Restrict permissions
advancedSecurity.setAllowPrint(false);
advancedSecurity.setAllowCopy(false);
advancedSecurity.setAllowEditContent(false);
advancedSecurity.setAllowEditAnnotations(false);
Zastosuj zabezpieczenia przez SecurityManager PDF-u:
// Apply security options to the PDF
SecurityManager securityManager = urlToPdf.getSecurity();
securityManager.setSecurityOptions(securityOptions);
// Save the password-protected PDF document
urlToPdf.saveAs("protected.pdf");
// Apply security options to the PDF
SecurityManager securityManager = urlToPdf.getSecurity();
securityManager.setSecurityOptions(securityOptions);
// Save the password-protected PDF document
urlToPdf.saveAs("protected.pdf");
Otwieranie PDF-u wyzwala monit o podanie hasła:
Po wprowadzeniu poprawnego hasła, PDF otwiera się normalnie.
Zobacz Przykład zabezpieczeń i metadanych dla dodatkowych ustawień.
Co zawiera kompletny kod źródłowy?
Kompletny kod źródłowy tego tutorialu:
// Import statement for IronPDF Java
import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;
public class App {
public static void main(String[] args) throws IOException {
// Apply your license key
License.setLicenseKey("Your License Key");
// Convert HTML string to a PDF and save it
String htmlString = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString);
pdf.saveAs(Paths.get("html.pdf"));
// Convert HTML file to a PDF and save it
PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");
myPdf.saveAs(Paths.get("html_file_saved.pdf"));
// Convert URL to a PDF and save it
PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
urlToPdf.saveAs(Paths.get("urlToPdf.pdf"));
// Password-protect the PDF file
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setUserPassword("shareable");
SecurityManager securityManager = urlToPdf.getSecurity();
securityManager.setSecurityOptions(securityOptions);
urlToPdf.saveAs(Paths.get("protected.pdf"));
}
}
// Import statement for IronPDF Java
import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;
public class App {
public static void main(String[] args) throws IOException {
// Apply your license key
License.setLicenseKey("Your License Key");
// Convert HTML string to a PDF and save it
String htmlString = "<h1>Hello World!</h1><p>This is an example HTML string.</p>";
PdfDocument pdf = PdfDocument.renderHtmlAsPdf(htmlString);
pdf.saveAs(Paths.get("html.pdf"));
// Convert HTML file to a PDF and save it
PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("example.html");
myPdf.saveAs(Paths.get("html_file_saved.pdf"));
// Convert URL to a PDF and save it
PdfDocument urlToPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
urlToPdf.saveAs(Paths.get("urlToPdf.pdf"));
// Password-protect the PDF file
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setUserPassword("shareable");
SecurityManager securityManager = urlToPdf.getSecurity();
securityManager.setSecurityOptions(securityOptions);
urlToPdf.saveAs(Paths.get("protected.pdf"));
}
}
IronPDF renderuje obrazy i tekst bez utraty formatowania. Przyciski pozostają klikalne, pola tekstowe edytowalne. Biblioteka obsługuje dodawanie podpisów, renderowanie wykresów i drukowanie PDF-ów.
Jakie są najważniejsze wnioski?
Ten przewodnik pokazał, jak tworzyć PDF-y w Java za pomocą IronPDF. IronPDF zapewnia prosty API do generowania PDF-ów z plików HTML, dokumentów XML lub innych źródeł.
Szybko generuj raporty, faktury czy inny rodzaj dokumentu. Wdrażaj na AWS, Azure lub Google Cloud.
IronPDF wymaga licencji komercyjnej zaczynającej się od $799. Uzyskaj darmową wersję próbną do testowania produkcji.
Często Zadawane Pytania
What is the easiest way to create a PDF file in Java?
The easiest way to create a PDF in Java is using IronPDF's renderHtmlAsPdf() method. Simply pass an HTML string to this method and save the result: PdfDocument pdf = PdfDocument.renderHtmlAsPdf("Hello World!"); pdf.saveAs(Paths.get("output.pdf"));
How do I add IronPDF to my Maven project?
Add IronPDF to your Maven project by including this dependency in your pom.xml file:
Can I convert existing HTML files to PDF format?
Yes, IronPDF provides the renderHtmlFileAsPdf() method specifically for converting HTML files to PDF. This method reads an HTML file from your file system and converts it into a PDF document.
How can I generate PDFs from web pages in Java?
IronPDF offers the renderUrlAsPdf() method to convert web pages directly to PDF. Simply provide the URL of the webpage you want to convert, and IronPDF will render it as a PDF document.
What types of business documents can I create programmatically?
IronPDF enables automated generation of various business documents including invoices, reports, forms, and other on-demand documents. The library supports advanced features like custom watermarks, PDF compression, and form creation.
Is it possible to create password-protected PDFs?
Yes, IronPDF supports password encryption for PDF files. You can export password-protected PDFs to your desired directory, ensuring document security for sensitive business information.
Jakie są wymagania systemowe dotyczące korzystania z IronPDF for Java?
To use IronPDF in Java, you need the Java Development Kit (JDK) for compiling and running applications, Maven or Gradle for dependency management, and the IronPDF library added as a dependency to your project.
Can I manipulate existing PDFs, not just create new ones?
Yes, IronPDF handles various PDF manipulation tasks beyond creation. You can merge multiple PDFs, split them, extract text and data, and perform file format conversions using the library's comprehensive features.




