Zum Fußzeileninhalt springen
VERWENDUNG VON IRONPDF FüR JAVA

Java PDF Editor Bibliothek (Wie & Code-Beispiel)

Die IronPDF Java PDF-Bibliothek ist ein leistungsstarkes Werkzeug zum Bearbeiten und Erstellen von PDF-Dokumenten innerhalb von Java-Anwendungen. Es vereinfacht eine Vielzahl von PDF-Bearbeitungsfunktionen, wie das Hinzufügen von Signaturen, HTML-Fußzeilen, Wasserzeichen und Anmerkungen.

Mit IronPDF können Sie PDF-Dateien problemlos programmatisch erstellen, Ihren Code effizient debuggen und Ihre Projekte auf vielen unterstützten Plattformen oder Umgebungen bereitstellen.

Das Hauptziel der meisten Java-PDF-Bibliotheken ist die dynamische Erstellung von PDF-Dateien. IronPDF glänzt bei dieser Aufgabe und bietet eine Vielzahl von Funktionen, um Ihre Bedürfnisse zu erfüllen.

Dieser Artikel geht auf einige der wichtigsten Funktionen von IronPDF ein und bietet Codebeispiele und Erklärungen. Am Ende werden Sie ein fundiertes Verständnis dafür haben, wie Sie IronPDF zum Bearbeiten von PDFs in Java verwenden können – perfekt für Ihre PDF-Bearbeitungsbedürfnisse.

class="hsg-featured-snippet">

Wie man die Java PDF Editor Bibliothek benutzt

  1. Java-Bibliothek zur PDF-Bearbeitung installieren
  2. PDF hinzufügen, kopieren und löschen mit prependPdf, copyPages und removePages Methoden
  3. PDF mit der merge Methode zusammenführen und PDF mit der copyPages Methode teilen
  4. Neues PDF mit benutzerdefinierter Papiergröße erstellen
  5. PDF-Metadaten bearbeiten

Dokumentenstruktur bearbeiten

PDF-Dokumente manipulieren

Mit IronPDF wird die Verwaltung von PDFs mühelos durch die Möglichkeit, PDFs an bestimmten Indizes hinzuzufügen, Seiten entweder als Bereich oder einzeln zu kopieren und Seiten mit Leichtigkeit zu löschen. All diese Aufgaben werden nahtlos im Hintergrund bearbeitet.

Seiten hinzufügen

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

