### Set Different Page Setups for Document Sections Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Applies different page setups, such as orientation and page size, to different sections within a Word document. ```java // Retrieve the first section of the document Section sectionOne = doc.getSections().get(0); // Set the orientation of the first section to Landscape sectionOne.getPageSetup().setOrientation(PageOrientation.Landscape); // Retrieve the second section of the document Section sectionTwo = doc.getSections().get(1); // Set the page size of the second section to a custom dimension of 800x800 sectionTwo.getPageSetup().setPageSize(new Dimension(800, 800)); ``` -------------------------------- ### Copy Content from a Bookmark in a Word Document Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example shows how to copy content associated with a specific bookmark. It handles cases where the bookmark is within a table cell or a regular paragraph, calculating start and end indices to accurately select and duplicate the content. The copied content is then appended to the document. ```java // Get the bookmark named "Test" from the document Bookmark bookmark = doc.getBookmarks().get("Test"); // Declare a DocumentObject variable to store the parent object of the bookmark start/end DocumentObject docObj = null; // Check if the paragraph containing the bookmark is within a cell of a table // If it is within a cell, find the outermost parent object (Table) and get its start/end index on the document body if (((Paragraph)bookmark.getBookmarkStart().getOwner()).isInCell()) { docObj = bookmark.getBookmarkStart().getOwner().getOwner().getOwner().getOwner(); } else { docObj = bookmark.getBookmarkStart().getOwner(); } // Get the start index of the parent object on the document body int startIndex = doc.getSections().get(0).getBody().getChildObjects().indexOf(docObj); // Check if the paragraph containing the bookmark end is within a cell of a table // If it is within a cell, find the outermost parent object (Table) and get its start/end index on the document body if (((Paragraph)bookmark.getBookmarkEnd().getOwner()).isInCell()) { docObj = bookmark.getBookmarkEnd().getOwner().getOwner().getOwner().getOwner(); } else { docObj = bookmark.getBookmarkEnd().getOwner(); } // Get the end index of the parent object on the document body int endIndex = doc.getSections().get(0).getBody().getChildObjects().indexOf(docObj); // Get the paragraph containing the bookmark start and its index within the paragraph Paragraph para = (Paragraph)bookmark.getBookmarkStart().getOwner(); int pStartIndex = para.getChildObjects().indexOf(bookmark.getBookmarkStart()); // Get the paragraph containing the bookmark end and its index within the paragraph para = (Paragraph)bookmark.getBookmarkEnd().getOwner(); int pEndIndex = para.getChildObjects().indexOf(bookmark.getBookmarkEnd()); // Create a TextBodySelection based on the start and end indices of the parent object and paragraph indices TextBodySelection select = new TextBodySelection(doc.getSections().get(0).getBody(), startIndex, endIndex, pStartIndex, pEndIndex); // Create a TextBodyPart using the TextBodySelection TextBodyPart body = new TextBodyPart(select); // Iterate through the items in the TextBodyPart and add them to the document's body for (int i = 0; i < body.getBodyItems().getCount(); i++) { doc.getSections().get(0).getBody().getChildObjects().add(body.getBodyItems().get(i).deepClone()); } ``` -------------------------------- ### Save Chart as Template (.crtx) Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example demonstrates how to create a new Word document, add a column chart to it, and then save the chart as a template file with the .crtx extension. ```java // Create a new instance of the Word document Document doc = new Document(); // Add a new section to the document Section section = doc.addSection(); // Add a new paragraph to a newly created section Paragraph paragraph = section.addParagraph(); // Append a column chart to the paragraph and retrieve the Chart object Chart chart = (paragraph.appendChart(ChartType.Column, 400, 300)).getChart(); // Save the chart as a template file (.crtx) chart.saveAsTemplate("SaveChartToTemplate.crtx"); ``` -------------------------------- ### Insert Text at Document Start and End Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Use DocumentNavigator to insert text at the beginning and end of a document. Ensure a Document and DocumentNavigator instance are created before use. ```java Document doc = new Document(); DocumentNavigator navigator = new DocumentNavigator(doc); navigator.moveToDocumentStart(); avigator.writeln("Insert the content at the beginning of the document."); avigator.writeln("This is new content."); avigator.moveToDocumentEnd(); avigator.writeln(); avigator.writeln("Insert the content at the end of the document."); ``` -------------------------------- ### Set Different First Page Header/Footer Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example shows how to configure distinct headers and footers for the first page of a Word document, along with standard headers and footers for subsequent pages. ```java Section section = doc.getSections().get(0); section.getPageSetup().setDifferentFirstPageHeaderFooter(true); Paragraph paragraph1 = section.getHeadersFooters().getFirstPageHeader().addParagraph(); paragraph1.getFormat().setHorizontalAlignment(HorizontalAlignment.Right); paragraph1.appendPicture(input2); Paragraph paragraph2 = section.getHeadersFooters().getFirstPageFooter().addParagraph(); paragraph2.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); TextRange firstPageFooter = paragraph2.appendText("First Page Footer"); firstPageFooter.getCharacterFormat().setFontSize(10); Paragraph paragraph3 = section.getHeadersFooters().getHeader().addParagraph(); paragraph3.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); TextRange headerText = paragraph3.appendText("Spire.Doc for JAVA"); headerText.getCharacterFormat().setFontSize(10); Paragraph paragraph4 = section.getHeadersFooters().getFooter().addParagraph(); paragraph4.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); TextRange footerText = paragraph4.appendText("E-iceblue"); footerText.getCharacterFormat().setFontSize(10); ``` -------------------------------- ### Compare Word Documents with Custom Options Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example shows how to compare two Word documents with custom comparison options, such as ignoring formatting differences, using the Spire.Doc library. ```java CompareOptions compareOptions = new CompareOptions(); compareOptions.setIgnoreFormatting(true); doc1.compare(doc2, "E-iceblue", compareOptions); ``` -------------------------------- ### Operate Table Cell Content and Formatting Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Add content to table cells and modify their formatting using DocumentNavigator. This example demonstrates creating a table, adding cells, writing content, and applying shading. ```java Document doc = new Document(); DocumentNavigator navigator = new DocumentNavigator(doc); navigator.startTable(); TableCell cell1 = navigator.insertCell(); addcellcontent(cell1, "Row 1, Cell 1"); TableCell cell2 = navigator.insertCell(); addcellcontent(cell2, "Row 1, Cell 2"); TableCell cell3 = navigator.insertCell(); addcellcontent(cell3, "Row 1, Cell 3"); avigator.endRow(); TableCell cell4 = navigator.insertCell(); addcellcontent(cell4, "Row 2, Cell 1"); avigator.endTable(); avigator.moveToCell(0, 0, 1, 0); avigator.writeln("new content"); CellFormat cellformat = navigator.getCellFormat(); cellformat.clearFormatting(); cellformat.getShading().setBackgroundPatternColor(Color.lightGray); static void addcellcontent(TableCell cell, String Content) { Paragraph para = cell.addParagraph(); para.appendText(Content); para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); cell.getCellFormat().getShading().setBackgroundPatternColor(Color.orange); cell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); } ``` -------------------------------- ### Convert HTML Document to Image in Java Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example shows how to load an HTML file and convert its first page into a BufferedImage. It uses Spire.Doc for the conversion process. Ensure the HTML file is accessible and the output format is set to Bitmap. ```java // Create a new Document object Document document = new Document(); // Load an HTML file into the document document.loadFromFile("input.html", FileFormat.Html, XHTMLValidationType.None); // Convert the first page of the document to an image BufferedImage image = document.saveToImages(0, ImageType.Bitmap); ``` -------------------------------- ### Print a Word Document Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Print a Word document using the Spire.Doc library. This is a basic example demonstrating the print functionality. ```java Document document = new Document(); document.getPrintDocument().print(); document.dispose(); ``` -------------------------------- ### Create Image Hyperlink in Word Document Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example shows how to create a Word document, add a paragraph, and insert an image as a hyperlink. The hyperlink points to a web URL. ```java // Create a new document object Document doc = new Document(); // Get the first section of the document Section section = doc.getSections().get(0); // Add a paragraph to the section Paragraph paragraph = section.addParagraph(); // Create a DocPicture and load an image DocPicture picture = new DocPicture(doc); picture.loadImage("data/spireDoc.png"); // Append a hyperlink to the paragraph with the image and set its URL and type paragraph.appendHyperlink("https://www.e-iceblue.com/Introduce/doc-for-java.html", picture, HyperlinkType.Web_Link); ``` -------------------------------- ### Convert HTML to PDF with Custom URL Handling in Java Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example demonstrates converting an HTML file to PDF while implementing a custom handler for external URL resources. It defines a handler to download content from URLs before loading the HTML. ```java public class handleUrlWhileConvertHtmlToPDF { public static void main(String[] args) { // Create a new Document object Document document = new Document(); // Set the custom URL load handler for the document document.HtmlUrlLoadEvent = new MyDownloadEvent(); // Load the HTML file into the document document.loadFromFile("data/Template_HtmlFile3.html", FileFormat.Html, XHTMLValidationType.None); // Save the document as a PDF document.saveToFile("output/Result.pdf", FileFormat.PDF); // Dispose of the document to release resources document.dispose(); } // Custom URL load handler class static class MyDownloadEvent extends HtmlUrlLoadHandler { @Override public void invoke(Object o, HtmlUrlLoadEventArgs htmlUrlLoadEventArgs) { try { // Download the bytes from the given URL byte[] bytes = downloadBytesFromURL(htmlUrlLoadEventArgs.getUrl()); // Set the downloaded bytes as the data for the event htmlUrlLoadEventArgs.setDataBytes(bytes); } catch (Exception e) { e.printStackTrace(); } } } // Method to download bytes from a URL public static byte[] downloadBytesFromURL(String urlString) throws Exception { // Create a URL object from the string URL url = new URL(urlString); // Open a connection to the URL HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Set the request method to GET connection.setRequestMethod("GET"); // Set connection and read timeouts connection.setConnectTimeout(5000); connection.setReadTimeout(5000); // Get the response code from the connection int responseCode = connection.getResponseCode(); // If the response code is HTTP OK, read the content if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int bytesRead; // Read the input stream into the output stream while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); // Return the byte array return outputStream.toByteArray(); } else { // Throw an exception if the response code is not HTTP OK throw new Exception("Failed to download content. Response code: " + responseCode); } } } ``` -------------------------------- ### Convert Word to PDF Preserving Bookmarks in Java Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example demonstrates the process of converting a Word document to PDF while preserving existing bookmarks. The code initializes a document, loads a file, and then saves it to PDF format. ```java // Create a new instance of the Document class Document document = new Document(); // Load the Word document from the specified input file document.loadFromFile(inputFile); // Save the document to PDF format, preserving bookmarks document.saveToFile(outputFile, FileFormat.PDF); // Dispose of system resources associated with the document document.dispose(); ``` -------------------------------- ### Compare Word Documents Ignoring Headers and Footers Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example shows how to compare two Word documents while ignoring differences in headers and footers using Spire.Doc. It utilizes `CompareOptions` to achieve this. ```java Document doc1 = new Document(); Document doc2 = new Document(); CompareOptions options = new CompareOptions(); options.setIgnoreHeadersAndFooters(true); doc1.compare(doc2,"e-iceblue",options); ``` -------------------------------- ### Create and Append Line Chart with Custom Data Series Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example demonstrates creating a line chart with custom data series. It covers setting the chart title and adding multiple series with specified categories and values. ```java Paragraph newPara = section.addParagraph(); ShapeObject shape = newPara.appendChart(ChartType.Line, 500, 300); Chart chart = shape.getChart(); ChartTitle title = chart.getTitle(); title.setText("My Chart"); ChartSeriesCollection seriesColl = chart.getSeries(); seriesColl.clear(); String[] categories = { "C1", "C2", "C3", "C4", "C5", "C6" }; seriesColl.add("AW Series 1", categories, new double[] { 1, 2, 2.5, 4, 5, 6 }); seriesColl.add("AW Series 2", categories, new double[] { 2, 3, 3.5, 6, 6.5, 7 }); ``` -------------------------------- ### Execute Basic Mail Merge with Field Names and Values Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example demonstrates a simple mail merge operation using predefined field names and values. It's suitable for basic data insertion into a Word document. ```java // Create a new Document object Document document = new Document(); // Define field names and values for mail merge String[] fieldName = new String[] {"XX_Name"}; String[] fieldValue = new String[] {"Jason Tang"}; // Execute the mail merge with the specified field names and values document.getMailMerge().execute(fieldName, fieldValue); ``` -------------------------------- ### Replace Text with a Table Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example replaces specific text in a document with a table. It requires an initialized 'document' object and involves finding text, creating a table, and inserting it into the document's body. ```java //Get the first section Section section = document.getSections().get(0); //Return TextSection by finding the key text string TextSelection selection = document.findString("Christmas Day, December 25", true, true); //Return TextRange from TextSection TextRange range = selection.getAsOneRange(); //Get Owner-Paragraph Paragraph paragraph = range.getOwnerParagraph(); //Get the owner TextBody Body body = paragraph.getOwnerTextBody(); // Get the index of paragraph int index = body.getChildObjects().indexOf(paragraph); //Create a new table Table table = section.addTable(true); //Set the number of rows and columns table.resetCells(3, 3); // Remove the paragraph and body.getChildObjects().remove(paragraph); //Insert table into the collection at the specified index body.getChildObjects().insert(index, table); ``` -------------------------------- ### Create and Format a Table Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This snippet demonstrates how to create a table with a specified number of rows and columns, add a header row with bold text and centered alignment, populate data rows, and apply alternating row colors. ```java Table table = section.addTable(true); table.resetCells(data.length + 1, header.length); // Add the header row TableRow row = table.getRows().get(0); row.isHeader(true); row.setHeight(20); row.setHeightType(TableRowHeightType.Exactly); for (int j = 0; j < row.getCells().getCount(); j++) { row.getCells().get(j).getCellFormat().getShading().setBackgroundPatternColor(Color.gray); } for (int i = 0; i < header.length; i++) { row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); Paragraph p = row.getCells().get(i).addParagraph(); p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); TextRange txtRange = p.appendText(header[i]); txtRange.getCharacterFormat().setBold(true); } // Add data rows for (int r = 0; r < data.length; r++) { TableRow dataRow = table.getRows().get(r + 1); dataRow.setHeight(25); dataRow.setHeightType(TableRowHeightType.Exactly); for (int c = 0; c < dataRow.getCells().getCount(); c++) { dataRow.getCells().get(c).getCellFormat().getShading().setBackgroundPatternColor(Color.white); } for (int c = 0; c < data[r].length; c++) { dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); dataRow.getCells().get(c).addParagraph().appendText(data[r][c]); } } // Apply alternating row color for (int j = 1; j < table.getRows().getCount(); j++) { if (j % 2 == 0) { TableRow row2 = table.getRows().get(j); for (int f = 0; f < row2.getCells().getCount(); f++) { row2.getCells().get(f).getCellFormat().getShading().setBackgroundPatternColor(new Color(173, 216, 230)/*Color.getLightBlue()*/); } } } ``` -------------------------------- ### Get Non-Hidden Bookmarks from Word Document Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example retrieves all bookmark collections from a document and iterates through them to identify and display the names of non-hidden bookmarks. It also shows how to identify hidden bookmarks. ```java BookmarkCollection collection = doc.getBookmarks(); String text = ""; if (collection != null && collection.getCount() > 0) { for (Object object : collection) { Bookmark bookmark = (Bookmark) object; String name = bookmark.getName(); if(!bookmark.isHidden()) { text += String.format("The bookmark name is : " + name +"\n"); } else { text += String.format("The hidden bookmark name is : " + name +"\n"); } } } ``` -------------------------------- ### Insert a None Field in Word Document Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example shows how to insert a 'None' field into a document. It involves getting a section, adding a paragraph, and appending a field with an empty field code and FieldType.Field_None. ```java // Get the first section of the document Section section = document.getSections().get(0); // Add a new paragraph to the section Paragraph par = section.addParagraph(); // Append a none field to the paragraph with an empty field code Field field = par.appendField("", FieldType.Field_None); // Enable updating fields in the document document.isUpdateFields(true); ``` -------------------------------- ### Set Page Margins and Size Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Demonstrates how to configure page margins and select a page size (e.g., Letter) for a document section using DocumentNavigator. ```java Document doc = new Document(); DocumentNavigator navigator = new DocumentNavigator(doc); // Move the navigator's cursor to the first section (section index 0) of the document. navigator.moveToSection(0); // Set the page margins for the current section. navigator.getPageSetup().setMargins(new MarginsF(100, 80, 100, 80)); // Set the page size of the current section to Letter. navigator.getPageSetup().setPageSize(PageSize.Letter); ``` -------------------------------- ### Get Table, Row, and Cell Indices Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example demonstrates how to retrieve the indices of a table, a specific row within that table, and a cell within that row from a Word document using Spire.Doc for Java. It utilizes the `indexOf` method for tables and direct index properties for rows and cells. ```java Section section = doc.getSections().get(0); Table table = section.getTables().get(0); TableCollection collections = section.getTables(); int tableIndex = collections.indexOf(table); TableRow row = table.getLastRow(); int rowIndex = row.getRowIndex(); TableCell cell = (TableCell) row.getLastChild(); int cellIndex = cell.getCellIndex(); ``` -------------------------------- ### Write Formatted Text with DocumentNavigator Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Demonstrates how to write text with various character formatting (underline, bold, shadow, color) and manage the format stack using DocumentNavigator. ```java Document doc = new Document(); DocumentNavigator navigator = new DocumentNavigator(doc); navigator.writeln("Write plain text into the document (without special formatting yet)."); avigator.getCharacterFormat().setUnderlineColor(SystemColor.ORANGE); avigator.getCharacterFormat().setUnderlineStyle(UnderlineStyle.Single); avigator.getCharacterFormat().setBold(true); avigator.getCharacterFormat().isShadow(true); avigator.getCharacterFormat().setTextColor(Color.BLUE); avigator.writeln("Write formatted text using the current character formatting settings."); avigator.pushCharacterFormat(); avigator.getCharacterFormat().clearFormatting(); avigator.writeln("Write text with cleared (default) formatting"); avigator.popCharacterFormat(); avigator.writeln("Write text using the restored formatting."); ``` -------------------------------- ### Create a Word Document in Java Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/README.md Demonstrates how to create a new Word document, add a section and a paragraph, append text, and save the document to a .docx file. ```java //Create a Document instance Document doc = new Document(); //Add a section Section section = doc.addSection(); //Add a paragraph Paragraph para = section.addParagraph(); //Append text to the paragraph para.appendText("Hello World"); //Save the result document doc.saveToFile("output/Output.docx", FileFormat.Docx_2013); ``` -------------------------------- ### Get Form Fields Collection Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Obtain the collection of all form fields within a document section and get the total count. This is helpful for understanding the number of form fields present. ```java Section section = document.getSections().get(0); FormFieldCollection formFields = section.getBody().getFormFields(); int formFieldCount = formFields.getCount(); ``` -------------------------------- ### Convert Word to PDF, HTML, and XPS in Java Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/README.md Shows how to load an existing Word document and convert it into PDF, HTML, and XPS formats using Spire.Doc for Java. ```java //Create a Document instance Document document = new Document(); //Load a sample document document.loadFromFile("C:/Templates/Template.docx"); //Save to PDF document.saveToFile("toPDF.pdf", FileFormat.PDF); //Save to HTML document.saveToFile("toHTML.html", FileFormat.Html); //Save to XPS document.saveToFile("toXPS.xps", FileFormat.XPS); ``` -------------------------------- ### Set Document Gutter Position and Size Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Demonstrates how to enable the top gutter and set its size for a document section. Requires a new Document object. ```java // Create a new Document object Document document = new Document(); // Get the first section of the document Section section = document.getSections().get(0); // Set the top gutter to true for the section's page setup section.getPageSetup().isTopGutter(true); // Set the gutter size to 100f for the section's page setup section.getPageSetup().setGutter(100f); ``` -------------------------------- ### Get Bookmarks from Document by Index and Name Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This snippet demonstrates how to retrieve bookmarks from a Word document. It shows how to get a bookmark by its index in the collection and how to access a bookmark by its specific name. ```java Document document = new Document(); Bookmark bookmark1 = document.getBookmarks().get(0); Bookmark bookmark2 = document.getBookmarks().get("Test2"); document.dispose(); ``` -------------------------------- ### Extract Content Starting from Form Field in Word Document Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Extracts content from a Word document starting from a specific form field. The code first locates a 'FieldFormTextInput' type form field, determines its paragraph index, and then extracts the subsequent three elements. Ensure the document contains form fields. ```java // Define a variable int index = 0; // Traverse FormFields for (Object fieldObj : sourceDocument.getSections().get(0).getBody().getFormFields()) { FormField field = (FormField) fieldObj; // Find FieldFormTextInput type field if (field.getType() == FieldType.Field_Form_Text_Input) { // Get the paragraph Paragraph paragraph = field.getOwnerParagraph(); // Get the index index = sourceDocument.getSections().get(0).getBody().getChildObjects().indexOf(paragraph); break; } } // Extract the content for (int i = index; i < (index + 3); i++) { // Clone the ChildObjects of source document DocumentObject doobj = sourceDocument.getSections().get(0).getBody().getChildObjects().get(i).deepClone(); // Add to destination document section.getBody().getChildObjects().add(doobj); } ``` -------------------------------- ### Configure Headers and Footers with Text and Images Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This snippet demonstrates how to set up page size, margins, and insert pictures and text into the header and footer of a Word document. It also shows how to add page numbering and set border properties. ```java // Get the first section of the document Section section = document.getSections().get(0); // Set page size and margins for the section section.getPageSetup().setPageSize(PageSize.A4); section.getPageSetup().getMargins().setTop(72f); section.getPageSetup().getMargins().setBottom(72f); section.getPageSetup().getMargins().setLeft(89.85f); section.getPageSetup().getMargins().setRight(89.85f); // Get header and footer objects from the section HeaderFooter header = section.getHeadersFooters().getHeader(); HeaderFooter footer = section.getHeadersFooters().getFooter(); // Insert picture and text to the header Paragraph headerParagraph = header.addParagraph(); // Add image to header DocPicture headerPicture = headerParagraph.appendPicture(/* header image file path */); // Add header text TextRange text = headerParagraph.appendText("Demo of Spire.Doc"); text.getCharacterFormat().setFontName("Arial"); text.getCharacterFormat().setFontSize(10); text.getCharacterFormat().setItalic(true); headerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right); // Set border properties for the header paragraph headerParagraph.getFormat().getBorders().getBottom().setBorderType(BorderStyle.Single); headerParagraph.getFormat().getBorders().getBottom().setSpace(0.05F); // Set layout properties for the header picture headerPicture.setTextWrappingStyle(TextWrappingStyle.Behind); headerPicture.setHorizontalOrigin(HorizontalOrigin.Page); headerPicture.setHorizontalAlignment(ShapeHorizontalAlignment.Left); headerPicture.setVerticalOrigin(VerticalOrigin.Page); headerPicture.setVerticalAlignment(ShapeVerticalAlignment.Top); // Insert picture to the footer Paragraph footerParagraph = footer.addParagraph(); // Add image to footer DocPicture footerPicture = footerParagraph.appendPicture(/* footer image file path */); // Set layout properties for the footer picture footerPicture.setTextWrappingStyle(TextWrappingStyle.Behind); footerPicture.setHorizontalOrigin(HorizontalOrigin.Page); footerPicture.setHorizontalAlignment(ShapeHorizontalAlignment.Left); footerPicture.setVerticalOrigin(VerticalOrigin.Page); footerPicture.setVerticalAlignment(ShapeVerticalAlignment.Bottom); // Insert page number and total number of pages in the footer footerParagraph.appendField("page number", FieldType.Field_Page); footerParagraph.appendText(" of "); footerParagraph.appendField("number of pages", FieldType.Field_Num_Pages); footerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right); // Set border properties for the footer paragraph footerParagraph.getFormat().getBorders().getTop().setBorderType(BorderStyle.Single); footerParagraph.getFormat().getBorders().getTop().setSpace(0.05F); ``` -------------------------------- ### Add Horizontal Line to Word Document Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example shows how to create a new document, add a section and paragraph, and then append a horizontal line to that paragraph. ```java // Create a new Document object Document doc = new Document(); // Add a new Section to the Document Section sec = doc.addSection(); // Add a new Paragraph to the Section Paragraph para = sec.addParagraph(); // Append a horizontal line to the Paragraph para.appendHorizonalLine(); ``` -------------------------------- ### Configure Line Numbering for Document Sections Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Configures line numbering properties for a document section, including start value, step, distance from text, and restart mode. ```java // Set the start value of line numbering in the first section to 1 document.getSections().get(0).getPageSetup().setLineNumberingStartValue(1); // Set the step value for line numbering in the first section to 6 document.getSections().get(0).getPageSetup().setLineNumberingStep(6); // Set the distance between line numbers and text in the first section to 40f document.getSections().get(0).getPageSetup().setLineNumberingDistanceFromText(40f); // Set the line numbering restart mode in the first section to Continuous document.getSections().get(0).getPageSetup().setLineNumberingRestartMode(LineNumberingRestartMode.Continuous); ``` -------------------------------- ### Create, Populate, and Delete Table Rows Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This snippet shows how to create a table, add content to its cells, and then delete a row using DocumentNavigator. It includes a helper method for cell content formatting. ```java Document doc = new Document(); DocumentNavigator navigator = new DocumentNavigator(doc); Table table = navigator.startTable(); table.resetCells(2, 2); table.setPreferredWidth(new PreferredWidth(WidthType.Percentage, (short)100)); table.getFirstRow().setHeight(30f); TableCell cell1 = table.getRows().get(0).getCells().get(0); addcellcontent(cell1, "Row 1, Cell 1"); TableCell cell2 = table.getRows().get(0).getCells().get(1); addcellcontent(cell2, "Row 1, Cell 2"); TableCell cell3 = table.getRows().get(1).getCells().get(0); addcellcontent(cell3, "Row 2, Cell 1"); TableCell cell4 = table.getRows().get(1).getCells().get(1); addcellcontent(cell4, "Row 2, Cell 2"); navigator.endTable(); avigator.deleteRow(0, 0); ``` ```java // Helper method to add content to a table cell with formatting static void addcellcontent(TableCell cell, String Content) { // Add a new paragraph to the table cell. Paragraph para = cell.addParagraph(); // Append the specified text content to the paragraph inside the cell. para.appendText(Content); // Center-align the text horizontally within the paragraph. para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); // Set the background (shading) color of the table cell to ORANGE. cell.getCellFormat().getShading().setBackgroundPatternColor(Color.ORANGE); // Vertically center the content within the table cell. cell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); } ``` -------------------------------- ### Specify Protection Type for a Document Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example demonstrates how to protect a Word document, specifically setting it to 'Allow_Only_Reading' mode with a given password. Replace '123456' with your desired password. ```java document.protect(ProtectionType.Allow_Only_Reading, "123456"); ``` -------------------------------- ### Add Cover Image and Convert to EPUB Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Demonstrates how to add a cover image to a document before converting it to EPUB format. Ensure the document and image files exist at the specified paths. ```java // Create a new Document object Document doc = new Document(); // Load the document from the specified file path doc.loadFromFile("data/ToEpub.doc"); // Create a DocPicture object and load the cover image DocPicture picture = new DocPicture(doc); picture.loadImage("data/Cover.png"); // Save the document to EPUB format with the added cover image doc.saveToEpub("output/addCoverImage.epub", picture); // Clean up system resources doc.dispose(); ``` -------------------------------- ### Remove a Table from a Word Document Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example shows how to remove the first table from a specific section of a Word document. Ensure the section and table exist before attempting removal. ```java // Get the first section of the document and remove the first table in it doc.getSections().get(0).getTables().removeAt(0); ``` -------------------------------- ### Combine and Split Tables in Java Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Demonstrates combining rows from one table into another and splitting a table at a specified row. Ensure tables and sections are correctly referenced. ```java private static void CombineTables() { // Get the first section Section section = doc.getSections().get(0); // Get the first and second table Table table1 = section.getTables().get(0); Table table2 = section.getTables().get(1); // Add the rows of table2 to table1 for (int i = 0; i < table2.getRows().getCount(); i++) { table1.getRows().add(table2.getRows().get(i).deepClone()); } // Remove table2 section.getTables().remove(table2); } private static void SplitTable() { // Get the first section Section section = doc.getSections().get(0); // Get the first table Table table = section.getTables().get(0); // We will split the table at the third row int splitIndex = 2; // Create a new table for the split table Table newTable = new Table(section.getDocument()); // Add rows to the new table for (int i = splitIndex; i < table.getRows().getCount(); i++) { newTable.getRows().add(table.getRows().get(i).deepClone()); } // Remove rows from the original table for (int i = table.getRows().getCount() - 1; i >= splitIndex; i--) { table.getRows().removeAt(i); } // Add the new table in section section.getTables().add(newTable); } ``` -------------------------------- ### Allow Latin Text to Wrap Mid-Word Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example shows how to configure a paragraph's format to allow Latin text to wrap within a word, rather than only at spaces. ```java //Create Word document. Document document = new Document(); Paragraph para = document.getSections().get(0).getParagraphs().get(0); //Allow Latin text to wrap in the middle of a word para.getFormat().setWordWrap(false); ``` -------------------------------- ### Apply Custom Table Style in Java Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Shows how to define and apply a custom style to a table in a document using Spire.Doc. This includes setting alignment, border color, and line style. The Spire.Doc library must be referenced. ```java // Initialize a new Document object Document doc = new Document(); // Add a new section to the document Section section = doc.addSection(); // Create a new custom table style named "TestTableStyle1" TableStyle tableStyle = (TableStyle) doc.getStyles().add(StyleType.Table_Style, "TestTableStyle1"); // Set the horizontal alignment of the table content to Center tableStyle.setHorizontalAlignment(RowAlignment.Center); // Access the borders of the style and set their color to Blue tableStyle.getBorders().setColor(Color.BLUE); // Set the border line style to Single tableStyle.getBorders().setBorderType(BorderStyle.Single); // Add a new table to the current section Table table = section.addTable(); // Reset the table structure to have 1 row and 1 column table.resetCells(1, 1); // Access the first cell, add a paragraph and append text table.getRows().get(0).getCells().get(0).addParagraph().appendText("Aligned to the center of the page"); // Set the preferred width of the table to 300 points table.setPreferredWidth(PreferredWidth.fromPoints(300)); // Apply the previously defined custom style to this table table.applyStyle(tableStyle); ``` -------------------------------- ### Remove a Field from a Document Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This snippet shows how to remove a specific field from a document. It involves getting the field, identifying its parent paragraph, and removing it from the paragraph's child objects. ```java // Get the first field in the document Field field = document.getFields().get(0); // Get the owner paragraph of the field Paragraph par = field.getOwnerParagraph(); // Get the index of the field within its parent paragraph int index = par.getChildObjects().indexOf(field); // Remove the field from its parent paragraph par.getChildObjects().removeAt(index); ``` -------------------------------- ### Get Merge Field Names Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Retrieve an array of all merge field names present in a document's mail merge data. This is useful for understanding what data can be merged into the document. ```java String[] fieldNames = document.getMailMerge().getMergeFieldNames(); int fieldCount = fieldNames.length; for (String name : fieldNames) { } ``` -------------------------------- ### Get Table Positioning Information Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Retrieves detailed positioning and spacing information for a table within a Word document. Ensure the document has at least one section and one table. ```java Section section = document.getSections().get(0); Table table = section.getTables().get(0); if (table.getFormat().getWrapTextAround()) { TablePositioning position = table.getFormat().getPositioning(); String horizPosition = "Position: " + position.getHorizPosition() + " pt"; String horizAbsPosition = "Absolute Position: " + position.getHorizPositionAbs() + ", Relative to: " + position.getHorizRelationTo(); String vertPosition = "Position: " + position.getVertPosition() + " pt"; String vertAbsPosition = "Absolute Position: " + position.getVertPositionAbs() + ", Relative to: " + position.getVertRelationTo(); String distance = "Top: " + position.getDistanceFromTop() + " pt, Left: " + position.getDistanceFromLeft() + " pt\nBottom: " + position.getDistanceFromBottom() + " pt, Right: " + position.getDistanceFromRight() + " pt"; } ``` -------------------------------- ### Remove Bookmark Content Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Removes the content located between the start and end positions of a bookmark in a Word document. It identifies the content by index within the bookmark's owner paragraph. ```java // Get the bookmark named "Test2" from the document's bookmarks collection Bookmark bookmark = document.getBookmarks().get("Test2"); // Get the Paragraph that contains the start position of the bookmark Paragraph para = (Paragraph)bookmark.getBookmarkStart().getOwner(); // Determine the index of the bookmark start within its parent paragraph int startIndex = para.getChildObjects().indexOf(bookmark.getBookmarkStart()); // Get the Paragraph that contains the end position of the bookmark para = (Paragraph)bookmark.getBookmarkEnd().getOwner(); // Determine the index of the bookmark end within its parent paragraph int endIndex = para.getChildObjects().indexOf(bookmark.getBookmarkEnd()); // Remove the content between the bookmark start and end positions for (int i = startIndex + 1; i < endIndex; i++) { para.getChildObjects().removeAt(startIndex + 1); } ``` -------------------------------- ### Create and Format a Text Box Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This snippet shows how to create a new TextBox, add text, format the text, set the position and size of the TextBox, style its border, and adjust its internal margins. ```java // Create a new TextBox object and append it to the Section TextBox TB = sec.addParagraph().appendTextBox(310, 90); // Add a new Paragraph to the TextBox Paragraph para = TB.getBody().addParagraph(); // Append some text to the Paragraph TextRange TR = para.appendText("Using Spire.Doc, developers will find " + "a simple and effective method to endow their applications with rich MS Word features. "); // Set the font name and size for the text TR.getCharacterFormat().setFontName("Cambria "); TR.getCharacterFormat().setFontSize(13); // Set the position and size of the TextBox on the page TB.getFormat().setHorizontalOrigin(HorizontalOrigin.Page); TB.getFormat().setHorizontalPosition(120); TB.getFormat().setVerticalOrigin(VerticalOrigin.Page); TB.getFormat().setVerticalPosition(100); // Set the style of the TextBox border TB.getFormat().setLineStyle(TextBoxLineStyle.Double); TB.getFormat().setLineColor(Color.BLUE); TB.getFormat().setLineDashing(LineDashing.Solid); TB.getFormat().setLineWidth(5); // Set the internal margins of the TextBox TB.getFormat().getInternalMargin().setTop(15); TB.getFormat().getInternalMargin().setBottom(10); TB.getFormat().getInternalMargin().setLeft(12); TB.getFormat().getInternalMargin().setRight(10); ``` -------------------------------- ### Lock Sections in Document Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Protects a document by locking specified sections while allowing others to remain editable. This example demonstrates protecting the document and then disabling protection for a specific section. ```java document.protect(ProtectionType.Allow_Only_Form_Fields, "123"); s2.setProtectForm(false); ``` -------------------------------- ### Convert DOCX to WPS Format in Java Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This snippet demonstrates how to load a DOCX document and save it into the WPS format using Spire.Doc. Ensure the input file path is correct and the output directory is writable. ```java // Create a new Document object Document document = new Document(); // Load a document from a file document.loadFromFile("input_path.docx"); // Save the document to WPS format document.saveToFile("output_path.wps", FileFormat.Wps); // Dispose of the document resources document.dispose(); ``` -------------------------------- ### Set Built-in Document Properties Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This example shows how to set various built-in document properties for a Word document, such as title, author, subject, and keywords, using the Spire.Doc library. ```java Document document = new Document(); document.getBuiltinDocumentProperties().setTitle("Document Demo Document"); document.getBuiltinDocumentProperties().setSubject("demo"); document.getBuiltinDocumentProperties().setAuthor("James"); document.getBuiltinDocumentProperties().setCompany("e-iceblue"); document.getBuiltinDocumentProperties().setManager("Jakson"); document.getBuiltinDocumentProperties().setCategory("Doc Demos"); document.getBuiltinDocumentProperties().setKeywords("Document, Property, Demo"); document.getBuiltinDocumentProperties().setComments("This document is just a demo."); ``` -------------------------------- ### Add Bullet and Numbered Lists in Java Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Demonstrates how to create and populate both bulleted and numbered lists within a document using Spire.Doc. Ensure the Spire.Doc library is included in your project. ```java // Create a new Document object Document document = new Document(); // Add a new section Section section = document.addSection(); // Define bullet list template ListTemplate template = ListTemplate.Bullet_Default; ListDefinitionReference listRef = document.getListReferences().add(template); // Define numbered list template ListTemplate template1 = ListTemplate.Number_Default; ListDefinitionReference listRef1 = document.getListReferences().add(template1); // Add bullet list items Paragraph paragraph = section.addParagraph(); paragraph.appendText("List Item 1"); paragraph.getListFormat().applyListRef(listRef, 0); paragraph = section.addParagraph(); paragraph.appendText("List Item 2"); paragraph.getListFormat().applyListRef(listRef, 1); paragraph = section.addParagraph(); paragraph.appendText("List Item 3"); paragraph.getListFormat().applyListRef(listRef, 2); // Add numbered list items paragraph = section.addParagraph(); paragraph.appendText("List Item 6"); paragraph.getListFormat().applyListRef(listRef1, 0); paragraph = section.addParagraph(); paragraph.appendText("List Item 7"); paragraph.getListFormat().applyListRef(listRef1, 1); paragraph = section.addParagraph(); paragraph.appendText("List Item 8"); paragraph.getListFormat().applyListRef(listRef1, 2); ``` -------------------------------- ### Convert Word to Image in Java Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/README.md Illustrates how to load a Word document and convert each page into a PNG image using Spire.Doc for Java. Requires Java ImageIO for saving the image. ```java //Create a Document instance Document document = new Document(); //Load a sample document document.loadFromFile("C:/Templates/Template.docx"); //Save to PNG image for (int i = 0; i < document.getPageCount(); i++) { BufferedImage image = document.saveToImages(i, ImageType.Bitmap); File file = new File("out/" + String.format(("Img-%d.png"), i)); ImageIO.write(image, "PNG", file); } ``` -------------------------------- ### Track Document Revisions Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md Enables and manages revision tracking within a Word document. This includes starting tracking, adding new text, deleting paragraphs, and stopping the tracking process. ```java import spire.doc.*; import java.util.Date; // Start the track revisions document.startTrackRevisions("User01", new Date()); // Get the first paragraph and add content document.getSections().get(0).getParagraphs().get(0).appendText("User01 add new Text!"); // Delete a paragraph document.getSections().get(0).getParagraphs().removeAt(2); // Stop the track revisions document.stopTrackRevisions(); ``` -------------------------------- ### Create Simple and Nested Bookmarks in Word Document Source: https://github.com/eiceblue/spire.doc-for-java/blob/master/Examples/doc_java.md This snippet illustrates how to create bookmarks within a document's paragraph. It shows the creation of a basic bookmark and also demonstrates how to establish nested bookmark structures, including multiple levels of nesting. ```java // Create a simple bookmark paragraph.appendBookmarkStart("SimpleCreateBookmark"); paragraph.appendText("This is a simple bookmark."); paragraph.appendBookmarkEnd("SimpleCreateBookmark"); // Create nested bookmarks paragraph.appendBookmarkStart("Root"); txtRange = paragraph.appendText(" This is Root data. "); txtRange.getCharacterFormat().setItalic(true); paragraph.appendBookmarkStart("NestedLevel1"); txtRange = paragraph.appendText(" This is Nested Level1. "); txtRange.getCharacterFormat().setItalic(true); txtRange.getCharacterFormat().setTextColor(new Color(40, 79, 79)); paragraph.appendBookmarkStart("NestedLevel2"); txtRange = paragraph.appendText(" This is Nested Level2. "); txtRange.getCharacterFormat().setItalic(true); txtRange.getCharacterFormat().setTextColor(new Color(105, 105, 105)); paragraph.appendBookmarkEnd("NestedLevel2"); paragraph.appendBookmarkEnd("NestedLevel1"); paragraph.appendBookmarkEnd("Root"); ```