### Build ICEpdf Examples Source: https://github.com/pcorless/icepdf/blob/main/examples/readme.html Commands to build specific ICEpdf example modules using Maven or Gradle. ```shell ~$ mvn -pl org.icepdf.examples:png-capture -am package ``` ```shell ~$ gradle :examples:capture:png:assemble ``` -------------------------------- ### Build Annotation Creation Example with Gradle Source: https://github.com/pcorless/icepdf/wiki/Building-From-Source Use this command to assemble the annotation creation example. Ensure you are in the project's root directory. ```bash ~$ gradle :examples:annotation:creation:assemble ``` -------------------------------- ### Install Jars to Local Repository Source: https://github.com/pcorless/icepdf/wiki/Building-From-Source Commands to install compiled core and viewer jars into the local Maven repository. ```bash # Install icepdf-core.jar in local repository ~$ mvn -pl :icepdf-core install # Install icepdf-viwer.jar in local repository ~$ mvn -pl :icepdf-viewer install ``` -------------------------------- ### Load PDF from URL Source: https://github.com/pcorless/icepdf/wiki/Viewer-RI Use the -loadurl option to start the icepdf Viewer with a PDF file from a given URL. ```bash mvn exec:java -Dexec.mainClass=org.icepdf.ri.viewer.Launcher -loadurl http://www.examplesite.com/file.pdf ``` -------------------------------- ### Load Local PDF File Source: https://github.com/pcorless/icepdf/wiki/Viewer-RI Use the -loadfile option to start the icepdf Viewer with a specified local PDF file. ```bash mvn exec:java -Dexec.mainClass=org.icepdf.ri.viewer.Launcher -loadfile c:/examplepath/file.pdf ``` -------------------------------- ### Implement Custom Diagonal Watermark Source: https://context7.com/pcorless/icepdf/llms.txt Implement the WatermarkCallback interface to create a custom watermark. This example creates a diagonal, semi-transparent red text watermark. Ensure the necessary imports are included. ```java import org.icepdf.core.pobjects.Document; import org.icepdf.core.pobjects.Page; import org.icepdf.core.pobjects.PDimension; import org.icepdf.core.pobjects.graphics.WatermarkCallback; import org.icepdf.core.util.GraphicsRenderingHints; import javax.imageio.ImageIO; import java.awt.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.io.File; // Custom watermark implementation class DiagonalWatermark implements WatermarkCallback { private final String text; public DiagonalWatermark(String text) { this.text = text; } @Override public void paintWatermark(Graphics g, Page page, int renderHintType, int boundary, float rotation, float zoom) { Graphics2D g2 = (Graphics2D) g; Rectangle2D.Float mediaBox = page.getPageBoundary(boundary); // Apply 45-degree rotation transform AffineTransform af = new AffineTransform(); af.scale(1, -1); af.rotate(-45.0 * Math.PI / 180.0, mediaBox.getWidth() / 2.0, -mediaBox.getHeight() / 2.0); g2.transform(af); // Semi-transparent red text g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f)); g2.setColor(new Color(255, 0, 0)); g2.setFont(new Font("Dialog", Font.BOLD, 72)); FontMetrics fm = g2.getFontMetrics(); Rectangle2D textBounds = fm.getStringBounds(text, g2); int x = (int) (mediaBox.x + (mediaBox.width - textBounds.getWidth()) / 2.0); int y = -(int) (mediaBox.y - (mediaBox.height - textBounds.getHeight()) / 2.0); g2.drawString(text, x, y); } } ``` -------------------------------- ### Quickly Get Page Images Using getPageImage() Source: https://context7.com/pcorless/icepdf/llms.txt Uses the Document.getPageImage() method for a simplified way to capture a PDF page as an Image object. This method handles the rendering process internally. Specify the desired rendering hints and boundary for capture. ```java import org.icepdf.core.pobjects.Document; import org.icepdf.core.pobjects.Page; import org.icepdf.core.util.GraphicsRenderingHints; import javax.imageio.ImageIO; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; Document document = new Document(); try { document.setFile("/path/to/document.pdf"); float rotation = 0f; float zoom = 2.0f; // 200% for high quality // Use built-in getPageImage method Image pageImage = document.getPageImage( 0, // page number (0-based) GraphicsRenderingHints.SCREEN, // or PRINT for higher quality Page.BOUNDARY_CROPBOX, // page boundary rotation, zoom ); // Cast to BufferedImage and save BufferedImage bufferedImage = (BufferedImage) pageImage; ImageIO.write(bufferedImage, "png", new File("quick_capture.png")); bufferedImage.flush(); } catch (Exception e) { e.printStackTrace(); } finally { document.dispose(); } ``` -------------------------------- ### Build Entire Project Source: https://github.com/pcorless/icepdf/wiki/Building-From-Source Command to build the complete project hierarchy. ```bash # or with full group id. ~$ mvn package ``` -------------------------------- ### Create Link Annotations with Java Source: https://context7.com/pcorless/icepdf/llms.txt Demonstrates how to instantiate a document, add URI and GoTo link annotations to a specific page, and save the modified file. ```java import org.icepdf.core.pobjects.Document; import org.icepdf.core.pobjects.Page; import org.icepdf.core.pobjects.Destination; import org.icepdf.core.pobjects.Reference; import org.icepdf.core.pobjects.annotations.*; import org.icepdf.core.pobjects.actions.*; import org.icepdf.core.util.Library; import org.icepdf.core.util.updater.WriteMode; import java.awt.*; import java.io.*; import java.util.List; Document document = new Document(); try { document.setFile("/path/to/document.pdf"); Library library = document.getPageTree().getLibrary(); Page page = document.getPageTree().getPage(0); // Create a link annotation with URI action (opens web URL) Rectangle linkBounds = new Rectangle(100, 700, 200, 30); LinkAnnotation linkAnnotation = (LinkAnnotation) AnnotationFactory.buildAnnotation( library, Annotation.SUBTYPE_LINK, linkBounds); // Style the annotation BorderStyle borderStyle = new BorderStyle(); borderStyle.setBorderStyle(BorderStyle.BORDER_STYLE_SOLID); borderStyle.setStrokeWidth(2.0f); linkAnnotation.setBorderStyle(borderStyle); linkAnnotation.setColor(Color.BLUE); // Create URI action URIAction uriAction = (URIAction) ActionFactory.buildAction( library, ActionFactory.URI_ACTION); uriAction.setURI("https://github.com/pcorless/icepdf"); linkAnnotation.addAction(uriAction); // Add to page page.addAnnotation(linkAnnotation, true); // Create a GoTo action (navigates to page 5) LinkAnnotation gotoLink = (LinkAnnotation) AnnotationFactory.buildAnnotation( library, Annotation.SUBTYPE_LINK, new Rectangle(100, 650, 200, 30)); gotoLink.setColor(Color.GREEN); GoToAction gotoAction = (GoToAction) ActionFactory.buildAction( library, ActionFactory.GOTO_ACTION); Reference pageRef = document.getPageTree().getPageReference(4); // Page 5 (0-indexed) List destArray = Destination.destinationSyntax(pageRef, Destination.TYPE_FIT); gotoAction.setDestination(new Destination(library, destArray)); gotoLink.addAction(gotoAction); page.addAnnotation(gotoLink, true); // Save modified document try (FileOutputStream fos = new FileOutputStream("annotated_document.pdf"); BufferedOutputStream bos = new BufferedOutputStream(fos)) { document.saveToOutputStream(bos, WriteMode.INCREMENT_UPDATE); } } catch (Exception e) { e.printStackTrace(); } finally { document.dispose(); } ``` -------------------------------- ### Build ICEpdf with Gradle Source: https://github.com/pcorless/icepdf/blob/main/README.md Commands to assemble specific modules or the full distribution using Gradle. ```bash ~$ gradle :core:core-awt:assemble ``` ```bash ~$ gradle :viewer:viewer-awt:assemble ``` ```bash ~$ gradle :examples:annotation:creation:assemble ``` ```bash # defaultTasks allows for a call to just gradle ~$ gradle ``` -------------------------------- ### Create PKCS12 Keystore with OpenSSL Source: https://github.com/pcorless/icepdf/wiki/Viewer-RI Use OpenSSL to generate a private key and a self-signed certificate, then combine them into a PKCS12 file. This file can be used for digital signing in the Viewer RI. ```bash openssl req -newkey rsa:2048 -keyout my-private.key -x509 -days 365 -out my-cert.crt ``` ```bash openssl pkcs12 -inkey my-private.key -in my-cert.crt -export -out my-pkcs12-combo.pfx ``` -------------------------------- ### Build ICEpdf Viewer Jar with Gradle Source: https://github.com/pcorless/icepdf/wiki/Building-From-Source Use this command to assemble the ICEpdf viewer reference implementation jar. Ensure you are in the project's root directory. ```bash ~$ gradle :viewer:viewer-awt:assemble ``` -------------------------------- ### Launch icepdf Viewer with Maven Source: https://github.com/pcorless/icepdf/wiki/Viewer-RI Execute this command in your Maven project to launch the icepdf Viewer RI. ```bash mvn exec:java -Dexec.mainClass=org.icepdf.ri.viewer.Launcher ``` -------------------------------- ### Build ICEpdf with Maven Source: https://github.com/pcorless/icepdf/blob/main/README.md Commands to compile specific modules or the entire project hierarchy using Maven. ```bash # core module ~$ mvn -pl :icepdf-core package # viewer module, -am insures dependencies are build ~$ mvn -pl :icepdf-viewer -am package # Viewer jar with all dependences in one self executing jar ~$ mvn -pl :icepdf-viewer -am package -P assembly # examples module, -am insures dependencies are build ~$ mvn -pl :png-capture -am package # or with full group id. ~$ mvn -pl org.icepdf.examples:png-capture -am package ~$ java -jar icepdf-viewer-7.0.0-SNAPSHOT-jar-with-dependencies.jar # Whole project hierarchy can be built with or with full group id. ~$ mvn package ``` -------------------------------- ### Build ICEpdf Core Jar with Gradle Source: https://github.com/pcorless/icepdf/wiki/Building-From-Source Use this command to assemble the ICEpdf core library jar. Ensure you are in the project's root directory. ```bash ~$ gradle :core:core-awt:assemble ``` -------------------------------- ### View Maven Reactor Build Order Source: https://github.com/pcorless/icepdf/wiki/Building-From-Source Displays the order in which ICEpdf modules are built by the Maven reactor. ```text ------------------------------------------------------ Reactor Build Order: ICEpdf :: Core :: Core Swing/AWT ICEpdf :: Core ICEpdf :: Viewer : Swing/AWT Viewer RI ICEpdf :: Viewer ICEpdf :: Examples :: Annotation :: Callback ICEpdf :: Examples :: Annotation :: Creation ICEpdf :: Examples :: Annotation ICEpdf :: Examples :: Capture :: Listener ICEpdf :: Examples :: Capture :: PNG ICEpdf :: Examples :: Capture :: Portfolio ICEpdf :: Examples :: Capture :: TIFF ICEpdf :: Examples :: Capture :: Watermark ICEpdf :: Examples :: Capture ICEpdf :: Examples :: Component Swing/AWT ICEpdf :: Examples :: Extraction :: Images ICEpdf :: Examples :: Extraction :: Metadata ICEpdf :: Examples :: Extraction :: Text ICEpdf :: Examples :: Extraction ICEpdf :: Examples :: JavaFx ICEpdf :: Examples :: Loading Events ICEpdf :: Examples :: Print Services ICEpdf :: Examples :: Search :: Highlight ICEpdf :: Examples :: Search :: Headless ICEpdf :: Examples :: Search ICEpdf :: Examples :: Signatures ICEpdf :: Examples :: SVG Capture ICEpdf :: Examples ICEpdf ``` -------------------------------- ### Build ICEpdf Viewer Component Source: https://github.com/pcorless/icepdf/blob/main/README.md Illustrates how to build a complete PDF Viewer component panel using SwingViewBuilder and SwingController. Ensure necessary imports for Swing and ICEpdf classes. ```java String filePath = "somefilepath/myfile.pdf"; // initiate font caching for faster startups FontPropertiesManager.getInstance().loadOrReadSystemFonts(); // build a controller SwingController controller = new SwingController(); // Build a SwingViewFactory configured with the controller SwingViewBuilder factory = new SwingViewBuilder(controller); // Use the factory to build a JPanel that is pre-configured //with a complete, active Viewer UI. JPanel viewerComponentPanel = factory.buildViewerPanel(); // add copy keyboard command ComponentKeyBinding.install(controller, viewerComponentPanel); // add interactive mouse link annotation support via callback controller.getDocumentViewController().setAnnotationCallback( new org.icepdf.ri.common.MyAnnotationCallback( controller.getDocumentViewController())); // Create a JFrame to display the panel in JFrame window = new JFrame("Using the Viewer Component"); window.getContentPane().add(viewerComponentPanel); window.pack(); window.setVisible(true); // Open a PDF document to view controller.openDocument(filePath); ``` -------------------------------- ### Build ICEpdf Distribution Archives with Gradle Source: https://github.com/pcorless/icepdf/wiki/Building-From-Source Builds the distribution zip and tar archives for the ICEpdf project. The default task 'gradle' will execute predefined tasks including archive creation. Alternatively, specify individual tasks. ```bash # defaultTasks allows for a call to just gradle ~$ gradle # or one can use the full task list ~$ gradle projectReport, sourcesJar, genPomFileForCoreJarPub, genPomFileForViewerJarPub, osDistZip, osDistTar ``` -------------------------------- ### Rendering Configuration Properties Source: https://github.com/pcorless/icepdf/wiki/Configuration A collection of configuration keys used to set JVM rendering hints and page background behavior. ```APIDOC ## Rendering Configuration Properties ### Description These properties allow fine-tuning of the rendering engine, including color rendering, dithering, interpolation, and text anti-aliasing. ### Parameters #### Configuration Keys - **org.icepdf.core.target.background** (string) - Sets whether a Page will draw a background fill color. Values: VALUE_DRAW_WHITE_BACKGROUND (default), VALUE_DRAW_NO_BACKGROUND. - **org.icepdf.core.target.colorRender** (string) - Sets the JVM's color render rendering hint. Values: VALUE_COLOR_RENDER_QUALITY (default), VALUE_COLOR_RENDER_DEFAULT. - **org.icepdf.core.target.dither** (string) - Sets the JVM's dither rendering hint. Values: VALUE_DITHER_ENABLE (default), VALUE_DITHER_DEFAULT, VALUE_DITHER_DISABLE. - **org.icepdf.core.target.fractionalmetrics** (string) - Sets the JVM's fractional metrics rendering hint. Values: VALUE_FRACTIONALMETRICS_ON (default), VALUE_FRACTIONALMETRICS_DEFAULT, VALUE_FRACTIONALMETRICS_OFF. - **org.icepdf.core.target.interpolation** (string) - Sets the JVM's interpolation rendering hint. Values: VALUE_INTERPOLATION_BICUBIC (default), VALUE_INTERPOLATION_BILINEAR, VALUE_INTERPOLATION_NEAREST_NEIGHBOR. - **org.icepdf.core.target.render** (string) - Sets the JVM's render rendering hint. Values: VALUE_RENDER_QUALITY (default), VALUE_RENDER_DEFAULT, VALUE_RENDER_SPEED. - **org.icepdf.core.target.stroke** (string) - Sets the JVM's stroke rendering hint. Values: VALUE_STROKE_NORMALIZE (default), VALUE_STROKE_PURE, VALUE_STROKE_DEFAULT. - **org.icepdf.core.target.textAntiAliasing** (string) - Sets the Font rendering engine's antialiasing rendering hint. Values: true (default), false. ``` -------------------------------- ### Apply Watermark and Render PDF Pages Source: https://context7.com/pcorless/icepdf/llms.txt Load a PDF document, attach a custom watermark callback, and then render each page to an image file. Ensure the document path is correct and handle potential exceptions. The document must be disposed of in a finally block. ```java // Usage Document document = new Document(); try { document.setFile("/path/to/document.pdf"); // Attach watermark callback document.setWatermarkCallback(new DiagonalWatermark("CONFIDENTIAL")); // Render pages - watermark will be applied automatically for (int pageNum = 0; pageNum < document.getNumberOfPages(); pageNum++) { Page page = document.getPageTree().getPage(pageNum); page.init(); PDimension sz = page.getSize(Page.BOUNDARY_CROPBOX, 0f, 1f); BufferedImage image = new BufferedImage( (int) sz.getWidth(), (int) sz.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); page.paint(g, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX, 0f, 1f); g.dispose(); ImageIO.write(image, "png", new File("watermarked_page_" + pageNum + ".png")); image.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { document.dispose(); } ``` -------------------------------- ### Build Specific ICEpdf Modules Source: https://github.com/pcorless/icepdf/wiki/Building-From-Source Commands to build individual modules using Maven, including dependency resolution with the -am flag. ```bash # core module ~$ mvn -pl :icepdf-core package # viewer module, -am insures dependencies are build ~$ mvn -pl :icepdf-viewer -am package # examples module, -am insures dependencies are build ~$ mvn -pl :png-capture -am package # or with full group id. ~$ mvn -pl org.icepdf.os.examples:png-capture -am package ``` -------------------------------- ### Load PDF from File Path Source: https://context7.com/pcorless/icepdf/llms.txt Uses the setFile method to open a local PDF file. Always call dispose() to release resources after processing. ```java import org.icepdf.core.pobjects.Document; import org.icepdf.core.exceptions.PDFSecurityException; import java.io.IOException; // Create a new Document instance Document document = new Document(); try { // Load PDF from file path document.setFile("/path/to/document.pdf"); // Get document information int pageCount = document.getNumberOfPages(); System.out.println("Document has " + pageCount + " pages"); // Access document metadata PInfo info = document.getInfo(); if (info != null) { System.out.println("Title: " + info.getTitle()); System.out.println("Author: " + info.getAuthor()); } } catch (PDFSecurityException e) { System.err.println("Error: Document is encrypted - " + e.getMessage()); } catch (IOException e) { System.err.println("Error loading document: " + e.getMessage()); } finally { // Always dispose when done document.dispose(); } ``` -------------------------------- ### Rendering Quality Properties Source: https://github.com/pcorless/icepdf/wiki/Configuration Advanced rendering hints for AWT font loading, alpha transparency, and anti-aliasing. ```APIDOC ## Rendering Quality Properties ### Description Controls rendering quality and performance. Note: Call org.icepdf.core.util.GraphicsRenderingHints.reset() for dynamic changes to take effect. ### Properties - **org.icepdf.core.awtFontLoading** (boolean) - Use java.awt.Font for embedded fonts. Default: false. - **org.icepdf.core.paint.disableAlpha** (boolean) - Suspend alpha/transparency painting. Dynamic: Yes. - **org.icepdf.core.paint.disableClipping** (boolean) - Suspend clipping. Dynamic: Yes. - **org.icepdf.core.target.alphaInterpolation** (string) - JVM alpha interpolation hint. Dynamic: Yes. - **org.icepdf.core.target.antiAliasing** (string) - JVM anti-aliasing hint. Dynamic: Yes. ``` -------------------------------- ### Clone the ICEpdf Repository Source: https://github.com/pcorless/icepdf/blob/main/README.md Use git to obtain a local copy of the source code. ```bash $ git clone https://github.com/pcorless/icepdf.git $ cd icepdf ``` -------------------------------- ### View and Buffer Configuration Source: https://github.com/pcorless/icepdf/wiki/Configuration Properties related to viewport buffering, refresh intervals, and interactive annotation settings. ```APIDOC ## View and Buffer Properties ### Description These properties control the behavior of the view buffer, including sizing, refresh rates, and interactive annotation handling. ### Properties - **org.icepdf.core.views.buffersize.horizontal** (string) - Sets the horizontal ratio for screen buffer. Default: 1.0. - **org.icepdf.core.views.refreshfrequency** (integer) - Interval in ms between view buffer refreshes. Default: 250. - **org.icepdf.core.views.dirtytimer.interval** (integer) - Interval in ms for dirty buffer checks. Default: 5. - **org.icepdf.core.annotations.interactive.enabled** (boolean) - Enables link annotation activation via mouse. Default: true. ``` -------------------------------- ### Print PDF Documents using Java Print Services Source: https://context7.com/pcorless/icepdf/llms.txt Configures headless mode and utilizes PrintHelper to send a PDF document to a selected printer with specific paper and quality settings. ```java import org.icepdf.core.pobjects.Document; import org.icepdf.core.util.Defs; import org.icepdf.ri.common.print.PrintHelper; import org.icepdf.ri.common.print.PrintHelperFactory; import org.icepdf.ri.common.print.PrintHelperFactoryImpl; import javax.print.*; import javax.print.attribute.standard.*; // Configure headless mode for server environments Defs.setProperty("java.awt.headless", "true"); Defs.setProperty("org.icepdf.core.print.disableAlpha", "true"); PrintHelperFactory printHelperFactory = PrintHelperFactoryImpl.getInstance(); Document document = new Document(); try { document.setFile("/path/to/document.pdf"); // Find available printers PrintService[] services = PrintServiceLookup.lookupPrintServices( DocFlavor.SERVICE_FORMATTED.PAGEABLE, null); if (services.length == 0) { System.err.println("No printers found"); return; } // Select default printer (or let user choose) PrintService selectedPrinter = PrintServiceLookup.lookupDefaultPrintService(); System.out.println("Printing to: " + selectedPrinter.getName()); // Create print helper with paper size and quality settings PrintHelper printHelper = printHelperFactory.createPrintHelper( null, // parent component (null for headless) document.getPageTree(), 0f, // rotation MediaSizeName.NA_LETTER, // paper size (Letter, A4, Legal, etc.) PrintQuality.NORMAL // print quality ); // Configure print job: all pages, 1 copy, scale to fit printHelper.setupPrintService( selectedPrinter, 0, // first page (0 = first) 0, // last page (0 = all pages) 1, // copies true // shrink to fit ); // Execute print printHelper.print(); System.out.println("Print job submitted successfully"); } catch (PrintException e) { System.err.println("Print error: " + e.getMessage()); } catch (Exception e) { e.printStackTrace(); } finally { document.dispose(); } ``` -------------------------------- ### Implementing SecurityCallback for Password Retrieval Source: https://github.com/pcorless/icepdf/wiki/Viewer-RI Use this interface to provide a custom mechanism for retrieving passwords when opening encrypted PDF documents. ```java // new document instance Document document = new Document(); // setup a security callback before opening an encrypted document. document.setSecurityCallback(new SecurityCallback(){ public String requestPassword(Document document) { System.out.println( "This document is Encrypted please type the document password:"); String input = ""; // get users password try { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); input = stdin.readLine(); } catch (IOException e) {} return input; } }); // finally open the document ``` -------------------------------- ### Build Embeddable PDF Viewer Component Source: https://context7.com/pcorless/icepdf/llms.txt Creates a Swing-based PDF viewer component that can be embedded into desktop applications. Requires a file path as a command-line argument and configures viewer properties like zoom level. ```java import org.icepdf.ri.common.SwingController; import org.icepdf.ri.common.SwingViewBuilder; import org.icepdf.ri.common.MyAnnotationCallback; import org.icepdf.ri.util.FontPropertiesManager; import org.icepdf.ri.util.ViewerPropertiesManager; import javax.swing.*; public class PdfViewerExample { public static void main(String[] args) { String filePath = args[0]; SwingUtilities.invokeLater(() -> { // Initialize font cache FontPropertiesManager.getInstance().loadOrReadSystemFonts(); // Create controller SwingController controller = new SwingController(); controller.setIsEmbeddedComponent(true); // Configure viewer properties ViewerPropertiesManager properties = ViewerPropertiesManager.getInstance(); properties.getPreferences().putFloat( ViewerPropertiesManager.PROPERTY_DEFAULT_ZOOM_LEVEL, 1.25f); // Build viewer panel SwingViewBuilder factory = new SwingViewBuilder(controller, properties); JPanel viewerPanel = factory.buildViewerPanel(); // Enable annotation callbacks for interactive links controller.getDocumentViewController().setAnnotationCallback( new MyAnnotationCallback(controller.getDocumentViewController())); // Create frame JFrame frame = new JFrame("ICEpdf Viewer"); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.getContentPane().add(viewerPanel); // Open document controller.openDocument(filePath); // Add cleanup listener frame.addWindowListener(controller); // Display frame.pack(); frame.setSize(1024, 768); frame.setVisible(true); }); } } ``` -------------------------------- ### Handle Password-Protected Documents in Java Source: https://context7.com/pcorless/icepdf/llms.txt Implements the SecurityCallback interface to provide passwords for encrypted PDFs, supporting both GUI prompts and automated headless processing. ```java import org.icepdf.core.SecurityCallback; import org.icepdf.core.pobjects.Document; import org.icepdf.core.exceptions.PDFSecurityException; import javax.swing.JOptionPane; // Implement security callback for password prompting class PasswordCallback implements SecurityCallback { @Override public String requestPassword(Document document) { // In a GUI application, show password dialog return JOptionPane.showInputDialog(null, "Enter password for: " + document.getDocumentOrigin(), "Password Required", JOptionPane.QUESTION_MESSAGE); } } // Headless password callback for automated processing class AutomatedPasswordCallback implements SecurityCallback { private final String password; public AutomatedPasswordCallback(String password) { this.password = password; } @Override public String requestPassword(Document document) { return password; } } // Usage Document document = new Document(); document.setSecurityCallback(new AutomatedPasswordCallback("secret123")); try { document.setFile("/path/to/encrypted.pdf"); System.out.println("Document opened successfully"); System.out.println("Pages: " + document.getNumberOfPages()); } catch (PDFSecurityException e) { System.err.println("Failed to decrypt: " + e.getMessage()); } catch (Exception e) { e.printStackTrace(); } finally { document.dispose(); } ``` -------------------------------- ### Imaging and Security Properties Source: https://github.com/pcorless/icepdf/wiki/Configuration Configuration for image rendering behavior and security provider settings. ```APIDOC ## Imaging and Security Properties ### Security - **rg.icepdf.core.security.jceProvider** (string) - Classname of the JCE security provider. Default: org.bouncycastle.jce.provider.BouncyCastleProvider ### Imaging - **org.icepdf.core.imageReference** (string) - Default image reference type ('default', 'scaled', 'mipmap'). Default: 'default' - **org.icepdf.core.ccittfax.jai** (boolean) - Use JAI for CCITTFAX decoding. Default: false - **org.icepdf.core.imageProxy** (boolean) - Load images on separate thread. Default: true ``` -------------------------------- ### Application Configuration Properties Source: https://github.com/pcorless/icepdf/wiki/Viewer-RI Configuration properties for controlling the visibility of various UI components in the ICEpdf viewer. ```APIDOC ## Application Configuration Properties ### Description These properties control the visibility of toolbars, utility panes, and status bar components within the ICEpdf viewer. ### Properties - **application.toolbar.show.tool** (boolean) - Show the tools toolbar and children. Default: true. - **application.toolbar.show.annotation** (boolean) - Show the annotation toolbar and children. Default: true. - **application.utilitypane.show.bookmarks** (boolean) - Show the document outline panel tab. Default: true. - **application.utilitypane.show.search** (boolean) - Show the search panel tab. Default: true. - **application.utilitypane.show.annotation** (boolean) - Show the annotation properties pane. Default: true. - **application.utilitypane.show.thumbs** (boolean) - Show the thumbnail view pane. Default: true. - **application.utilitypane.show.layers** (boolean) - Show the layers view pane. Default: true. - **application.statusbar** (boolean) - Show the status bar and child component. Default: true. - **application.statusbar.show.statuslabel** (boolean) - Show the status label. Default: true. - **application.statusbar.show.viewmode** (boolean) - Show the view mode controls. Default: true. ``` -------------------------------- ### SwingViewBuilder GUI Construction Source: https://github.com/pcorless/icepdf/wiki/Viewer-RI Overview of the SwingViewBuilder class used for constructing pre-configured GUI components for PDF viewing. ```APIDOC ## SwingViewBuilder ### Description The `org.icepdf.ri.common.SwingViewBuilder` class constructs GUI components pre-configured to work with `org.icepdf.ri.common.SwingController`. ### Key Methods - **buildViewerFrame()**: High-level entry point to construct a complete PDF Viewer frame. - **buildViewerPanel()**: High-level entry point to construct a complete PDF Viewer panel. - **buildCompleteMenubar()**: Constructs a complete application menu bar. - **buildFileMenu()**: Constructs the File menu (Open, Close, Save As, etc.). ### Customization Strategies 1. **Modify/Copy Source**: Directly modify the source or copy the class to a new implementation. 2. **Subclassing**: Extend `SwingViewBuilder` and override specific `build...` methods to customize components while inheriting future library updates. ``` -------------------------------- ### Capture PDF Page as SVG Source: https://github.com/pcorless/icepdf/blob/main/README.md Demonstrates how to render a specific page of a PDF document into an SVG file using ICEpdf's Document class and Batik's SVGGraphics2D. Requires setting up DOMImplementation and SVGGenerator. ```java String filePath = "somefilepath/myfile.pdf"; Document document = new Document(); document.setFile(filePath); // Get a DOMImplementation DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // Create an instance of org.w3c.dom.Document org.w3c.dom.Document svgDocument = domImpl.createDocument(null,"svg",null); // Create an instance of the SVG Generator SVGGraphics2D svgGenerator = new SVGGraphics2D(svgDocument); float userRotation = 0; float userZoom = 1; int pageNumber = 0; PDimension pdfDimension=document.getPageDimension(pageNumber,userRotation,userZoom); svgGenerator.setSVGCanvasSize(pdfDimension.toDimension()); // paint the page to the Batik svgGenerator graphics context. document.paintPage(pageNumber,svgGenerator, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX, userRotation, userZoom); File file = new File("svgCapture_"+pageNumber+".svg"); // Finally, stream the SVG using UTF-8character byte encoding Writer fileWriter = new OutputStreamWriter(new FileOutputStream(file),StandardCharsets.UTF_8); // Enable SVG CSS style attribute boolean SVG_CSS = true; svgGenerator.stream(fileWriter,SVG_CSS); ``` -------------------------------- ### Configuring ICEpdf System Properties Source: https://github.com/pcorless/icepdf/wiki/Configuration Methods for setting ICEpdf configuration properties programmatically or via the command line. ```APIDOC ## System Properties Configuration ### Description ICEpdf properties can be set programmatically within the application or via command-line arguments at startup. ### Programmatic Usage ```java System.getProperties().put("org.icepdf.core.imageReference", "scaled"); ``` ### Command Line Usage ```bash java -Dorg.icepdf.core.imageReference=scaled -jar your-app.jar ``` ``` -------------------------------- ### Render PDF Pages to PNG Images Source: https://context7.com/pcorless/icepdf/llms.txt Renders each page of a PDF document to a PNG image file. Ensure the PDF file path is correct and the output directory is writable. Supports multi-threaded processing. ```java import org.icepdf.core.pobjects.Document; import org.icepdf.core.pobjects.Page; import org.icepdf.core.pobjects.PDimension; import org.icepdf.core.util.GraphicsRenderingHints; import org.icepdf.ri.util.FontPropertiesManager; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; // Initialize font cache for better rendering FontPropertiesManager.getInstance().loadOrReadSystemFonts(); Document document = new Document(); try { document.setFile("/path/to/document.pdf"); float rotation = 0f; // No rotation float scale = 1.5f; // 150% zoom for higher quality for (int pageNumber = 0; pageNumber < document.getNumberOfPages(); pageNumber++) { Page page = document.getPageTree().getPage(pageNumber); page.init(); // Calculate page dimensions PDimension sz = page.getSize(Page.BOUNDARY_CROPBOX, rotation, scale); int pageWidth = (int) sz.getWidth(); int pageHeight = (int) sz.getHeight(); // Create image buffer BufferedImage image = new BufferedImage(pageWidth, pageHeight, BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); // Render page to graphics context page.paint(g, GraphicsRenderingHints.PRINT, Page.BOUNDARY_CROPBOX, rotation, scale); g.dispose(); // Save to file File outputFile = new File("page_" + pageNumber + ".png"); ImageIO.write(image, "png", outputFile); System.out.println("Captured page " + pageNumber); image.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { document.dispose(); } ``` -------------------------------- ### Search Text in PDF Documents with Highlighting Source: https://context7.com/pcorless/icepdf/llms.txt Utilize DocumentSearchController to find terms across pages and generate highlighted images of matching pages. Remember to clear highlights when finished. ```java import org.icepdf.core.pobjects.Document; import org.icepdf.core.pobjects.Page; import org.icepdf.core.pobjects.PDimension; import org.icepdf.core.search.DocumentSearchController; import org.icepdf.core.util.GraphicsRenderingHints; import org.icepdf.ri.common.search.DocumentSearchControllerImpl; import org.icepdf.core.pobjects.graphics.text.WordText; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; Document document = new Document(); try { document.setFile("/path/to/document.pdf"); // Create search controller DocumentSearchController searchController = new DocumentSearchControllerImpl(document); // Add search terms (case sensitive, whole word) searchController.addSearchTerm("PDF", true, false); searchController.addSearchTerm("document", false, false); float scale = 1.0f; float rotation = 0f; for (int pageNum = 0; pageNum < document.getNumberOfPages(); pageNum++) { Page page = document.getPageTree().getPage(pageNum); page.init(); // Search and get matching words ArrayList foundWords = searchController.searchPage(pageNum); if (foundWords != null && !foundWords.isEmpty()) { System.out.println("Page " + pageNum + ": Found " + foundWords.size() + " matches"); // Capture page with search highlighting PDimension sz = page.getSize(Page.BOUNDARY_CROPBOX, rotation, scale); BufferedImage image = new BufferedImage( (int) sz.getWidth(), (int) sz.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); // Paint with highlighting enabled (last two params: true, true) page.paint(g, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale, true, true); g.dispose(); ImageIO.write(image, "png", new File("search_result_page_" + pageNum + ".png")); image.flush(); } } // Clear highlights when done searchController.clearAllSearchHighlight(); } catch (Exception e) { e.printStackTrace(); } finally { document.dispose(); } ``` -------------------------------- ### Save Modified Documents in Java Source: https://context7.com/pcorless/icepdf/llms.txt Demonstrates saving PDF modifications using either incremental updates to preserve signatures or full updates for redactions. ```java import org.icepdf.core.pobjects.Document; import org.icepdf.core.util.updater.WriteMode; import java.io.*; Document document = new Document(); try { document.setFile("/path/to/document.pdf"); // Make modifications (annotations, form fields, etc.) // ... // Save with incremental update (appends changes, preserves signatures) File incrementalOutput = new File("document_incremental.pdf"); try (FileOutputStream fos = new FileOutputStream(incrementalOutput); BufferedOutputStream bos = new BufferedOutputStream(fos, 8192)) { long bytesWritten = document.saveToOutputStream(bos, WriteMode.INCREMENT_UPDATE); System.out.println("Incremental save: " + bytesWritten + " bytes"); } // OR save with full update (rewrites entire document, applies redactions) File fullOutput = new File("document_full.pdf"); try (FileOutputStream fos = new FileOutputStream(fullOutput); BufferedOutputStream bos = new BufferedOutputStream(fos, 8192)) { long bytesWritten = document.writeToOutputStream(bos, WriteMode.FULL_UPDATE); System.out.println("Full update save: " + bytesWritten + " bytes"); } } catch (Exception e) { e.printStackTrace(); } finally { document.dispose(); } ``` -------------------------------- ### Load PDF from URL Source: https://context7.com/pcorless/icepdf/llms.txt Loads a PDF document from a remote URL. The library automatically handles downloading and caching to a temporary directory. ```java import org.icepdf.core.pobjects.Document; import java.net.URL; Document document = new Document(); try { // Load from URL - file is cached to temp directory by default URL pdfUrl = new URL("https://example.com/document.pdf"); document.setUrl(pdfUrl); System.out.println("Pages: " + document.getNumberOfPages()); System.out.println("Location: " + document.getDocumentLocation()); } catch (Exception e) { e.printStackTrace(); } finally { document.dispose(); } ``` -------------------------------- ### Set System Property via Command Line Source: https://github.com/pcorless/icepdf/wiki/Configuration Configure ICEpdf system properties when launching your Java application from the command line using the -D flag. This is useful for environment-specific settings. ```bash java -Dorg.icepdf.core.imageReference=scaled ... ``` -------------------------------- ### Page Decorator Properties Source: https://github.com/pcorless/icepdf/wiki/Configuration Configuration for visual elements of the page view, including colors and threading modes. ```APIDOC ## Page Decorator Properties ### Description Defines the visual appearance of the PDF page view and the threading model for page loading. ### Properties - **org.icepdf.core.views.page.paper.color** (string) - Default paper color. Default: #FFFFFF. - **org.icepdf.core.views.page.border.color** (string) - Default border color. Default: #000000. - **org.icepdf.core.views.page.shadow.color** (string) - Default shadow color. Default: #333333. - **org.icepdf.core.views.background.color** (string) - Default background color. Default: #808080. - **org.icepdf.core.views.page.proxy** (boolean) - Enables multi-threaded page loading. Default: true. ``` -------------------------------- ### Create and Apply Redaction Annotations in Java Source: https://context7.com/pcorless/icepdf/llms.txt Uses DocumentSearchController to locate text and AnnotationFactory to generate redaction annotations. Requires a full update write mode to ensure sensitive content is permanently removed. ```java import org.icepdf.core.pobjects.Document; import org.icepdf.core.pobjects.Page; import org.icepdf.core.pobjects.annotations.*; import org.icepdf.core.pobjects.graphics.text.WordText; import org.icepdf.core.search.DocumentSearchController; import org.icepdf.core.util.updater.WriteMode; import org.icepdf.ri.common.search.DocumentSearchControllerImpl; import org.icepdf.ri.util.FontPropertiesManager; import java.awt.*; import java.awt.geom.*; import java.io.*; import java.util.*; FontPropertiesManager.getInstance().loadOrReadSystemFonts(); Document document = new Document(); try { document.setFile("/path/to/document.pdf"); // Search for sensitive content DocumentSearchController searchController = new DocumentSearchControllerImpl(document); searchController.addSearchTerm("confidential", false, false); searchController.addSearchTerm("secret", false, false); for (int pageNum = 0; pageNum < document.getNumberOfPages(); pageNum++) { Page page = document.getPageTree().getPage(pageNum); page.init(); ArrayList foundWords = searchController.searchPage(pageNum); if (foundWords != null) { for (WordText word : foundWords) { Rectangle bounds = word.getBounds().getBounds(); // Create redaction annotation RedactionAnnotation redaction = (RedactionAnnotation) AnnotationFactory.buildAnnotation( document.getPageTree().getLibrary(), Annotation.SUBTYPE_REDACT, bounds); redaction.setColor(Color.BLACK); redaction.setMarkupBounds(new ArrayList<>(Collections.singletonList(bounds))); redaction.setMarkupPath(new GeneralPath(bounds)); redaction.setBBox(bounds); redaction.resetAppearanceStream(new AffineTransform()); page.addAnnotation(redaction, true); } } } // Export with FULL_UPDATE to burn redactions into content streams // This permanently removes the underlying text try (FileOutputStream fos = new FileOutputStream("redacted_document.pdf"); BufferedOutputStream bos = new BufferedOutputStream(fos, 8192)) { document.writeToOutputStream(bos, WriteMode.FULL_UPDATE); } System.out.println("Redacted document saved successfully"); } catch (Exception e) { e.printStackTrace(); } finally { document.dispose(); } ``` -------------------------------- ### Annotation Properties Source: https://github.com/pcorless/icepdf/wiki/Configuration Configuration properties for default colors and font settings for various PDF annotations. ```APIDOC ## Annotation Properties - **org.icepdf.core.views.page.annotation.textmarkup.highlight.color** (string) - Default: #ffff00 - **org.icepdf.core.views.page.annotation.strikeOut.highlight.color** (string) - Default: #ff0000 - **org.icepdf.core.views.page.annotation.strikeOut.underline.color** (string) - Default: #00ff00 - **org.icepdf.core.views.page.annotation.ink.line.color** (string) - Default: #00ff00 - **org.icepdf.core.views.page.annotation.line.stroke.color** (string) - Default: #ff0000 - **org.icepdf.core.views.page.annotation.line.fill.color** (string) - Default: #ffffff - **org.icepdf.core.views.page.annotation.squareCircle.fill.color** (string) - Default: #000000 - **org.icepdf.core.views.page.annotation.squareCircle.stroke.color** (string) - Default: #ff0000 - **org.icepdf.core.views.page.annotation.text.fill.color** (string) - Default: #ffff00 - **org.icepdf.core.views.page.annotation.freeText.font.color** (string) - Default: #000000 - **org.icepdf.core.views.page.annotation.freeText.fill.color** (string) - Default: #ffffff - **org.icepdf.core.views.page.annotation.freeText.font.size** (int) - Default: 24 - **org.icepdf.core.views.page.annotation.outline.color** (string) - Default: #CCCCCC - **org.icepdf.core.views.page.annotation.outlineResize.color** (string) - Default: #ffffff ``` -------------------------------- ### Add Encryption Support Dependencies (XML) Source: https://github.com/pcorless/icepdf/wiki/Configuration Include these dependencies in your Maven project to enable encryption support in ICEpdf. ```xml org.bouncycastle bcprov-jdk15on org.bouncycastle bcprov-ext-jdk15on org.bouncycastle bcpkix-jdk15on ``` -------------------------------- ### Add JPEG2000 Image Support Dependencies (XML) Source: https://github.com/pcorless/icepdf/wiki/Configuration Include these Maven dependencies to enable JPEG2000 image format support within ICEpdf. ```xml org.apache.pdfbox jbig2-imageio com.github.jai-imageio jai-imageio-jpeg2000 ``` -------------------------------- ### Configure ICEpdf Maven Dependencies Source: https://github.com/pcorless/icepdf/blob/main/README.md Include these dependencies in your pom.xml to use the ICEpdf core, viewer, and optional font embedding components. ```xml com.github.pcorless.icepdf icepdf-core 7.4.0 com.github.pcorless.icepdf icepdf-viewer 7.4.0 com.github.pcorless.icepdf icepdf-fonts 7.4.0 ``` -------------------------------- ### Configuring AnnotationCallback for SwingController Source: https://github.com/pcorless/icepdf/wiki/Viewer-RI Configure the SwingController with an AnnotationCallback to enable user interaction with link annotations in a PDF document. ```java // build a component controller SwingController controller = new SwingController(); SwingViewBuilder factory = new SwingViewBuilder(controller); JPanel viewerComponentPanel = factory.buildViewerPanel(); // add interactive mouse link annotation support via callback controller.getDocumentViewController().setAnnotationCallback( new org.icepdf.ri.common.MyAnnotationCallback( controller.getDocumentViewController())); JFrame applicationFrame = new JFrame(); applicationFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); applicationFrame.getContentPane().add(viewerComponentPanel); // Now that the GUI is all in place, we can try openning a PDF controller.openDocument(filePath); ``` -------------------------------- ### Add TIFF/CCITTFAX Image Support Dependency (XML) Source: https://github.com/pcorless/icepdf/wiki/Configuration Add this Maven dependency to enable support for TIFF and CCITTFAX image formats in ICEpdf. ```xml com.twelvemonkeys.imageio imageio-tiff ``` -------------------------------- ### Load PDF from InputStream or Byte Array Source: https://context7.com/pcorless/icepdf/llms.txt Supports loading PDF data from memory or streams, useful for database BLOBs or dynamically generated content. ```java import org.icepdf.core.pobjects.Document; import java.io.InputStream; import java.io.FileInputStream; Document document = new Document(); try { // From InputStream InputStream inputStream = new FileInputStream("/path/to/document.pdf"); document.setInputStream(inputStream, "memory-document.pdf"); // OR from byte array byte[] pdfData = getPdfBytesFromDatabase(); document.setByteArray(pdfData, 0, pdfData.length, "database-document.pdf"); System.out.println("Loaded document with " + document.getNumberOfPages() + " pages"); } catch (Exception e) { e.printStackTrace(); } finally { document.dispose(); } ```