### Hello World Example Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/INDEX.md A basic example demonstrating how to create a simple PDF document with text using Spire.PDF for Java. ```APIDOC ## Hello World Example This example demonstrates the fundamental steps to create a PDF document, add a page, draw text on it, and save the document. ### Purpose To provide a starting point for users to quickly generate a PDF file. ### Code Example ```java import com.spire.pdf.*; import com.spire.pdf.graphics.*; import java.awt.*; PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.getPages().add(); PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 30f); PdfBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black)); page.getCanvas().drawString("Hello, World!", font, brush, 10, 10); doc.saveToFile("output.pdf", FileFormat.PDF); doc.close(); ``` ### Key Classes Used - `PdfDocument`: Represents the PDF document. - `PdfPageBase`: Represents a single page within the document. - `PdfFont`: Defines the font properties for text. - `PdfBrush`: Defines the color and style for drawing. - `PdfCanvas`: Provides methods for drawing on a page. ``` -------------------------------- ### Complete PDF Document Configuration Example Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/configuration.md Provides a comprehensive example of configuring a PDF document, including setting metadata, file information, page margins and size, form permissions, and security policies before saving. This serves as a template for setting up new PDF documents. ```java public void configurePdfDocument() { PdfDocument doc = new PdfDocument(); // Document metadata PdfDocumentInformation info = doc.getDocumentInformation(); info.setTitle("Sample Report"); info.setAuthor("Software Team"); info.setSubject("Configuration Example"); // File settings PdfFileInfo fileInfo = doc.getFileInfo(); fileInfo.setVersion(PdfVersion.Version_1_5); // Page configuration PdfMargins margins = new PdfMargins(); margins.setTop(36); margins.setBottom(36); margins.setLeft(54); margins.setRight(54); PdfPageBase page = doc.getPages().add(PdfPageSize.Letter, margins); // Form configuration doc.setAllowCreateForm(true); // Security PdfPasswordSecurityPolicy policy = new PdfPasswordSecurityPolicy("user", "owner"); doc.encrypt(policy); // Save doc.saveToFile("configured.pdf", FileFormat.PDF); doc.close(); } ``` -------------------------------- ### Example: Creating Bookmark Hierarchy Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfBookmark.md Demonstrates how to create a hierarchical bookmark structure with nested child bookmarks and set their navigation destinations. ```java PdfDocument doc = new PdfDocument(); PdfPageBase page1 = doc.getPages().add(); PdfPageBase page2 = doc.getPages().add(); PdfBookmark chapter1 = doc.getBookmarks().add("Chapter 1"); PdfBookmark section1 = chapter1.add("Section 1.1"); PdfBookmark section2 = chapter1.add("Section 1.2"); // Set navigation destinations chapter1.setAction(new PdfGoToAction(new PdfDestination(page1))); section1.setAction(new PdfGoToAction(new PdfDestination(page2))); ``` -------------------------------- ### Example: Creating a Simple PDF Outline Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfBookmark.md Demonstrates creating a PDF document with multiple pages and adding simple, top-level bookmarks that navigate to each page. ```java PdfDocument doc = new PdfDocument(); // Create pages with content PdfPageBase page1 = doc.getPages().add(); PdfPageBase page2 = doc.getPages().add(); PdfPageBase page3 = doc.getPages().add(); // Add content to pages PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 24f); PdfBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK)); page1.getCanvas().drawString("Chapter 1: Introduction", font, brush, 50, 50); page2.getCanvas().drawString("Chapter 2: Main Content", font, brush, 50, 50); page3.getCanvas().drawString("Chapter 3: Conclusion", font, brush, 50, 50); // Create bookmarks PdfBookmark chapter1 = doc.getBookmarks().add("Chapter 1"); PdfBookmark chapter2 = doc.getBookmarks().add("Chapter 2"); PdfBookmark chapter3 = doc.getBookmarks().add("Chapter 3"); // Set navigation destinations chapter1.setAction(new PdfGoToAction(new PdfDestination(page1))); chapter2.setAction(new PdfGoToAction(new PdfDestination(page2))); chapter3.setAction(new PdfGoToAction(new PdfDestination(page3))); doc.saveToFile("bookmarks.pdf", FileFormat.PDF); doc.close(); ``` -------------------------------- ### Regular Expression Search Example Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfTextFinder.md Illustrates how to use regular expressions for advanced text pattern matching. This example finds email addresses within the document. ```java PdfDocument doc = new PdfDocument(); doc.loadFromFile("document.pdf"); PdfPageBase page = doc.getPages().get(0); PdfTextFinder finder = new PdfTextFinder(page); // Configure regex pattern matching PdfTextFindOptions options = finder.getOptions(); options.setTextFindParameter(EnumSet.of(TextFindParameter.Regex)); // Find email addresses List results = finder.findAll(); for (PdfTextFind result : results) { System.out.println("Email found: " + result.getText()); } doc.close(); ``` -------------------------------- ### Create a New PdfDocument Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfDocument.md Instantiates a new, empty PDF document. This is the starting point for creating a PDF from scratch. ```java public PdfDocument() ``` ```java PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.getPages().add(); doc.saveToFile("output.pdf", FileFormat.PDF); doc.close(); ``` -------------------------------- ### Create a Submit Button Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/form-fields.md Example of creating a submit button, setting its text, font, background color, and adding a submit action with a URL. ```java PdfButtonField submitButton = new PdfButtonField(page, "submit"); submitButton.setBounds(new Rectangle2D.Double(100, 300, 100, 25)); submitButton.setText("Submit"); submitButton.setFont(new PdfFont(PdfFontFamily.Helvetica, 12f)); submitButton.setBackColor(new PdfRGBColor(200, 200, 200)); // Add submit action PdfSubmitAction action = new PdfSubmitAction("https://example.com/submit"); submitButton.getActions().add(action); doc.getForm().getFields().add(submitButton); ``` -------------------------------- ### Creating Bookmarks with Styling Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfBookmark.md This example shows how to add bookmarks to a PDF document and apply different text styles (bold, italic) and colors to them. ```APIDOC ## Bookmarks with Styling This example demonstrates creating PDF bookmarks with various styling options, including text style (bold, italic) and color. ### Code Example ```java PdfDocument doc = new PdfDocument(); PdfPageBase page1 = doc.getPages().add(); PdfPageBase page2 = doc.getPages().add(); PdfPageBase page3 = doc.getPages().add(); // Create bookmarks with different styles PdfBookmark normalBookmark = doc.getBookmarks().add("Normal Section"); normalBookmark.setAction(new PdfGoToAction(new PdfDestination(page1))); PdfBookmark boldBookmark = doc.getBookmarks().add("Important Section"); boldBookmark.setColor(new PdfRGBColor(Color.RED)); boldBookmark.setDisplayStyle(PdfTextStyle.Bold); boldBookmark.setAction(new PdfGoToAction(new PdfDestination(page2))); PdfBookmark italicBookmark = doc.getBookmarks().add("Reference Section"); italicBookmark.setColor(new PdfRGBColor(Color.BLUE)); italicBookmark.setDisplayStyle(PdfTextStyle.Italic); italicBookmark.setAction(new PdfGoToAction(new PdfDestination(page3))); doc.saveToFile("styled_bookmarks.pdf", FileFormat.PDF); doc.close(); ``` ### Related Classes - **PdfGoToAction**: Used to define the navigation action for a bookmark. - **PdfDestination**: Specifies the target location (page and position) for a bookmark. - **PdfRGBColor**: Defines a color using RGB values. - **PdfTextStyle**: Enum for applying text styles like Bold and Italic. ``` -------------------------------- ### Create and Render a Simple PDF Table Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfTable.md A complete example demonstrating the creation of a PdfTable, setting its data from a 2D array, drawing it onto a PDF page, and saving the document. ```java PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.getPages().add(); // Prepare table data Object[][] data = { {"Product", "Price", "Quantity"}, {"Laptop", "$1200", "5"}, {"Mouse", "$25", "50"}, {"Keyboard", "$75", "30"} }; // Create and draw table PdfTable table = new PdfTable(); table.setDataSource(data); table.draw(page, new Point2D.Double(50, 50)); doc.saveToFile("table.pdf", FileFormat.PDF); doc.close(); ``` -------------------------------- ### Creating Bookmarks to Specific Locations Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfBookmark.md This example shows how to create bookmarks that not only link to a page but also to a precise location (x, y coordinates) on that page. ```APIDOC ## Bookmarks to Specific Locations This example demonstrates how to create bookmarks that navigate to a specific point (x, y coordinates) on a PDF page, in addition to the page itself. ### Code Example ```java PdfDocument doc = new PdfDocument(); PdfPageBase page1 = doc.getPages().add(); PdfPageBase page2 = doc.getPages().add(); // Content on page 1 PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 14f); PdfBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK)); page1.getCanvas().drawString("Section A", font, brush, 50, 100); page1.getCanvas().drawString("Section B", font, brush, 50, 200); page1.getCanvas().drawString("Section C", font, brush, 50, 300); // Create bookmarks to specific locations on page PdfBookmark secA = doc.getBookmarks().add("Section A"); secA.setAction(new PdfGoToAction( new PdfDestination(page1, new Point2D.Double(50, 100)) )); PdfBookmark secB = doc.getBookmarks().add("Section B"); secB.setAction(new PdfGoToAction( new PdfDestination(page1, new Point2D.Double(50, 200)) )); PdfBookmark secC = doc.getBookmarks().add("Section C"); secC.setAction(new PdfGoToAction( new PdfDestination(page1, new Point2D.Double(50, 300)) )); doc.saveToFile("location_bookmarks.pdf", FileFormat.PDF); doc.close(); ``` ### Related Classes - **PdfGoToAction**: Defines the action for bookmark navigation. - **PdfDestination**: Specifies the target page and coordinates for navigation. - **Point2D.Double**: Represents a point with double-precision coordinates. ``` -------------------------------- ### Example: Creating Hierarchical Bookmarks in PDF Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfBookmark.md Illustrates the creation of a multi-level bookmark structure within a PDF document, including root-level parts and nested chapters with navigation actions. ```java PdfDocument doc = new PdfDocument(); PdfPageBase page1 = doc.getPages().add(); PdfPageBase page2 = doc.getPages().add(); PdfPageBase page3 = doc.getPages().add(); PdfPageBase page4 = doc.getPages().add(); // Create root-level bookmarks PdfBookmark part1 = doc.getBookmarks().add("Part I"); PdfBookmark part2 = doc.getBookmarks().add("Part II"); // Add child bookmarks to Part I PdfBookmark ch1 = part1.add("Chapter 1"); PdfBookmark ch2 = part1.add("Chapter 2"); // Add child bookmarks to Part II PdfBookmark ch3 = part2.add("Chapter 3"); PdfBookmark ch4 = part2.add("Chapter 4"); // Set up navigation ch1.setAction(new PdfGoToAction(new PdfDestination(page1))); ch2.setAction(new PdfGoToAction(new PdfDestination(page2))); ch3.setAction(new PdfGoToAction(new PdfDestination(page3))); ch4.setAction(new PdfGoToAction(new PdfDestination(page4))); doc.saveToFile("hierarchical_bookmarks.pdf", FileFormat.PDF); doc.close(); ``` -------------------------------- ### TextFindParameter Usage Example Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/types.md Demonstrates how to set multiple text find parameters using EnumSet for case-insensitive and whole-word matching. ```java options.setTextFindParameter( EnumSet.of(TextFindParameter.IgnoreCase, TextFindParameter.WholeWord) ); ``` -------------------------------- ### Setup Standard PDF Fonts Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/configuration.md Instantiate standard PDF fonts like Helvetica, Times-Roman, and Courier with specified sizes and styles (e.g., Bold, Italic). ```java // Predefined PDF fonts PdfFont helvetica = new PdfFont(PdfFontFamily.Helvetica, 12f); PdfFont timesRoman = new PdfFont(PdfFontFamily.Times_Roman, 14f); PdfFont courier = new PdfFont(PdfFontFamily.Courier, 10f); // With styles PdfFont boldHelvetica = new PdfFont( PdfFontFamily.Helvetica, 12f, EnumSet.of(PdfFontStyle.Bold) ); PdfFont boldItalic = new PdfFont( PdfFontFamily.Times_Roman, 12f, EnumSet.of(PdfFontStyle.Bold, PdfFontStyle.Italic) ); ``` -------------------------------- ### Setup Custom Fonts Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/configuration.md Load TrueType fonts from files or Java Font objects, and configure CJK standard fonts for use in PDF documents. ```java // Load TrueType font from file PdfTrueTypeFont customFont = new PdfTrueTypeFont( "C:\\Fonts\\Arial.ttf", 14f ); // From Java Font with Unicode Font awtFont = new Font("SimSun", Font.PLAIN, 12); PdfTrueTypeFont chineseFont = new PdfTrueTypeFont(awtFont, true); // CJK (Chinese, Japanese, Korean) fonts PdfCjkStandardFont cjkFont = new PdfCjkStandardFont( PdfCjkFontFamily.Hanyang_Systems_Gothic_Medium, 12f ); ``` -------------------------------- ### Case-Insensitive Search Example Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfTextFinder.md Shows how to perform a search that ignores the case of the text. This is useful for finding variations of a word regardless of capitalization. ```java PdfDocument doc = new PdfDocument(); doc.loadFromFile("document.pdf"); PdfPageBase page = doc.getPages().get(0); PdfTextFinder finder = new PdfTextFinder(page); // Configure case-insensitive search PdfTextFindOptions options = finder.getOptions(); options.setTextFindParameter(EnumSet.of(TextFindParameter.IgnoreCase)); // Find "HELLO", "hello", "Hello" etc. List results = finder.findAll(); System.out.println("Found " + results.size() + " matches"); doc.close(); ``` -------------------------------- ### Creating a Table of Contents with Bookmarks Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfBookmark.md This example illustrates how to generate a Table of Contents (TOC) where each entry is a bookmark linking to a specific page in the document. ```APIDOC ## Table of Contents with Bookmarks This example demonstrates creating a Table of Contents (TOC) where each chapter title is a bookmark that navigates to the corresponding page. ### Code Example ```java PdfDocument doc = new PdfDocument(); // Create TOC page PdfPageBase tocPage = doc.getPages().add(); PdfFont tocFont = new PdfFont(PdfFontFamily.Helvetica, 18f); PdfBrush tocBrush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK)); tocPage.getCanvas().drawString("Table of Contents", tocFont, tocBrush, 50, 50); // Create content pages with bookmarks String[] chapters = {"Introduction", "Main Content", "Advanced Topics", "Conclusion"}; int pageNum = 0; for (String chapter : chapters) { PdfPageBase page = doc.getPages().add(); // Draw page content PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 20f); page.getCanvas().drawString(chapter, font, tocBrush, 50, 50); // Create bookmark PdfBookmark bookmark = doc.getBookmarks().add(chapter); bookmark.setAction(new PdfGoToAction(new PdfDestination(page))); // Add to TOC PdfFont smallFont = new PdfFont(PdfFontFamily.Helvetica, 12f); tocPage.getCanvas().drawString(chapter, smallFont, tocBrush, 70, 80 + (pageNum * 20)); pageNum++; } doc.saveToFile("toc_bookmarks.pdf", FileFormat.PDF); doc.close(); ``` ### Related Classes - **PdfGoToAction**: Used for navigation actions within bookmarks. - **PdfDestination**: Defines the target page and position for navigation. - **PdfBookmark**: Represents a bookmark entry in the PDF document. ``` -------------------------------- ### Usage Examples Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfTrueTypeFont.md Illustrates practical usage scenarios for PdfTrueTypeFont, including loading from files, using system fonts with Unicode, and combining multiple custom fonts. ```APIDOC ## Load Custom Font from File ### Description Demonstrates how to load a TrueType font from a .ttf file and use it to draw text on a PDF canvas. ### Code Example ```java PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.getPages().add(); // Load TrueType font from file PdfTrueTypeFont font = new PdfTrueTypeFont("C:\\Fonts\\Georgia.ttf", 16f); PdfBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.DARK_GRAY)); page.getCanvas().drawString("Using Georgia font", font, brush, 10, 10); doc.saveToFile("output.pdf", FileFormat.PDF); doc.close(); ``` ``` ```APIDOC ## Use System Font with Unicode ### Description Shows how to create a PdfTrueTypeFont from a system's AWT Font object and enable Unicode support for drawing text in multiple languages. ### Code Example ```java // Create AWT font with bold italic Font awtFont = new Font("DejaVu Sans", Font.BOLD | Font.ITALIC, 12); // Create PDF font with Unicode support PdfTrueTypeFont pdfFont = new PdfTrueTypeFont(awtFont, true); // Draw mixed language content String text = "English and Français and Español"; // canvas.drawString(text, pdfFont, brush, 10, 50); ``` ``` ```APIDOC ## Multiple Custom Fonts in One Document ### Description Illustrates how to use different PdfTrueTypeFont objects for headings and body text within the same PDF document. ### Code Example ```java PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.getPages().add(); // Heading font PdfTrueTypeFont headingFont = new PdfTrueTypeFont( new Font("Courier New", Font.BOLD, 12), 18f, false ); // Body font PdfTrueTypeFont bodyFont = new PdfTrueTypeFont( new Font("Calibri", Font.PLAIN, 12), 11f, false ); PdfBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK)); // Draw heading page.getCanvas().drawString("Document Title", headingFont, brush, 10, 10); // Draw body text page.getCanvas().drawString("Body text content", bodyFont, brush, 10, 40); doc.saveToFile("output.pdf", FileFormat.PDF); doc.close(); ``` ``` -------------------------------- ### Simple Text Search Example Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfTextFinder.md Demonstrates a basic search for a specific text string within a PDF page. It retrieves and prints the found text and its coordinates. ```java PdfDocument doc = new PdfDocument(); doc.loadFromFile("sample.pdf"); PdfPageBase page = doc.getPages().get(0); PdfTextFinder finder = new PdfTextFinder(page); // Find all occurrences of "invoice" List results = finder.findAll(); for (PdfTextFind result : results) { String foundText = result.getText(); Rectangle2D bounds = result.getBounds(); System.out.println("Found: " + foundText); System.out.println("At position: " + bounds.getX() + ", " + bounds.getY()); } doc.close(); ``` -------------------------------- ### Whole Word Search Example Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfTextFinder.md Demonstrates how to configure the finder to match only whole words. This prevents partial matches within larger words (e.g., finding 'cat' but not in 'concatenate'). ```java PdfDocument doc = new PdfDocument(); doc.loadFromFile("document.pdf"); PdfPageBase page = doc.getPages().get(0); PdfTextFinder finder = new PdfTextFinder(page); // Configure whole word search (won't match "cat" in "concatenate") PdfTextFindOptions options = finder.getOptions(); options.setTextFindParameter(EnumSet.of(TextFindParameter.WholeWord)); List results = finder.findAll(); for (PdfTextFind result : results) { System.out.println("Whole word found: " + result.getText()); } doc.close(); ``` -------------------------------- ### Search Text Across Multiple PDF Pages Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfTextFinder.md This example shows how to iterate through all pages of a PDF document to find occurrences of text. It configures search options for case-insensitive matching and prints the number of matches found on each page and the total count. Ensure the PdfDocument is loaded before starting the loop. ```java PdfDocument doc = new PdfDocument(); doc.loadFromFile("document.pdf"); int totalMatches = 0; // Search all pages for (int i = 0; i < doc.getPages().getCount(); i++) { PdfPageBase page = doc.getPages().get(i); PdfTextFinder finder = new PdfTextFinder(page); // Configure options PdfTextFindOptions options = finder.getOptions(); options.setTextFindParameter(EnumSet.of(TextFindParameter.IgnoreCase)); // Find occurrences List results = finder.findAll(); totalMatches += results.size(); System.out.println("Page " + (i+1) + ": found " + results.size() + " matches"); } System.out.println("Total matches: " + totalMatches); doc.close(); ``` -------------------------------- ### PdfUnitConvertor Class and Example Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/types.md Provides functionality to convert values between different measurement units. An example shows converting inches to points. ```java public class PdfUnitConvertor { public PdfUnitConvertor() {} public float convertUnits(float value, PdfGraphicsUnit fromUnit, PdfGraphicsUnit toUnit) } PdfUnitConvertor convertor = new PdfUnitConvertor(); float inchesToPoints = convertor.convertUnits(1f, PdfGraphicsUnit.Inch, PdfGraphicsUnit.Point); // Returns 72f ``` -------------------------------- ### Hello World PDF Creation in Java Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/INDEX.md A basic example demonstrating how to create a new PDF document, add a page, draw text, and save the document. Ensure you have the Spire.PDF for Java library added to your project. ```java import com.spire.pdf.*; import com.spire.pdf.graphics.*; import java.awt.*; PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.getPages().add(); PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 30f); PdfBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black)); page.getCanvas().drawString("Hello, World!", font, brush, 10, 10); doc.saveToFile("output.pdf", FileFormat.PDF); doc.close(); ``` -------------------------------- ### getXMPMetadata() Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfDocument.md Gets XMP metadata from the document. ```APIDOC ## getXMPMetadata() ### Description Gets XMP metadata from the document. ### Method GET ### Endpoint `/document/xmp-metadata` ### Response #### Success Response (200) - **metadata** (PdfXMPMetadata) - XMP metadata object ### Response Example ```json { "metadata": "PdfXMPMetadata" } ``` ``` -------------------------------- ### Create a Simple PDF Document Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/Samples/pdf_java.md Demonstrates how to create a new PDF document and add a page with "Hello, World!" text. Ensure you have the Spire.PDF library imported. ```java // Create a pdf document PdfDocument doc = new PdfDocument(); // Create one page PdfPageBase page = doc.getPages().add(); // Define the color as black PdfRGBColor color = new PdfRGBColor(Color.black); // Draw the text on the page page.getCanvas().drawString("Hello, World!", new PdfFont(PdfFontFamily.Helvetica, 30f), new PdfSolidBrush(color), 10, 10); ``` -------------------------------- ### Get Coordinates of a Text Box Field Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/Samples/pdf_java.md Load a PDF, access the form widget, retrieve a specific text box field by name, and get its location on the page. Ensure the PDF has a text box field named 'Text1'. ```java PdfDocument doc = new PdfDocument(); doc.loadFromFile("data/TextBoxSample.pdf"); PdfFormWidget formWidget = (PdfFormWidget) doc.getForm(); PdfTextBoxFieldWidget textbox = (PdfTextBoxFieldWidget) formWidget.getFieldsWidget().get("Text1"); Point2D location = textbox.getLocation(); ``` -------------------------------- ### Get Image Height Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfImage.md Retrieves the original height of the image in pixels. ```java int getHeight() ``` ```java PdfImage image = PdfImage.fromFile("photo.jpg"); int height = image.getHeight(); ``` -------------------------------- ### Initialize PdfDocument and Set Options Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/configuration.md Demonstrates basic initialization of a PdfDocument and setting various document-level configurations including form creation allowance, zoom factor, viewer preferences, document information, and file information. ```java PdfDocument doc = new PdfDocument(); // Set allowance for form creation (required before adding form fields) doc.setAllowCreateForm(true); // Set zoom level when opening PDF doc.setZoomFactor(1.5f); // 150% zoom // Set viewer preferences PdfViewerPreference preference = doc.getViewerPreference(); // Configure preference settings... // Configure document information (metadata) PdfDocumentInformation info = doc.getDocumentInformation(); info.setTitle("Document Title"); info.setAuthor("Author Name"); info.setSubject("Document Subject"); info.setKeywords("keyword1, keyword2"); info.setCreator("Application Name"); info.setProducer("Producer"); // Configure file-level settings PdfFileInfo fileInfo = doc.getFileInfo(); fileInfo.setVersion(PdfVersion.Version_1_5); fileInfo.setCrossReferenceType(PdfCrossReferenceType.Cross_Reference_Stream); fileInfo.setIncrementalUpdate(false); ``` -------------------------------- ### Complete Document Creation in Java Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/README.md This snippet demonstrates how to create a PDF document from scratch, including adding text, images, and form fields, and saving the document. It requires the Spire.PDF library and a 'logo.png' file. ```java import com.spire.pdf.*; import com.spire.pdf.graphics.*; import java.awt.*; import java.awt.geom.*; public class PdfExample { public static void main(String[] args) { PdfDocument doc = null; try { // Create document doc = new PdfDocument(); // Add page with margins PdfMargins margins = new PdfMargins(); margins.setTop(36); margins.setLeft(54); PdfPageBase page = doc.getPages().add(PdfPageSize.Letter, margins); // Add text PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 14f); PdfBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK)); page.getCanvas().drawString("Sample PDF", font, brush, 50, 50); // Add image PdfImage image = PdfImage.fromFile("logo.png"); page.getCanvas().drawImage(image, 50, 100, 100, 75); // Add form field doc.setAllowCreateForm(true); PdfTextBoxField textField = new PdfTextBoxField(page, "name"); textField.setBounds(new Rectangle2D.Double(50, 200, 200, 20)); doc.getForm().getFields().add(textField); // Save doc.saveToFile("output.pdf", FileFormat.PDF); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(); } finally { if (doc != null) { doc.close(); doc.dispose(); } } } } ``` -------------------------------- ### Get Image Width Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfImage.md Retrieves the original width of the image in pixels. ```java int getWidth() ``` ```java PdfImage image = PdfImage.fromFile("photo.jpg"); int width = image.getWidth(); ``` -------------------------------- ### Get Font Height Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfFont.md Retrieves the height of the current font in points. ```java double height = font.getHeight(); ``` -------------------------------- ### Create PDF Navigation and JavaScript Actions Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/Samples/pdf_java.md This example shows how to create GoTo actions for navigating within a PDF, set named actions like navigating to the last page upon opening, and define a JavaScript action to execute before closing the document. Requires Spire.PDF library. ```java // Define a destination for navigating to the top of the table PdfDestination tableTopDest = new PdfDestination(page); tableTopDest.setLocation(new Point2D.Float(0, y)); tableTopDest.setMode(PdfDestinationMode.Location); tableTopDest.setZoom(1f); // Define a destination for navigating to the bottom of the table PdfDestination tableBottomDest = new PdfDestination(tableLayoutResult.getPage()); tableBottomDest.setLocation(new Point2D.Float(0, (float) tableLayoutResult.getBounds().getY())); tableBottomDest.setMode(PdfDestinationMode.Location); tableBottomDest.setZoom(1f); // Create and add a GoTo action annotation to navigate to the bottom of the table PdfGoToAction action1 = new PdfGoToAction(tableBottomDest); PdfActionAnnotation annotation1 = new PdfActionAnnotation(buttonBounds, action1); annotation1.setBorder(new PdfAnnotationBorder(0.75f)); annotation1.setColor(new PdfRGBColor(Color.lightGray)); ((PdfNewPage) ((page instanceof PdfNewPage) ? page : null)).getAnnotations().add(annotation1); // Create and add a GoTo action annotation to navigate to the top of the table PdfGoToAction action2 = new PdfGoToAction(tableTopDest); PdfActionAnnotation annotation2 = new PdfActionAnnotation(buttonBounds, action2); annotation2.setBorder(new PdfAnnotationBorder(0.75f)); annotation2.setColor(new PdfRGBColor(Color.lightGray)); com.spire.pdf.PdfPageBase tempVar = tableLayoutResult.getPage(); ((PdfNewPage) ((tempVar instanceof PdfNewPage) ? tempVar : null)).getAnnotations().add(annotation2); // Set an action to be executed when the PDF document is opened (navigates to the last page) PdfNamedAction action3 = new PdfNamedAction(PdfActionDestination.LastPage); doc.setAfterOpenAction(action3); // Define a JavaScript action to be executed before the PDF document is closed String script = "app.alert({" + " cMsg: \"Oh no, you want to leave me.\"," + " nIcon: 3," + " cTitle: \"JavaScript Action\"" + "});"; PdfJavaScriptAction action4 = new PdfJavaScriptAction(script); doc.setBeforeCloseAction(action4); ``` -------------------------------- ### Set Annotation Border Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/types.md Example of creating a PdfAnnotationBorder and applying it to a link annotation. ```java PdfAnnotationBorder border = new PdfAnnotationBorder(2f); link.setBorder(border); ``` -------------------------------- ### Complete Form Example in Java Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/form-fields.md Demonstrates how to create a complete contact form with various fields like text boxes, a combo box, a checkbox, and a submit button. Ensure the Spire.PDF library is included in your project. ```java PdfDocument doc = new PdfDocument(); doc.setAllowCreateForm(true); PdfPageBase page = doc.getPages().add(); // Add title PdfFont titleFont = new PdfFont(PdfFontFamily.Helvetica, 18f, EnumSet.of(PdfFontStyle.Bold)); PdfBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK)); page.getCanvas().drawString("Contact Form", titleFont, brush, 50, 30); // Name field PdfFont labelFont = new PdfFont(PdfFontFamily.Helvetica, 12f); page.getCanvas().drawString("Name:", labelFont, brush, 50, 80); PdfTextBoxField nameField = new PdfTextBoxField(page, "name"); nameField.setBounds(new Rectangle2D.Double(150, 75, 200, 20)); doc.getForm().getFields().add(nameField); // Email field page.getCanvas().drawString("Email:", labelFont, brush, 50, 120); PdfTextBoxField emailField = new PdfTextBoxField(page, "email"); emailField.setBounds(new Rectangle2D.Double(150, 115, 200, 20)); doc.getForm().getFields().add(emailField); // Country dropdown page.getCanvas().drawString("Country:", labelFont, brush, 50, 160); PdfComboBoxField country = new PdfComboBoxField(page, "country"); country.setBounds(new Rectangle2D.Double(150, 155, 200, 20)); country.getItems().add(new PdfListFieldItem("USA", "USA")); country.getItems().add(new PdfListFieldItem("Canada", "CA")); country.getItems().add(new PdfListFieldItem("UK", "UK")); doc.getForm().getFields().add(country); // Agreement checkbox PdfCheckBoxField agree = new PdfCheckBoxField(page, "agree"); agree.setBounds(new Rectangle2D.Double(50, 200, 20, 20)); agree.setStyle(PdfCheckBoxStyle.Check); page.getCanvas().drawString("I agree to terms", labelFont, brush, 80, 200); doc.getForm().getFields().add(agree); // Submit button PdfButtonField submit = new PdfButtonField(page, "submit"); submit.setBounds(new Rectangle2D.Double(150, 240, 100, 25)); submit.setText("Submit"); submit.getActions().add(new PdfSubmitAction("https://example.com/submit")); doc.getForm().getFields().add(submit); doc.saveToFile("contact_form.pdf", FileFormat.PDF); doc.close(); ``` -------------------------------- ### Set Up Header and Footer Templates Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/configuration.md Illustrates how to create and configure header and footer elements for PDF pages using PdfPageTemplateElement. Shows setting dimensions, foreground/background, and adding text content. ```java PdfDocument doc = new PdfDocument(); // Access page template PdfPageTemplateElement template = doc.getTemplate(); // Configure dimensions PdfPageTemplateElement headerTemplate = new PdfPageTemplateElement(doc.getPages().get(0).getSize().getWidth(), 50); // Set as foreground (appears above content) headerTemplate.setForeground(true); // Add header content PdfCanvas headerGraphics = headerTemplate.getGraphics(); PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 12f); PdfBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK)); headerGraphics.drawString("Company Name", font, brush, 50, 20); // Similarly for footer PdfPageTemplateElement footerTemplate = new PdfPageTemplateElement(doc.getPages().get(0).getSize().getWidth(), 50); footerTemplate.setForeground(false); PdfCanvas footerGraphics = footerTemplate.getGraphics(); footerGraphics.drawString("Page 1", font, brush, 50, 20); ``` -------------------------------- ### getSize() Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfPageBase.md Gets the total dimensions of the PDF page, including any defined margins. ```APIDOC ## getSize() ### Description Returns the total page size including margins. ### Method ```java Dimension2D getSize() ``` ### Returns Dimension2D - Page width and height ### Example ```java Dimension2D size = page.getSize(); double width = size.getWidth(); double height = size.getHeight(); ``` ``` -------------------------------- ### Set PdfDestination Zoom Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/types.md Example of creating a PdfDestination and setting its zoom level for navigation. ```java PdfDestination dest = new PdfDestination(page, new Point2D.Double(0, 200)); dest.setZoom(1.5f); ``` -------------------------------- ### Set PdfMargins Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/types.md Example of how to create and configure PdfMargins for a page. Margins are set in points. ```java PdfMargins margins = new PdfMargins(); margins.setTop(36); // 0.5 inch margins.setBottom(36); margins.setLeft(54); // 0.75 inch margins.setRight(54); ``` -------------------------------- ### Get Font Width Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfFont.md Retrieves the average character width of the current font in points. ```java double width = font.getWidth(); ``` -------------------------------- ### Convert Text to PDF Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/Samples/pdf_java.md This example demonstrates how to convert plain text content into a PDF document. It configures font, spacing, and text layout for proper rendering. Ensure the 'text' variable is populated with the content to be converted. ```java import spire.pdf.*; import spire.pdf.graphics.*; import java.awt.geom.Rectangle2D; public class TextToPdfConverter { public static void main(String[] args) { // Placeholder for the text content to be converted String text = "This is a sample text that will be converted to PDF. It demonstrates text layout and pagination."; // Create a new PDF document PdfDocument doc = new PdfDocument(); // Add a section to the document PdfSection section = doc.getSections().add(); // Add a page to the section PdfPageBase page = section.getPages().add(); // Specify the font for the text PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 11); // Set the line spacing for the text layout PdfStringFormat format = new PdfStringFormat(); format.setLineSpacing(20f); // Set the brush color for the text PdfBrush brush = PdfBrushes.getBlack(); // Configure the text layout to fit within the page and paginate the content PdfTextLayout textLayout = new PdfTextLayout(); textLayout.setBreak(PdfLayoutBreakType.Fit_Page); textLayout.setLayout(PdfLayoutType.Paginate); // Define the bounds of the text widget on the page Rectangle2D.Float bounds = new Rectangle2D.Float(); bounds.setRect(10, 20, page.getCanvas().getClientSize().getWidth(), page.getCanvas().getClientSize().getHeight()); // Create a new text widget with the specified text, font, and brush PdfTextWidget textWidget = new PdfTextWidget(text, font, brush); textWidget.setStringFormat(format); // Draw the text widget on the page within the specified bounds using the given layout textWidget.draw(page, bounds, textLayout); // Save the document doc.saveToFile("output/textToPDF.pdf"); // Close the document doc.close(); doc.dispose(); } } ``` -------------------------------- ### PdfTable Constructor Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfTable.md Creates a new, empty PdfTable instance. This is the starting point for building a table. ```APIDOC ## PdfTable() ### Description Creates a new empty table. ### Method Constructor ### Endpoint N/A ### Parameters None ### Request Example ```java PdfTable table = new PdfTable(); ``` ### Response N/A ``` -------------------------------- ### Add Items to ComboBox Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/types.md Example of creating PdfListFieldItem objects and adding them to a combo box's items collection. ```java comboBox.getItems().add(new PdfListFieldItem("United States", "USA")); comboBox.getItems().add(new PdfListFieldItem("Canada", "CA")); ``` -------------------------------- ### Get Physical Image Dimensions Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfImage.md Returns the physical dimensions of the image in points or inches, based on screen DPI. ```java Dimension2D getPhysicalDimension() ``` ```java PdfImage image = PdfImage.fromFile("photo.jpg"); Dimension2D physDim = image.getPhysicalDimension(); double widthInches = physDim.getWidth(); double heightInches = physDim.getHeight(); ``` -------------------------------- ### PdfDocument() Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/api-reference/PdfDocument.md Creates a new, empty PDF document instance. This is the primary constructor for starting a new PDF document. ```APIDOC ## PdfDocument() ### Description Creates a new, empty PDF document instance. ### Method Constructor ### Example ```java PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.getPages().add(); doc.saveToFile("output.pdf", FileFormat.PDF); doc.close(); ``` ``` -------------------------------- ### Configure PDF Colors and Gradients Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/_autodocs/configuration.md Shows how to set up RGB colors, including those with alpha transparency, and how to create linear gradient brushes for use in PDF documents. Supports direct RGB values, Java Color objects, and gradient definitions. ```java // RGB colors (most common) PdfRGBColor red = new PdfRGBColor(255, 0, 0); PdfRGBColor green = new PdfRGBColor(0, 128, 0); PdfRGBColor blue = new PdfRGBColor(0, 0, 255); // ARGB with alpha (transparency) PdfRGBColor semiTransparent = new PdfRGBColor(128, 255, 0, 0); // 50% alpha // From Java Color PdfRGBColor awtColor = new PdfRGBColor(java.awt.Color.CYAN); // Gradient setup PdfLinearGradientBrush gradient = new PdfLinearGradientBrush( new Rectangle(0, 0, 300, 100), new PdfRGBColor(255, 0, 0), // Start color new PdfRGBColor(0, 0, 255), // End color PdfLinearGradientMode.Horizontal ); ``` -------------------------------- ### Create PDF Table from Database Source in Java Source: https://github.com/eiceblue/spire.pdf-for-java/blob/master/Samples/pdf_java.md This snippet demonstrates creating a PDF document, setting page margins, defining table styles, connecting to an ODBC data source, retrieving data, and populating a PDF table. It includes database connection, data retrieval, and table rendering logic. ```java // Create a new PDF document PdfDocument doc = new PdfDocument(); // Create a PdfUnitConvertor to convert units PdfUnitConvertor unitCvtr = new PdfUnitConvertor(); // Create a PdfMargins object to set the page margins PdfMargins margin = new PdfMargins(); // Set the top margin by converting 2.54 centimeters to points margin.setTop(unitCvtr.convertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)); // Set the bottom margin equal to the top margin margin.setBottom(margin.getTop()); // Set the left margin by converting 3.17 centimeters to points margin.setLeft(unitCvtr.convertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)); // Set the right margin equal to the left margin margin.setRight(margin.getLeft()); // Add a new page to the document with A4 size and the specified margins PdfPageBase page = doc.getPages().add(PdfPageSize.A4, margin); // Set the initial y coordinate for drawing on the page float y = 10; // Set the font and format for the title PdfBrush brush1 = PdfBrushes.getBlack(); PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 16)); PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center); // Draw the title "Country List" at the center of the page page.getCanvas().drawString("Country List", font1, brush1, page.getCanvas().getClientSize().getWidth() / 2, y, format1); // Calculate the height of the title and adjust the y coordinate accordingly y += (float) font1.measureString("Country List", format1).getHeight(); y += 5; // Create a new PDF table PdfTable table = new PdfTable(); // Set the padding and border properties for the table table.getStyle().setCellPadding(2); table.getStyle().setBorderPen(new PdfPen(brush1, 0.75f)); // Set the default style for table cells table.getStyle().getDefaultStyle().setBackgroundBrush(PdfBrushes.getSkyBlue()); table.getStyle().getDefaultStyle().setFont(new PdfTrueTypeFont(new Font("Arial", Font.PLAIN, 10))); // Create a new PdfCellStyle object for the alternate style PdfCellStyle alternateStyle = new PdfCellStyle(); // Set the background brush for the alternate style to LightYellow alternateStyle.setBackgroundBrush(PdfBrushes.getLightYellow()); // Set the font for the alternate style using Arial font with size 10 alternateStyle.setFont(new PdfTrueTypeFont(new Font("Arial", 0, 10))); // Set the header source for the table to Column_Captions table.getStyle().setHeaderSource(PdfHeaderSource.Column_Captions); // Set the background brush for the header style to CadetBlue table.getStyle().getHeaderStyle().setBackgroundBrush(PdfBrushes.getCadetBlue()); // Set the font for the header style using Arial font with bold and size 11 table.getStyle().getHeaderStyle().setFont(new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 11))); // Set the string format for the header style to center alignment table.getStyle().getHeaderStyle().setStringFormat(new PdfStringFormat(PdfTextAlignment.Center)); // Set the showHeader property of the table to true table.getStyle().setShowHeader(true); // Connect to the database and retrieve data from the "country" table String url ="jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="+"data/demo.mdb"; DataTable dataTable = new DataTable(); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); try { Connection conn = DriverManager.getConnection(url); Statement sta = conn.createStatement(); ResultSet resultSet = sta.executeQuery("select Name,Capital,Continent,Area,Population from country "); // Fill the data table with the result set from the database JdbcAdapter jdbcAdapter = new JdbcAdapter(); jdbcAdapter.fillDataTable(dataTable, resultSet); // Set the data source for the table table.setDataSourceType(PdfTableDataSourceType.Table_Direct); table.setDataSource(dataTable); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } // Calculate the available width for the table based on the page size and borders float width = (float) page.getCanvas().getClientSize().getWidth() - ((float) (table.getColumns().getCount() + 1) * table.getStyle().getBorderPen().getWidth()); // Set the width and string format for the first column table.getColumns().get(0).setWidth(width * 0.24f); table.getColumns().get(0).setStringFormat(new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle)); // Set the width and string format for the second column table.getColumns().get(1).setWidth(width * 0.2f); table.getColumns().get(1).setStringFormat(new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle)); // Set the width and string format for the third column ```