public class AddPagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PdfDocument coverPagePdf = PdfDocument.renderHtmlAsPdf("<h1>Cover Page</h1><hr>");
            PDF.prependPdf(coverPagePdf);
            PDF.saveAs(Paths.get("report_with_cover.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;

public class AddPagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PdfDocument coverPagePdf = PdfDocument.renderHtmlAsPdf("<h1>Cover Page</h1><hr>");
            PDF.prependPdf(coverPagePdf);
            PDF.saveAs(Paths.get("report_with_cover.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Seiten kopieren

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

public class CopyPagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PDF.copyPages(0, 1).saveAs("report_highlight.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;

public class CopyPagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PDF.copyPages(0, 1).saveAs("report_highlight.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Seiten löschen

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;

public class DeletePagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PDF.removePages(PageSelection.lastPage()).saveAs(Paths.get("assets/lastPageRemove.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;

public class DeletePagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PDF.removePages(PageSelection.lastPage()).saveAs(Paths.get("assets/lastPageRemove.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Eine Titelseite anhängen

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;

public class AttachCoverPageExample {
    public static void main(String[] args) {
        // Create a Sample Cover Page using RenderHtmlAsPdf
        PdfDocument coverPage = PdfDocument.renderHtmlAsPdf("<h1>This is a Cover Page</h1>");
        PdfDocument webpage = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

        // Set the page number of the PDF document to be created to 2.
        HeaderFooterOptions headerFooterOptions = new HeaderFooterOptions();
        headerFooterOptions.setFirstPageNumber(1);
        TextHeaderFooter footer = new TextHeaderFooter();
        footer.setLeftText("");
        footer.setCenterText("Page {page}");
        footer.setRightText("");

        webpage.addTextFooter(footer, headerFooterOptions);

        // Convert a web page's content to a PDF document.
        // Merge the cover page with the web page and save the new PDF to the filesystem.
        try {
            PdfDocument.merge(coverPage, webpage).saveAs(Paths.get("assets/cover_page_pdf.pdf"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;

public class AttachCoverPageExample {
    public static void main(String[] args) {
        // Create a Sample Cover Page using RenderHtmlAsPdf
        PdfDocument coverPage = PdfDocument.renderHtmlAsPdf("<h1>This is a Cover Page</h1>");
        PdfDocument webpage = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

        // Set the page number of the PDF document to be created to 2.
        HeaderFooterOptions headerFooterOptions = new HeaderFooterOptions();
        headerFooterOptions.setFirstPageNumber(1);
        TextHeaderFooter footer = new TextHeaderFooter();
        footer.setLeftText("");
        footer.setCenterText("Page {page}");
        footer.setRightText("");

        webpage.addTextFooter(footer, headerFooterOptions);

        // Convert a web page's content to a PDF document.
        // Merge the cover page with the web page and save the new PDF to the filesystem.
        try {
            PdfDocument.merge(coverPage, webpage).saveAs(Paths.get("assets/cover_page_pdf.pdf"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
JAVA

Erfahren Sie mehr über das Anhängen einer Titelseite in PDF-Dokumenten bei IronPDF.

PDFs zusammenführen und teilen

IronPDF Java vereinfacht den Prozess, mehrere PDFs zu einem zusammenzufügen oder ein bestehendes PDF mithilfe seiner benutzerfreundlichen API zu teilen.

Mehrere vorhandene PDF-Dokumente zu einem einzigen PDF-Dokument zusammenfügen

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

public class MergePdfsExample {
    public static void main(String[] args) {
        String htmlA = "<p> [PDF_A] </p>" +
                "<p> [PDF_A] 1st Page </p>" +
                "<div style='page-break-after: always;'></div>" +
                "<p> [PDF_A] 2nd Page</p>";
        String htmlB = "<p> [PDF_B] </p>" +
                "<p> [PDF_B] 1st Page </p>" +
                "<div style='page-break-after: always;'></div>" +
                "<p> [PDF_B] 2nd Page</p>";

        PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
        PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);
        PdfDocument merged = PdfDocument.merge(pdfA, pdfB);

        merged.saveAs(Paths.get("assets/merged.pdf"));
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;

public class MergePdfsExample {
    public static void main(String[] args) {
        String htmlA = "<p> [PDF_A] </p>" +
                "<p> [PDF_A] 1st Page </p>" +
                "<div style='page-break-after: always;'></div>" +
                "<p> [PDF_A] 2nd Page</p>";
        String htmlB = "<p> [PDF_B] </p>" +
                "<p> [PDF_B] 1st Page </p>" +
                "<div style='page-break-after: always;'></div>" +
                "<p> [PDF_B] 2nd Page</p>";

        PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
        PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);
        PdfDocument merged = PdfDocument.merge(pdfA, pdfB);

        merged.saveAs(Paths.get("assets/merged.pdf"));
    }
}
JAVA

Ein PDF teilen und Seiten extrahieren

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

public class SplitPdfExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PdfDocument copied = PDF.copyPage(0);
            copied.saveAs("assets/Split.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;

public class SplitPdfExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PdfDocument copied = PDF.copyPage(0);
            copied.saveAs("assets/Split.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Die benutzerdefinierte Größe von PDF-Dokumenten festlegen

Mit IronPDF können Entwickler PDF-Dokumente mit nicht standardmäßigen Abmessungen erstellen, jenseits der konventionellen A4-Größe (8½ x 11 Zoll oder 21,59 x 27,94 cm).

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.render.PaperSize;
import java.io.IOException;
import java.nio.file.Paths;

public class CustomSizeExample {
    public static void main(String[] args) {
        String html = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>";

        ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
        renderOptions.setPaperSize(PaperSize.Custom);

        /*
        * Setting page sizes using different measuring units:
        * 1. setCustomPaperWidth( width ) / setCustomPaperHeight( height ): for inches
        * 2. setCustomPaperSizeInCentimeters( width, height ): for centimeters.
        * 3. setCustomPaperSizeInMillimeters( width, height ): for millimeters
        * 4. setCustomPaperSizeInPixelsOrPoints( width, height ): for pixels/points
        * */
        renderOptions.setCustomPaperSizeInCentimeters(13.97, 13.97);

        PdfDocument.renderHtmlAsPdf(html, renderOptions).saveAs(Paths.get("assets/CustomPaperSize.pdf"));
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.render.PaperSize;
import java.io.IOException;
import java.nio.file.Paths;

public class CustomSizeExample {
    public static void main(String[] args) {
        String html = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>";

        ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
        renderOptions.setPaperSize(PaperSize.Custom);

        /*
        * Setting page sizes using different measuring units:
        * 1. setCustomPaperWidth( width ) / setCustomPaperHeight( height ): for inches
        * 2. setCustomPaperSizeInCentimeters( width, height ): for centimeters.
        * 3. setCustomPaperSizeInMillimeters( width, height ): for millimeters
        * 4. setCustomPaperSizeInPixelsOrPoints( width, height ): for pixels/points
        * */
        renderOptions.setCustomPaperSizeInCentimeters(13.97, 13.97);

        PdfDocument.renderHtmlAsPdf(html, renderOptions).saveAs(Paths.get("assets/CustomPaperSize.pdf"));
    }
}
JAVA

Hier finden Sie weitere Tipps zu benutzerdefinierten PDF-Papiergrößen bei IronPDF.

PDF-Ausrichtung festlegen

Mit IronPDF für Java können Seitenorientierungen in sowohl neuen als auch bestehenden PDFs geändert werden. Standardmäßig sind neue mit IronPDF erstellte PDFs im Hochformat ausgerichtet, Entwickler können dies jedoch ändern, indem sie eine ChromePdfRenderOptions Instanz verwenden, wenn sie Inhalte (wie HTML, RTFs und URLs) in PDFs konvertieren.

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.page.PageRotation;
import com.ironsoftware.ironpdf.render.*;
import java.io.IOException;
import java.nio.file.Paths;

public class SetOrientationExample {
    public static void main(String[] args) {
        // Load an existing PDF
        PdfDocument existingPdf = PdfDocument.fromFile("assets/sample.pdf");

        // Get the orientation of the first page of the existing PDF document.
        PageRotation firstPageRotation = existingPdf.getPagesInfo().get(0).getPageRotation();
        System.out.println(firstPageRotation);

        // Rotate the first page of the document only 90 degrees clockwise.
        existingPdf.rotatePage(PageRotation.CLOCKWISE_90, PageSelection.firstPage());

        // Rotate all pages of the document clockwise.
        existingPdf.rotateAllPages(PageRotation.CLOCKWISE_270);

        existingPdf.saveAs(Paths.get("assets/ExistingPdfRotated.pdf"));
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.page.PageRotation;
import com.ironsoftware.ironpdf.render.*;
import java.io.IOException;
import java.nio.file.Paths;

public class SetOrientationExample {
    public static void main(String[] args) {
        // Load an existing PDF
        PdfDocument existingPdf = PdfDocument.fromFile("assets/sample.pdf");

        // Get the orientation of the first page of the existing PDF document.
        PageRotation firstPageRotation = existingPdf.getPagesInfo().get(0).getPageRotation();
        System.out.println(firstPageRotation);

        // Rotate the first page of the document only 90 degrees clockwise.
        existingPdf.rotatePage(PageRotation.CLOCKWISE_90, PageSelection.firstPage());

        // Rotate all pages of the document clockwise.
        existingPdf.rotateAllPages(PageRotation.CLOCKWISE_270);

        existingPdf.saveAs(Paths.get("assets/ExistingPdfRotated.pdf"));
    }
}
JAVA

Für mehr Informationen besuchen Sie das Tutorial zur Festlegung der PDF-Ausrichtung auf der IronPDF-Website.

Benutzerdefinierte Ränder von PDF festlegen

IronPDF erstellt neue PDFs standardmäßig mit einem Rand von 25 mm auf allen Seiten (oben, unten, links, rechts). Allerdings können Entwickler jeden Rand mit spezifischen Messungen anpassen, indem sie IronPDF verwenden.

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class CustomMarginsExample {
    public static void main(String[] args) {
        // Set Margins (in millimeters)
        ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
        renderOptions.setMarginTop(40);
        renderOptions.setMarginLeft(20);
        renderOptions.setMarginRight(20);
        renderOptions.setMarginBottom(40);

        try {
            PdfDocument.renderHtmlFileAsPdf("assets/wikipedia.html", renderOptions).saveAs(Paths.get("assets/MyContent.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class CustomMarginsExample {
    public static void main(String[] args) {
        // Set Margins (in millimeters)
        ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
        renderOptions.setMarginTop(40);
        renderOptions.setMarginLeft(20);
        renderOptions.setMarginRight(20);
        renderOptions.setMarginBottom(40);

        try {
            PdfDocument.renderHtmlFileAsPdf("assets/wikipedia.html", renderOptions).saveAs(Paths.get("assets/MyContent.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Besuchen Sie die IronPDF-Website, um mehr über benutzerdefinierte Ränder für PDF-Dokumente festzulegen.

PDF-Dokumente in Bilder konvertieren

IronPDF kann Seiten einer geladenen PDF-Datei, des konvertierten Quellinhalts oder eines modifizierten PDFs mit Kopfzeilen, Fußzeilen, Rändern usw. in Bilder exportieren, die im Dateisystem gespeichert, in einer Datenbank abgelegt oder über Netzwerke übertragen werden können.

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.image.ToImageOptions;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

public class ConvertPdfToImagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/composite.pdf"));

            // Extract all the pages from the PDF file.
            List<BufferedImage> extractedImages = pdf.toBufferedImages();

            // With the ToImageOptions object, specify maximum image dimensions for each
            // extracted image, as well as their DPI
            ToImageOptions rasterOptions = new ToImageOptions();
            rasterOptions.setImageMaxHeight(100);
            rasterOptions.setImageMaxWidth(100);

            // Call the toBufferedImage method along with a PageSelection object to choose the pages from which to
            // extract the images
            //
            // Available PageSelection methods include: allPages, lastPage, firstPage, singlePage(int pageIndex),
            // and pageRange(int startingPage, int endingPage)
            List<BufferedImage> sizedExtractedImages = pdf.toBufferedImages(rasterOptions, PageSelection.allPages());

            // Save all the extracted images to a file location
            int i = 1;
            for (BufferedImage extractedImage : sizedExtractedImages) {
                String fileName = "assets/images/" + i++ + ".png";
                ImageIO.write(extractedImage, "PNG", new File(fileName));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.image.ToImageOptions;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

public class ConvertPdfToImagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/composite.pdf"));

            // Extract all the pages from the PDF file.
            List<BufferedImage> extractedImages = pdf.toBufferedImages();

            // With the ToImageOptions object, specify maximum image dimensions for each
            // extracted image, as well as their DPI
            ToImageOptions rasterOptions = new ToImageOptions();
            rasterOptions.setImageMaxHeight(100);
            rasterOptions.setImageMaxWidth(100);

            // Call the toBufferedImage method along with a PageSelection object to choose the pages from which to
            // extract the images
            //
            // Available PageSelection methods include: allPages, lastPage, firstPage, singlePage(int pageIndex),
            // and pageRange(int startingPage, int endingPage)
            List<BufferedImage> sizedExtractedImages = pdf.toBufferedImages(rasterOptions, PageSelection.allPages());

            // Save all the extracted images to a file location
            int i = 1;
            for (BufferedImage extractedImage : sizedExtractedImages) {
                String fileName = "assets/images/" + i++ + ".png";
                ImageIO.write(extractedImage, "PNG", new File(fileName));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Hintergrund und Vordergrund hinzufügen

IronPDF provides addBackgroundPdf and addForegroundPdf methods for adding a specific background or foreground element to PDFs. Diese Methoden ermöglichen es Entwicklern, Inhalte aus einem PDF als Hintergrund oder Vordergrund eines anderen PDFs einzufügen, was es effizient macht, Sammlungen von PDFs basierend auf einer gemeinsamen Designvorlage zu generieren.

PDF als Hintergrund hinzufügen

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

public class AddBackgroundExample {
    public static void main(String[] args) {
        try {
            // Load background PDFs from the filesystem (or create them programmatically)
            PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));

            // Render content (HTML, URL, etc) as a PDF Document
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

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

            pdf.saveAs(Paths.get("assets/BackgroundPdf.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;

public class AddBackgroundExample {
    public static void main(String[] args) {
        try {
            // Load background PDFs from the filesystem (or create them programmatically)
            PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));

            // Render content (HTML, URL, etc) as a PDF Document
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

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

            pdf.saveAs(Paths.get("assets/BackgroundPdf.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

PDF als Vordergrund hinzufügen

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

public class AddForegroundExample {
    public static void main(String[] args) {
        try {
            PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
            pdf.addForegroundPdf(foregroundPdf);

            pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;

public class AddForegroundExample {
    public static void main(String[] args) {
        try {
            PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
            pdf.addForegroundPdf(foregroundPdf);

            pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Dokumenteigenschaften bearbeiten

PDF-Metadaten hinzufügen und verwenden

IronPDF bietet die Möglichkeit, PDF-Metadaten und Sicherheitsmerkmale zu ändern, einschließlich das Festlegen von PDFs auf nur-schreibgeschützt, nicht druckbar, passwortgeschützt und verschlüsselt. In IronPDF für Java kann der MetadataManager auf die Metadaten eines PDFs zugreifen und diese bearbeiten. Die MetadataManager Klasse bietet direkten Zugriff auf Metadateninhalte und ermöglicht es Entwicklern, allgemeine Metadateneigenschaften mit gleichnamigen Setzern und Holern zu lesen und zu bearbeiten.

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.metadata.MetadataManager;
import com.ironsoftware.ironpdf.security.PdfPrintSecurity;
import com.ironsoftware.ironpdf.security.SecurityOptions;
import com.ironsoftware.ironpdf.security.SecurityManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;

public class EditMetadataExample {
    public static void main(String[] args) {
        try {
            // Open an encrypted file (or create a new one from HTML)
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/encrypted.pdf"), "password");

            // Edit file metadata
            MetadataManager metadata = pdf.getMetadata();
            metadata.setAuthor("Satoshi Nakamoto");
            metadata.setKeywords("SEO, Friendly");
            metadata.setModifiedDate(new Date().toString());

            // Edit file security settings
            // The code below makes the PDF read-only and disallows users to copy, paste, and print
            SecurityOptions securityOptions = new SecurityOptions();
            securityOptions.setAllowUserCopyPasteContent(false);
            securityOptions.setAllowUserAnnotations(false);
            securityOptions.setAllowUserPrinting(PdfPrintSecurity.FULL_PRINT_RIGHTS);
            securityOptions.setAllowUserFormData(false);
            securityOptions.setOwnerPassword("top-secret");
            securityOptions.setUserPassword("sharable");

            // Change or set the document encryption password
            SecurityManager securityManager = pdf.getSecurity();
            securityManager.removePasswordsAndEncryption();
            securityManager.makePdfDocumentReadOnly("secret-key");

            securityManager.setSecurityOptions(securityOptions);
            pdf.saveAs(Paths.get("assets/secured.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.metadata.MetadataManager;
import com.ironsoftware.ironpdf.security.PdfPrintSecurity;
import com.ironsoftware.ironpdf.security.SecurityOptions;
import com.ironsoftware.ironpdf.security.SecurityManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;

public class EditMetadataExample {
    public static void main(String[] args) {
        try {
            // Open an encrypted file (or create a new one from HTML)
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/encrypted.pdf"), "password");

            // Edit file metadata
            MetadataManager metadata = pdf.getMetadata();
            metadata.setAuthor("Satoshi Nakamoto");
            metadata.setKeywords("SEO, Friendly");
            metadata.setModifiedDate(new Date().toString());

            // Edit file security settings
            // The code below makes the PDF read-only and disallows users to copy, paste, and print
            SecurityOptions securityOptions = new SecurityOptions();
            securityOptions.setAllowUserCopyPasteContent(false);
            securityOptions.setAllowUserAnnotations(false);
            securityOptions.setAllowUserPrinting(PdfPrintSecurity.FULL_PRINT_RIGHTS);
            securityOptions.setAllowUserFormData(false);
            securityOptions.setOwnerPassword("top-secret");
            securityOptions.setUserPassword("sharable");

            // Change or set the document encryption password
            SecurityManager securityManager = pdf.getSecurity();
            securityManager.removePasswordsAndEncryption();
            securityManager.makePdfDocumentReadOnly("secret-key");

            securityManager.setSecurityOptions(securityOptions);
            pdf.saveAs(Paths.get("assets/secured.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Digitale Signaturen

Mit IronPDF für Java können neue oder bestehende PDF-Dateien sicher signiert werden, entweder mit X509Certificate2 digitalen Zertifikaten im .pfx oder .p12 Format. Durch das digitale Signieren eines PDFs wird dessen Authentizität garantiert und Änderungen ohne korrekte Zertifikatsvalidierung verhindert. Dies verbessert die Zuverlässigkeit des Dokuments.

Für eine kostenlose Möglichkeit, ein Signaturzertifikat zu generieren, bietet Adobe Reader Anweisungen in seinem Digital ID-Tutorial.

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.signature.Signature;
import com.ironsoftware.ironpdf.signature.SignatureManager;

public class DigitalSignatureExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));

            // Load the X509Certificate2 digitals certificates from .pfx or .p12 formats
            File path = new File("assets/Ironpdf.pfx");
            byte[] certificate = new byte[(int) path.length()];

            // Sign PDF with a specific signature
            Signature signature = new Signature(certificate, "1234");
            SignatureManager manager = PDF.getSignature();
            manager.signPdfWithSignature(signature);

            PDF.saveAs(Paths.get("assets/signed_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.signature.Signature;
import com.ironsoftware.ironpdf.signature.SignatureManager;

public class DigitalSignatureExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));

            // Load the X509Certificate2 digitals certificates from .pfx or .p12 formats
            File path = new File("assets/Ironpdf.pfx");
            byte[] certificate = new byte[(int) path.length()];

            // Sign PDF with a specific signature
            Signature signature = new Signature(certificate, "1234");
            SignatureManager manager = PDF.getSignature();
            manager.signPdfWithSignature(signature);

            PDF.saveAs(Paths.get("assets/signed_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

PDFs komprimieren

IronPDF reduces PDF file size with its compressImages method in the PdfDocument class, making it easy to compress PDFs with large images. Diese Optimierung führt zu erheblichen Einsparungen bei Speicherplatz und Kosten bei der Übertragung von PDFs per E-Mail und anderen Kommunikationskanälen.

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

public class CompressPdfExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/document.pdf"));

            // Valid image compression values range from 1 to 100, where 100 represents 100% of the original image quality.
            pdf.compressImages(60);
            pdf.saveAs(Paths.get("assets/document_compressed.pdf"));

            // The second, optional parameter can scale down the image resolution according to its visible size in the PDF document.
            // Note that this may cause distortion with some image configurations.
            pdf.compressImages(90, true);
            pdf.saveAs(Paths.get("assets/document_scaled_compressed.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;

public class CompressPdfExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/document.pdf"));

            // Valid image compression values range from 1 to 100, where 100 represents 100% of the original image quality.
            pdf.compressImages(60);
            pdf.saveAs(Paths.get("assets/document_compressed.pdf"));

            // The second, optional parameter can scale down the image resolution according to its visible size in the PDF document.
            // Note that this may cause distortion with some image configurations.
            pdf.compressImages(90, true);
            pdf.saveAs(Paths.get("assets/document_scaled_compressed.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

PDF-Inhalte bearbeiten

Kopf- und Fußzeilen hinzufügen

IronPDF allows you to add custom HTML headers and footers using the ChromePdfRenderOptions and HtmlHeaderFooter classes. It also supports custom text headers and footers through the TextHeaderFooter class, which allows specifying text for the header/footer's left, right, or center regions. Vorlagentags wie {date}, {time}, und {page} können mit benutzerdefiniertem Text verwendet werden.

HTML-Kopf- und Fußzeile

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

public class HtmlHeaderFooterExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

            // Build a footer using HTML
            // Merge Fields are: {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
            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
            // Note the use of BaseUrl to set a relative path to the assets
            HtmlHeaderFooter header = new HtmlHeaderFooter();
            header.setMaxHeight(20); // millimeters
            header.setHtmlFragment("<img src=\"logo.png\" />");
            header.setBaseUrl("./assets/");
            pdf.addHtmlHeader(header);

            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.ArrayList;
import java.util.List;

public class HtmlHeaderFooterExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

            // Build a footer using HTML
            // Merge Fields are: {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
            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
            // Note the use of BaseUrl to set a relative path to the assets
            HtmlHeaderFooter header = new HtmlHeaderFooter();
            header.setMaxHeight(20); // millimeters
            header.setHtmlFragment("<img src=\"logo.png\" />");
            header.setBaseUrl("./assets/");
            pdf.addHtmlHeader(header);

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

Text-Kopf- und Fußzeile

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.font.FontTypes;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class TextHeaderFooterExample {
    public static void main(String[] args) {
        try {
            // Initialize HeaderFooterOptions object.
            HeaderFooterOptions options = new HeaderFooterOptions();
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("http://www.google.com");

            // Add a header to every page easily
            // Mergeable fields are:
            // {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
            options.setFirstPageNumber(1); // use 2 if a coverpage will be appended
            TextHeaderFooter textHeader = new TextHeaderFooter();
            textHeader.setDrawDividerLine(true);
            textHeader.setCenterText("{url}");
            textHeader.setFont(FontTypes.getHelvetica());
            textHeader.setFontSize(12);
            pdf.addTextHeader(textHeader, options);

            // Add a footer too
            TextHeaderFooter textFooter = new TextHeaderFooter();
            textFooter.setDrawDividerLine(true);
            textFooter.setFont(FontTypes.getArial());
            textFooter.setFontSize(10);
            textFooter.setLeftText("{date} {time}");
            textFooter.setRightText("{page} of {total-pages}");
            pdf.addTextFooter(textFooter, options);

            pdf.saveAs(Paths.get("assets/text_headers_footers.pdf"));
        } catch (IOException e) {
            System.out.println("Failed to save PDF");
            throw new RuntimeException(e);
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.font.FontTypes;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class TextHeaderFooterExample {
    public static void main(String[] args) {
        try {
            // Initialize HeaderFooterOptions object.
            HeaderFooterOptions options = new HeaderFooterOptions();
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("http://www.google.com");

            // Add a header to every page easily
            // Mergeable fields are:
            // {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
            options.setFirstPageNumber(1); // use 2 if a coverpage will be appended
            TextHeaderFooter textHeader = new TextHeaderFooter();
            textHeader.setDrawDividerLine(true);
            textHeader.setCenterText("{url}");
            textHeader.setFont(FontTypes.getHelvetica());
            textHeader.setFontSize(12);
            pdf.addTextHeader(textHeader, options);

            // Add a footer too
            TextHeaderFooter textFooter = new TextHeaderFooter();
            textFooter.setDrawDividerLine(true);
            textFooter.setFont(FontTypes.getArial());
            textFooter.setFontSize(10);
            textFooter.setLeftText("{date} {time}");
            textFooter.setRightText("{page} of {total-pages}");
            pdf.addTextFooter(textFooter, options);

            pdf.saveAs(Paths.get("assets/text_headers_footers.pdf"));
        } catch (IOException e) {
            System.out.println("Failed to save PDF");
            throw new RuntimeException(e);
        }
    }
}
JAVA

Lesezeichen

With the BookmarkManager class, developers can create a hierarchical structure of bookmarks within a PDF, allowing users to easily navigate to different sections. Um ein neues Lesezeichen hinzuzufügen, verwenden Sie die Hinzufügemethode und geben den Titel und die Seitenzahl des Lesezeichens an. Lesezeichen können verschachtelt werden, um eine besser organisierte Struktur zu erstellen.

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 BookmarksExample {
    public static void main(String[] args) {
        try {
            // Load an existing PDF from the file system (or create a new one from HTML)
            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);

            // Retrieve a reference to the Summary bookmark so that we can add a sublist of bookmarks to it.
            List<Bookmark> bookmarkList = bookmarks.getBookmarks();
            Bookmark bookmark = bookmarkList.get(2);
            bookmark.addChildBookmark("Conclusion", 11);

            // Save the PDF to the filesystem
            pdf.saveAs(Paths.get("assets/bookmarked.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
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 BookmarksExample {
    public static void main(String[] args) {
        try {
            // Load an existing PDF from the file system (or create a new one from HTML)
            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);

            // Retrieve a reference to the Summary bookmark so that we can add a sublist of bookmarks to it.
            List<Bookmark> bookmarkList = bookmarks.getBookmarks();
            Bookmark bookmark = bookmarkList.get(2);
            bookmark.addChildBookmark("Conclusion", 11);

            // Save the PDF to the filesystem
            pdf.saveAs(Paths.get("assets/bookmarked.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Anmerkungen hinzufügen und bearbeiten

IronPDF can add "sticky note" style annotations to specific pages of a PDF using the AnnotationManager and AnnotationOptions classes. Erstellen Sie textbasierte Anmerkungen, indem Sie Text und (x, y) Koordinaten in den AnnotationOptions Konstruktor eingeben, und verwenden Sie dann die addTextAnnotation Methode des AnnotationManager, um die Anmerkung auf die gewünschte Seite hinzuzufügen.

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) {
        try {
            // Create a new PDF or load an existing one from the filesystem
            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);

            // Save the PDF with the modifications
            pdf.saveAs(Paths.get("assets/annotated.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
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) {
        try {
            // Create a new PDF or load an existing one from the filesystem
            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);

            // Save the PDF with the modifications
            pdf.saveAs(Paths.get("assets/annotated.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Stempeln und Wasserzeichen

IronPDF für Java hat eine leistungsstarke API, die umfangreiche Stempel- und Wasserzeichen-Fähigkeiten bietet. Mit seiner einfach zu bedienenden Benutzeroberfläche können Entwickler schnell Bilder und HTML-Stempel zu ihren PDFs hinzufügen. Egal ob Sie ein Firmenlogo, einen Vertraulichkeitshinweis oder einen einzigartigen Identifikator benötigen, IronPDF bietet Ihnen alles, was Sie brauchen, um Stempel zu Ihren PDFs einfach und professionell hinzuzufügen.

Text auf ein PDF stempeln

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.TextStamper;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

public class StampTextExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            TextStamper stamper1 = new TextStamper();
            stamper1.setText("Hello World! Stamp One Here!");
            stamper1.setFontFamily("Bungee Spice");
            stamper1.setUseGoogleFont(true);

            stamper1.setFontSize(100);
            stamper1.setBold(true);
            stamper1.setItalic(false);
            stamper1.setVerticalAlignment(VerticalAlignment.TOP);

            pdf.applyStamp(stamper1);
            pdf.saveAs(Paths.get("assets/stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.TextStamper;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

public class StampTextExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            TextStamper stamper1 = new TextStamper();
            stamper1.setText("Hello World! Stamp One Here!");
            stamper1.setFontFamily("Bungee Spice");
            stamper1.setUseGoogleFont(true);

            stamper1.setFontSize(100);
            stamper1.setBold(true);
            stamper1.setItalic(false);
            stamper1.setVerticalAlignment(VerticalAlignment.TOP);

            pdf.applyStamp(stamper1);
            pdf.saveAs(Paths.get("assets/stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Ein Bild auf ein PDF stempeln

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.stamp.ImageStamper;

public class StampImageExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            ImageStamper imageStamper = new ImageStamper(Paths.get("assets/logo.png"));
            // Apply to every page, one page, or some pages
            pdf.applyStamp(imageStamper);
            pdf.applyStamp(imageStamper, PageSelection.singlePage(2));
            pdf.applyStamp(imageStamper, PageSelection.pageRange(0, 2));
            pdf.saveAs(Paths.get("assets/image_stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.stamp.ImageStamper;

public class StampImageExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            ImageStamper imageStamper = new ImageStamper(Paths.get("assets/logo.png"));
            // Apply to every page, one page, or some pages
            pdf.applyStamp(imageStamper);
            pdf.applyStamp(imageStamper, PageSelection.singlePage(2));
            pdf.applyStamp(imageStamper, PageSelection.pageRange(0, 2));
            pdf.saveAs(Paths.get("assets/image_stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Einen Barcode auf ein PDF stempeln

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

public class StampBarcodeExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            BarcodeStamper barcodeStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39);

            barcodeStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
            barcodeStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);

            pdf.applyStamp(barcodeStamp);
            pdf.saveAs(Paths.get("assets/barcode_stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

public class StampBarcodeExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            BarcodeStamper barcodeStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39);

            barcodeStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
            barcodeStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);

            pdf.applyStamp(barcodeStamp);
            pdf.saveAs(Paths.get("assets/barcode_stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Einen QR-Code auf ein PDF stempeln

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

public class StampQrCodeExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            BarcodeStamper QRStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode);
            QRStamp.setHeight(50);
            QRStamp.setWidth(50);
            QRStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
            QRStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
            pdf.applyStamp(QRStamp);
            pdf.saveAs(Paths.get("assets/qrcode_stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

public class StampQrCodeExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            BarcodeStamper QRStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode);
            QRStamp.setHeight(50);
            QRStamp.setWidth(50);
            QRStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
            QRStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
            pdf.applyStamp(QRStamp);
            pdf.saveAs(Paths.get("assets/qrcode_stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Ein Wasserzeichen zu einem PDF hinzufügen

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

public class AddWatermarkExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            String html = "<h1> Example Title <h1/>";
            int watermarkOpacity = 30;
            pdf.applyWatermark(html, watermarkOpacity);
            pdf.saveAs(Paths.get("assets/watermarked_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;

public class AddWatermarkExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            String html = "<h1> Example Title <h1/>";
            int watermarkOpacity = 30;
            pdf.applyWatermark(html, watermarkOpacity);
            pdf.saveAs(Paths.get("assets/watermarked_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Verwendung von Formularen in PDFs

IronPDF Java bietet einen einfachen und effizienten Weg, um Werte von Textfeldern in einem PDF-Dokument einzustellen und abzurufen, indem die FormManager Klasse verwendet wird. Entwickler können die setFieldValue Methode aufrufen, um den Namen und Wert des Textfelds anzugeben.

Rufen Sie den Wert eines Formularfelds direkt über die Sammlung von FormField-Objekten des FormManager ab, indem Sie den relevanten Namen oder Index verwenden. Diese Ebene der Kontrolle über Formularfelder erleichtert die Arbeit mit dynamischen und interaktiven PDF-Formularen.

Formulare erstellen und bearbeiten

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class CreateAndEditFormsExample {
    public static void main(String[] args) {
        try {
            // #1 Use Case: Create a PDF Form from HTML Form Markup
            Path outputLocation = Paths.get("assets/BasicForm.pdf");
            String formHTML = "<html>" +
                    "<body>" +
                    "<h2>Editable PDF Form</h2>" +
                    "<form>" +
                    "First name: <br> <input type='text' name='firstname' value=''> <br>" +
                    "Last name: <br> <input type='text' name='lastname' value=''>" +
                    "</form>" +
                    "</body>" +
                    "</html>";

            ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
            renderOptions.setCreatePdfFormsFromHtml(true);
            PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);

            // #2 Use Case: Writing Values to the PDF Form
            PdfDocument form = PdfDocument.fromFile(outputLocation);

            // Set the value of the firstname input field.
            form.getForm().setFieldValue("firstname", "Minnie");

            // Set the value of the lastname input field.
            form.getForm().setFieldValue("lastname", "Mouse");

            // Save the changes to the PDF Form.
            form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class CreateAndEditFormsExample {
    public static void main(String[] args) {
        try {
            // #1 Use Case: Create a PDF Form from HTML Form Markup
            Path outputLocation = Paths.get("assets/BasicForm.pdf");
            String formHTML = "<html>" +
                    "<body>" +
                    "<h2>Editable PDF Form</h2>" +
                    "<form>" +
                    "First name: <br> <input type='text' name='firstname' value=''> <br>" +
                    "Last name: <br> <input type='text' name='lastname' value=''>" +
                    "</form>" +
                    "</body>" +
                    "</html>";

            ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
            renderOptions.setCreatePdfFormsFromHtml(true);
            PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);

            // #2 Use Case: Writing Values to the PDF Form
            PdfDocument form = PdfDocument.fromFile(outputLocation);

            // Set the value of the firstname input field.
            form.getForm().setFieldValue("firstname", "Minnie");

            // Set the value of the lastname input field.
            form.getForm().setFieldValue("lastname", "Mouse");

            // Save the changes to the PDF Form.
            form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

Bestehende Formulare ausfüllen

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

public class FillExistingFormsExample {
    public static void main(String[] args) {
        try {
            PdfDocument form = PdfDocument.fromFile("assets/pdfform.pdf");

            // Set the value of the firstname input field.
            form.getForm().setFieldValue("firstname", "Minnie");

            // Set the value of the lastname input field.
            form.getForm().setFieldValue("lastname", "Mouse");

            // Save the changes to the PDF Form.
            form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;

public class FillExistingFormsExample {
    public static void main(String[] args) {
        try {
            PdfDocument form = PdfDocument.fromFile("assets/pdfform.pdf");

            // Set the value of the firstname input field.
            form.getForm().setFieldValue("firstname", "Minnie");

            // Set the value of the lastname input field.
            form.getForm().setFieldValue("lastname", "Mouse");

            // Save the changes to the PDF Form.
            form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

PDF zum Drucken senden

Die Druckmethode von IronPDF ermöglicht es Entwicklern, das PDF-Drucken einfach in ihre Anwendungen zu integrieren. Indem Sie die [print](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#print()) Methode aufrufen, öffnet sich der Druckdialog des Betriebssystems und bietet Benutzern Optionen zur Anpassung von Einstellungen wie Drucker, Papiergröße und Anzahl der Kopien.

import com.ironsoftware.ironpdf.PdfDocument;
import java.awt.print.PrinterException;

public class PrintPdfExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Created with IronPDF!</h1>");
            pdf.print();
        } catch (PrinterException exception) {
            System.out.println("Failed to print PDF");
            exception.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.awt.print.PrinterException;

public class PrintPdfExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Created with IronPDF!</h1>");
            pdf.print();
        } catch (PrinterException exception) {
            System.out.println("Failed to print PDF");
            exception.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
JAVA

Abschluss

IronPDF ist eine umfassende PDF-Bibliothek für Java, die eine Vielzahl von Funktionen zum Erstellen, Bearbeiten und Verarbeiten von PDF-Dokumenten bietet. Es verfügt über robuste Methoden zur Text- und Bildextraktion, mit denen Entwickler auf PDF-Inhalte zugreifen und diese verarbeiten können. IronPDF bietet auch Flexibilität bei der Anpassung von PDF-Metadaten und Sicherheitseinstellungen, wie zum Beispiel das Festlegen eines PDFs auf nur lesbar oder passwortgeschützt. Es enthält eine Methode zur Komprimierung von PDFs, zur Reduzierung der Dateigröße und zur Verbesserung der Übertragungseffizienz.

Die Bibliothek ermöglicht das Hinzufügen von benutzerdefinierten Kopf- und Fußzeilen sowie Anmerkungen zu einem PDF-Dokument. Die Lesezeichenfunktion ermöglicht es Entwicklern, Lesezeichen für eine einfache Navigation innerhalb eines PDFs hinzuzufügen.

IronPDF bietet einen kostenlosen Testschlüssel, der es Benutzern ermöglicht, seine Funktionen und Fähigkeiten vor dem Kauf zu testen. Die IronPDF Java-Lizenz beginnt bei $799 und bietet eine kosteneffektive Lösung für Unternehmen und Einzelpersonen, die ihre PDF-Dateien absichern und verwalten möchten.

Häufig gestellte Fragen

Was sind die Hauptmerkmale der Java PDF-Editor-Bibliothek?

Die Java PDF-Editor-Bibliothek bietet umfassende Werkzeuge zum Bearbeiten und Erstellen von PDFs, einschließlich des Hinzufügens von Signaturen, HTML-Fußzeilen, Wasserzeichen und Anmerkungen. Sie unterstützt auch das Zusammenführen und Teilen von PDFs, das Anpassen von Größen und Ausrichtungen und das Konvertieren von PDFs in Bilder.

Wie kann ich eine PDF-Bibliothek in mein Java-Projekt integrieren?

Um eine PDF-Bibliothek wie IronPDF in Ihr Java-Projekt zu integrieren, laden Sie die Bibliothek von der offiziellen IronPDF-Website herunter und fügen Sie sie als Abhängigkeit in der Build-Konfiguration Ihres Projekts hinzu.

Wie kann ich die Struktur eines PDF-Dokuments in Java ändern?

Sie können die Struktur eines PDF-Dokuments in Java mit IronPDF ändern. Verwenden Sie Methoden wie prependPdf, copyPages und removePages, um Seiten hinzuzufügen, zu kopieren und zu löschen.

Ist es möglich, benutzerdefinierte Ränder und Metadaten für PDFs festzulegen?

Ja, mit IronPDF können Sie benutzerdefinierte Ränder festlegen und PDF-Metadaten, einschließlich Autor und Schlüsselwörter, mit der MetadataManager-Klasse ändern.

Kann ich PDF-Dokumente in Bildformate konvertieren?

Mit IronPDF können Sie PDF-Seiten in Bildformate umwandeln, indem Sie die Methode toBufferedImages verwenden, bei der Sie Bildabmessungen und DPI definieren können.

Wie benutzerdefinierte Wasserzeichen zu PDFs hinzufügen?

Um benutzerdefinierte Wasserzeichen zu PDF-Dateien hinzuzufügen, verwenden Sie die Methode applyWatermark von IronPDF. Sie können den Inhalt des Wasserzeichens, wie z. B. HTML, angeben und die Deckkraft anpassen.

Unterstützt IronPDF den Passwortschutz für PDF-Dokumente?

Ja, IronPDF unterstützt den Passwortschutz, wodurch Sie Dokumente sichern können, indem Sie unbefugten Zugriff und Änderungen verhindern.

Welche Werkzeuge stehen zur Verfügung, um mit PDF-Formularen in Java umzugehen?

IronPDF bietet eine FormManager-Klasse zur Erstellung, Bearbeitung und Ausfüllung von PDF-Formularen. Sie erleichtert das Setzen und Abrufen von Werten aus Formularfeldern.

Wie kann ich die Dokumentensicherheit mit digitalen Signaturen in PDFs sicherstellen?

IronPDF ermöglicht das sichere Signieren von PDF-Dokumenten mit X509Certificate2-Digitalsignaturen, um die Authentizität zu gewährleisten und unbefugte Änderungen zu verhindern.

Ist es möglich, PDF-Dateien zu komprimieren, um ihre Größe zu reduzieren?

IronPDF enthält Methoden zum Komprimieren von PDF-Dateien, was dazu beiträgt, Dateigrößen zu reduzieren und gleichzeitig die Dokumentenqualität zu erhalten.

Darrius Serrant
Full-Stack-Software-Ingenieur (WebOps)

Darrius Serrant hat einen Bachelor-Abschluss in Informatik von der University of Miami und arbeitet als Full-Stack-WebOps-Marketing-Ingenieur bei Iron Software. Seit seiner Jugend vom Programmieren angezogen, sah er die Informatik als sowohl mysteriös als auch zugänglich, was es zum perfekten Medium für Kreativität und Problemlösung ...

Weiterlesen