Spire.XLS for Java Program Guide Content
Spire.XLS for Java is a professional Java Excel API that enables developers to create, manage, manipulate, convert and print Excel worksheets without using Microsoft Office or Microsoft Excel.
It offers a wide range of features of operating Excel worksheets on Java applications, such as creating, reading, editing, converting and printing Excel worksheets, finding and replacing data, creating charts, creating auto filters, reading and writing hyperlinks, merging/unmerging cells and files, grouping/ungrouping rows and columns, freezing/unfreezing panes, adding digital signatures, encrypting/decrypting Excel workbooks etc.
Read and Extract Fillable Form Values in PDF in Java
Spire.PDF for Java empowers developers to read and extract value from a specific form field as well as read and extract values from all form fields. In this article, we'll see how to use Spire.PDF for Java to implement this function.
Below is the sample PDF document we used for demonstration:
Read and extract value from a specific form field
import com.spire.pdf.PdfDocument; import com.spire.pdf.widget.PdfFormWidget; import com.spire.pdf.widget.PdfTextBoxFieldWidget; import java.io.FileWriter; import java.io.IOException; public class ReadSpeicificFormValue { public static void main(String[] args){ //Load PDF document PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("fillFormFields.pdf"); //Get form fields PdfFormWidget formWidget = (PdfFormWidget)pdf.getForm(); //Get the textbox by index or by name PdfTextBoxFieldWidget textbox = ( PdfTextBoxFieldWidget)formWidget.getFieldsWidget().get(0); //PdfTextBoxFieldWidget textbox = ( PdfTextBoxFieldWidget)formWidget.getFieldsWidget().get("TextBox"); //Get the text of the textbox String text = textbox.getText(); try { //Write text into a .txt file FileWriter writer = new FileWriter("GetSpecificFieldValue.txt"); writer.write(text); writer.flush(); } catch (IOException e) { e.printStackTrace(); } pdf.close(); } }
Read and extract values from all form fields
import com.spire.pdf.PdfDocument; import com.spire.pdf.fields.PdfField; import com.spire.pdf.widget.*; import java.io.FileWriter; import java.io.IOException; public class ReadAllFormValues { public static void main(String[] args) //Load PDF document PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("fillFormFields.pdf"); //Get form fields PdfFormWidget formWidget = (PdfFormWidget)pdf.getForm(); StringBuilder sb = new StringBuilder(); //Loop through the form field widget collection and extract the value of each field for (int i = 0; i < formWidget.getFieldsWidget().getCount(); i++) { PdfField field = (PdfField)formWidget.getFieldsWidget().getList().get(i); if (field instanceof PdfTextBoxFieldWidget) { PdfTextBoxFieldWidget textBoxField = (PdfTextBoxFieldWidget)field ; //Get text of textbox String text = textBoxField.getText(); sb.append("The text in textbox is: " + text + "\r\n"); } if (field instanceof PdfListBoxWidgetFieldWidget) { PdfListBoxWidgetFieldWidget listBoxField = (PdfListBoxWidgetFieldWidget)field; sb.append("Listbox items are: \r\n"); //Get values of listbox PdfListWidgetItemCollection items = listBoxField.getValues(); for (PdfListWidgetItem item : (Iterable<PdfListWidgetItem>) items) { sb.append(item.getValue() + "\r\n"); } //Get selected value String selectedValue = listBoxField.getSelectedValue(); sb.append("The selected value in the listbox is: " + selectedValue + "\r\n"); } if (field instanceof PdfComboBoxWidgetFieldWidget) { PdfComboBoxWidgetFieldWidget comBoxField = (PdfComboBoxWidgetFieldWidget)field ; sb.append("comBoxField items are: \r\n"); //Get values of comboBox PdfListWidgetItemCollection items = comBoxField.getValues(); for (PdfListWidgetItem item : (Iterable<PdfListWidgetItem>) items) { sb.append(item.getValue() + "\r\n"); } //Get selected value String selectedValue = comBoxField.getSelectedValue(); sb.append("The selected value in the comBoxField is: " + selectedValue + "\r\n"); } if (field instanceof PdfRadioButtonListFieldWidget) { PdfRadioButtonListFieldWidget radioBtnField = (PdfRadioButtonListFieldWidget)field; //Get value of radio button String value = radioBtnField.getValue(); sb.append("The text in radioButtonField is: " + value + "\r\n"); } if (field instanceof PdfCheckBoxWidgetFieldWidget) { PdfCheckBoxWidgetFieldWidget checkBoxField = (PdfCheckBoxWidgetFieldWidget)field; //Get the checked state of the checkbox boolean state = checkBoxField.getChecked(); sb.append("Is the checkBox checked? " + state + "\r\n"); } } try { //Write text into a .txt file FileWriter writer = new FileWriter("GetAllValues.txt"); writer.write(sb.toString()); writer.flush(); } catch (IOException e) { e.printStackTrace(); } pdf.close(); } }
C#/VB.NET: Generate QR Code with a Logo Image
When generating a QR code, you might want to add a custom image such as your company’s logo or your personal profile image to it. In this article, you will learn how to achieve this task programmatically in C# and VB.NET using Spire.Barcode for .NET library.
Install Spire.Barcode for .NET
To begin with, you need to add the DLL files included in the Spire.Barcode for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Barcode
Note: This feature relies on a commercial license. If you want to test it, please go to the end of this article to request a temporary license.
Generate QR Code with a Logo Image in C# and VB.NET
The following are the steps to generate a QR code with a logo image:
- Create a BarcodeSettings object.
- Set barcode type, error correction level and data etc. using BarcodeSettings.Type, BarcodeSettings.QRCodeECL and BarcodeSetting.Data properties.
- Set logo image using BarcodeSettings.QRCodeLogoImage property.
- Create a BarCodeGenerator object based on the settings.
- Generate QR code image using BarCodeGenerator.GenerateImage() method.
- Save the image using Image.Save() method.
- C#
- VB.NET
using Spire.Barcode; using Spire.License; using System.Drawing; namespace AddLogoToQR { class Program { static void Main(string[] args) { //Load license Spire.License.LicenseProvider.SetLicenseFileFullPath("license.elic.xml"); //Create a BarcodeSettings object BarcodeSettings settings = new BarcodeSettings(); //Set barcode type, error correction level, data, etc. settings.Type = BarCodeType.QRCode; settings.QRCodeECL = QRCodeECL.M; settings.ShowText = false; settings.X = 2.5f; string data = "www.e-iceblue.com"; settings.Data = data; settings.Data2D = data; //Set logo image settings.QRCodeLogoImage = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png"); //Generate QR image based on the settings BarCodeGenerator generator = new BarCodeGenerator(settings); Image image = generator.GenerateImage(); image.Save("QR.png", System.Drawing.Imaging.ImageFormat.Png); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#: Replace Text in a PDF Document
People often need to replace text in a PDF document for a variety of reasons. It could be to correct errors or typos, update outdated information, customize the content for a specific audience or purpose, or comply with legal or regulatory requirements. By replacing text in a PDF, individuals can ensure accuracy, maintain document integrity, and enhance the overall quality and relevance of the information presented.
In this article, you will learn how to replace text in a PDF document in C# by using the Spire.PDF for .NET library.
- Replace Text in a Specific PDF Page in C#
- Replace Text in an Entire PDF Document in C#
- Replace the First Occurrence of the Target Text in C#
- Replace Text Based on a Regular Expression in C#
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Replace Text in a Specific PDF Page in C#
Spire.PDF for .NET offers the PdfTextReplacer.ReplaceAllText() method, allowing users to replace all occurrences of target text in a page with new text. The following are the steps to replace text in a specific page using C#.
- Create a PdfDocument object.
- Load a PDF file for a specified path.
- Get a specific page from the document.
- Create a PdfTextReplaceOptions object, and specify the replace options using ReplaceType property of the object.
- Create a PdfTextReplacer object, and apply the replace options using Options property of it.
- Replace all occurrences of the target text in the page with new text using PdfTextReplacer.ReplaceAllText() method.
- Save the document to a different PDF file.
- C#
using Spire.Pdf; using Spire.Pdf.Texts; namespace ReplaceTextInPage { class Program { static void Main(string[] args) { // Create a PdfDocument object PdfDocument doc = new PdfDocument(); // Load a PDF file doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf"); // Create a PdfTextReplaceOptions object PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions(); // Specify the options for text replacement textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.IgnoreCase; textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.WholeWord; textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.AutofitWidth; // Get a specific page PdfPageBase page = doc.Pages[0]; // Create a PdfTextReplacer object based on the page PdfTextReplacer textReplacer = new PdfTextReplacer(page); // Set the replace options textReplacer.Options = textReplaceOptions; // Replace all occurrences of target text with new text textReplacer.ReplaceAllText(".NET Framework", "New Content"); // Save the document to a different PDF file doc.SaveToFile("ReplaceTextInPage.pdf"); // Dispose resources doc.Dispose(); } } }
Replace Text in an Entire PDF Document in C#
In order to replace all occurrences of target text in the entire document with new text, you need to iterate through pages in the document and replace text on each page using the PdfTextReplacer.ReplaceAllText() method.
The following are the steps to replace text in an entire PDF document using C#.
- Create a PdfDocument object.
- Load a PDF file for a specified path.
- Create a PdfTextReplaceOptions object, and specify the replace options using ReplaceType property of the object.
- Iterate through the pages in the document.
- Create a PdfTextReplacer object based on a specified page, and apply the replace options using Options property of it.
- Replace all occurrences of the target text in the page with new text using PdfTextReplacer.ReplaceAllText() method.
- Save the document to a different PDF file.
- C#
using Spire.Pdf; using Spire.Pdf.Texts; namespace ReplaceInEntireDocument { class Program { static void Main(string[] args) { // Create a PdfDocument object PdfDocument doc = new PdfDocument(); // Load a PDF file doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf"); // Create a PdfTextReplaceOptions object PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions(); // Specify the options for text replacement textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.IgnoreCase; textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.WholeWord; textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.AutofitWidth; for (int i = 0; i < doc.Pages.Count; i++) { // Get a specific page PdfPageBase page = doc.Pages[i]; // Create a PdfTextReplacer object based on the page PdfTextReplacer textReplacer = new PdfTextReplacer(page); // Set the replace options textReplacer.Options = textReplaceOptions; // Replace all occurrences of target text with new text textReplacer.ReplaceAllText(".NET Framework", "New Content"); } // Save the document to a different PDF file doc.SaveToFile("ReplaceTextInDocument.pdf"); // Dispose resources doc.Dispose(); } } }
Replace the First Occurrence of the Target Text in C#
Instead of replacing all text on a page, you can only replace the first occurrence of the target text by utilizing the ReplaceText() method of the PdfTextReplacer class.
The following are the steps to replace the first occurrence of the target text using C#.
- Create a PdfDocument object.
- Load a PDF file for a specified path.
- Get a specific page from the document.
- Create a PdfTextReplaceOptions object, and specify the replace options using ReplaceType property of the object.
- Create a PdfTextReplacer object, and apply the replace options using Options property of it.
- Replace the first occurrence of the target text in the page with new text using PdfTextReplacer.ReplaceText() method.
- Save the document to a different PDF file.
- C#
using Spire.Pdf; using Spire.Pdf.Texts; namespace ReplaceFirstOccurance { class Program { static void Main(string[] args) { // Create a PdfDocument object PdfDocument doc = new PdfDocument(); // Load a PDF file doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf"); // Create a PdfTextReplaceOptions object PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions(); // Specify the options for text replacement textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.IgnoreCase; textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.WholeWord; textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.AutofitWidth; // Get a specific page PdfPageBase page = doc.Pages[1]; // Create a PdfTextReplacer object based on the page PdfTextReplacer textReplacer = new PdfTextReplacer(page); // Set the replace options textReplacer.Options = textReplaceOptions; // Replace the first occurrence of target text with new text textReplacer.ReplaceText(".NET Framework", "New Content"); // Save the document to a different PDF file doc.SaveToFile("ReplaceFirstOccurance.pdf"); // Dispose resources doc.Dispose(); } } }
Replace Text Based on a Regular Expression in C#
Regular expressions are powerful and versatile patterns used for matching and manipulating text. With Spire.PDF, you utilize regular expressions to search for specific text patterns in a PDF and replace them with new strings.
The steps to replace text in PDF based on a regular expression are as follows.
- Create a PdfDocument object.
- Load a PDF file for a specified path.
- Get a specific page from the document.
- Create a PdfTextReplaceOptions object.
- Specify the replace type as Regex using PdfTextReplaceOptions.ReplaceType property.
- Create a PdfTextReplacer object, and apply the replace options using Options property of it.
- Find and replace the text that matches a specified regular expression using PdfTextReplacer.ReplaceAllText() method.
- Save the document to a different PDF file.
- C#
using Spire.Pdf; using Spire.Pdf.Texts; namespace ReplaceUsingRegularExpression { class Program { static void Main(string[] args) { // Create a PdfDocument object PdfDocument doc = new PdfDocument(); // Load a PDF file doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf"); // Create a PdfTextReplaceOptions object PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions(); // Set the replace type as Regex textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.Regex; // Get a specific page PdfPageBase page = doc.Pages[1]; // Create a PdfTextReplacer object based on the page PdfTextReplacer textReplacer = new PdfTextReplacer(page); // Set the replace options textReplacer.Options = textReplaceOptions; // Specify the regular expression string regularExpression = @"\bC\w*?R\b"; // Replace all occurrences that match the regular expression with new text textReplacer.ReplaceAllText(regularExpression, "NEW"); // Save the document to a different PDF file doc.SaveToFile("ReplaceWithRegularExpression.pdf"); // Dispose resources doc.Dispose(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Add Tooltip to the Searched Text on PDF in C#
This article demonstrates how to add tooltip to the text on an existing PDF document in C#. Spire.PDF for .NET supports to create tooltips by adding invisible button over the searched text from the PDF file.
Step 1: Load the sample document file.
PdfDocument doc = new PdfDocument(); doc.LoadFromFile("Sample.pdf");
Step 2: Searched the text “Add tooltip to PDF” from the first page of the sample document and get the position of it.
PdfPageBase page = doc.Pages[0]; PdfTextFind[] result = page.FindText("Add tooltip to PDF").Finds; RectangleF rec = result[0].Bounds;
Step 3: Create invisible button on text position
PdfButtonField field1 = new PdfButtonField(page, "field1"); field1.Bounds = rec;
Step 4: Set the content and format for the tooltip field.
field1.ToolTip = "E-iceblue Co. Ltd., a vendor of .NET, Java and WPF development components"; field1.BorderWidth = 0; field1.BackColor = Color.Transparent; field1.ForeColor = Color.Transparent; field1.LayoutMode = PdfButtonLayoutMode.IconOnly; field1.IconLayout.IsFitBounds = true;
Step 5: Save the document to file.
doc.SaveToFile("Addtooltip.pdf", FileFormat.PDF);
Effective screenshot after adding the tooltip to PDF:
using Spire.Pdf; using Spire.Pdf.Fields; using Spire.Pdf.General.Find; using System.Drawing; namespace TooltipPDF { class Program { static void Main(string[] args) { PdfDocument doc = new PdfDocument(); doc.LoadFromFile("Sample.pdf"); PdfPageBase page = doc.Pages[0]; PdfTextFind[] result = page.FindText("Add tooltip to PDF").Finds; RectangleF rec = result[0].Bounds; PdfButtonField field1 = new PdfButtonField(page, "field1"); field1.Bounds = rec; field1.ToolTip = "E-iceblue Co. Ltd., a vendor of .NET, Java and WPF development components"; field1.BorderWidth = 0; field1.BackColor = Color.Transparent; field1.ForeColor = Color.Transparent; field1.LayoutMode = PdfButtonLayoutMode.IconOnly; field1.IconLayout.IsFitBounds = true; doc.SaveToFile("Addtooltip.pdf", FileFormat.PDF); } } }
Apply a Style to an Entire Excel Worksheet in C#
Starting from version 9.9.5, Spire.XLS supports applying style to an entire excel worksheet. This article will show you how to apply a style to an entire excel worksheet using Spire.XLS.
Detail steps:
Step 1: Instantiate a Workbook object and load the excel file.
Workbook workbook = new Workbook(); workbook.LoadFromFile("Input.xlsx");
Step 2: Get the first worksheet.
Worksheet sheet = workbook.Worksheets[0];
Step 3: Create a cell style, specify the cell background color, font color and font size.
CellStyle style = workbook.Styles.Add("newStyle"); style.Color = Color.DarkGray; style.Font.Color = Color.White; style.Font.Size = 15;
Step 4: Apply the style to the first worksheet.
sheet.ApplyStyle(style);
Step 5: Save the resultant file.
workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);
Output:
Full code:
using System.Drawing; using Spire.Xls; namespace StyleEntireWorksheet { class Program { static void Main(string[] args) { //Create a Workbook instance and load the excel file Workbook workbook = new Workbook(); workbook.LoadFromFile("Input.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Create a cell style CellStyle style = workbook.Styles.Add("newStyle"); style.Color = Color.DarkGray; style.Font.Color = Color.White; style.Font.Size = 15; //Apply the style to the first worksheet sheet.ApplyStyle(style); //Save the resultant file workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013); } } }
Java: Add Page Numbers to a PDF Document
Page numbers provide clarity and structure to the content, making it easier for readers to navigate through the document. By including page numbers, readers can quickly locate specific information or refer to a specific page. Adding page numbers to a PDF document is a common requirement when creating professional and organized files. Whether you're working on a report, a thesis, or any other type of PDF document, incorporating page numbers enhances the overall readability and professionalism of your work.
In this article, you will learn how to add page numbers to a PDF document at the footer section using Spire.PDF for Java.
- Add Page Numbers to the Left Corner of PDF Footer
- Add Page Numbers to the Center of PDF Footer
- Add Page Numbers to the Right Corner of PDF Footer
Install Spire.PDF for Java
You're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.pdf</artifactId> <version>10.4.4</version> </dependency> </dependencies>
PDF Coordinate System
When using Spire.PDF for Java to manipulate an existing PDF document, the coordinate system's origin is positioned at the top left corner of the page. The x-axis extends to the right, while the y-axis extends downward.
In general, page numbers are commonly positioned in the header or footer section of a document. As a result, it is important to consider the page size and margins when deciding where to place the page numbers.
Add Page Numbers to the Left Corner of PDF Footer in Java
Spire.PDF for Java offers the PdfPageNumberField class and the PdfPageCountField class, which reflect the current page number and the total page count when added to a page of a PDF document. To insert a piece of text like "Page X" or "Page X of Y", you can use a PdfCompositeField object to combine the text with one or more fields into a single field.
To add "Page X of Y" to the left corner of PDF footer, follow the steps below.
- Create a Document object.
- Load a PDF file from a specified page.
- Create a PdfPageNumberField object and a PdfPageCountField object.
- Create a PdfCompositeField object to create a "Page X of Y" format.
- Specify the location of the PdfCompositeField object using PdfCompositeField.setLocation() method.
- Iterate though the pages in the document, and add "Page X of Y" to the left corner of the footer section using PdfCompositeField.draw() method.
- Save the document to a different PDF file.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.automaticfields.PdfCompositeField; import com.spire.pdf.automaticfields.PdfPageCountField; import com.spire.pdf.automaticfields.PdfPageNumberField; import com.spire.pdf.graphics.*; import com.spire.pdf.license.LicenseProvider; import java.awt.*; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; public class AddPageNumberToLeftCorner { public static void main(String[] args) { // Apply your license key LicenseProvider.setLicenseKey("License Key"); // Create a PdfDocument object PdfDocument doc = new PdfDocument(); // Load a PDF file doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf"); // Create font, brush and pen, which determine the appearance of the page numbers to be added PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 12),true); PdfBrush brush = PdfBrushes.getBlack(); PdfPen pen = new PdfPen(brush, 1.0); // Create a PdfPageNumberField object and a PdfPageCountField object PdfPageNumberField pageNumberField = new PdfPageNumberField(); PdfPageCountField pageCountField = new PdfPageCountField(); // Create a PdfCompositeField object to combine page count field and page number field in a single field PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField); // Get the page size Dimension2D pageSize = doc.getPages().get(0).getSize(); // Set the location of the composite field compositeField.setLocation(new Point2D.Float(72, (float) pageSize.getHeight() - 45)); // Iterate through the pages in the document for (int i = 0; i < doc.getPages().getCount(); i++) { // Get a specific page PdfPageBase page = doc.getPages().get(i); // Draw a line at the specified position page.getCanvas().drawLine(pen, 72, pageSize.getHeight() - 50, pageSize.getWidth() - 72, pageSize.getHeight() - 50); // Draw the composite field on the page compositeField.draw(page.getCanvas(), 0.0, 0.0); } // Save to a different PDF file doc.saveToFile("Output/AddPageNumbersToLeftCorner.pdf"); // Dispose resources doc.dispose(); } }
Add Page Numbers to the Center of PDF Footer in Java
To center-align the page number in the footer section, it is necessary to dynamically calculate the width of the text "Page X of Y." This calculation is important because the X coordinate of the page number (PdfCompositeField) will be determined by subtracting the width of the page number from the page width and then dividing the result by 2, i.e., (PageWidth - PageNumberWidth)/2.
The steps to add page numbers to the center of PDF footer are as follows.
- Create a Document object.
- Load a PDF file from a specified page.
- Create a PdfPageNumberField object and a PdfPageCountField object.
- Create a PdfCompositeField object to create a "Page X of Y" format.
- Specify the location of the PdfCompositeField object using PdfCompositeField.setLocation() method.
- Iterate though the pages in the document, and add "Page X of Y" to the center of the footer section using PdfCompositeField.draw() method.
- Save the document to a different PDF file.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.automaticfields.PdfCompositeField; import com.spire.pdf.automaticfields.PdfPageCountField; import com.spire.pdf.automaticfields.PdfPageNumberField; import com.spire.pdf.graphics.PdfBrush; import com.spire.pdf.graphics.PdfBrushes; import com.spire.pdf.graphics.PdfPen; import com.spire.pdf.graphics.PdfTrueTypeFont; import com.spire.pdf.license.LicenseProvider; import java.awt.*; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; public class AddPageNumberToCenter { public static void main(String[] args) { // Apply your license key LicenseProvider.setLicenseKey("License Key"); // Create a PdfDocument object PdfDocument doc = new PdfDocument(); // Load a PDF file doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf"); // Create font, brush and pen, which determine the appearance of the page numbers to be added PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 12),true); PdfBrush brush = PdfBrushes.getBlack(); PdfPen pen = new PdfPen(brush, 1.0); // Create a PdfPageNumberField object and a PdfPageCountField object PdfPageNumberField pageNumberField = new PdfPageNumberField(); PdfPageCountField pageCountField = new PdfPageCountField(); // Create a PdfCompositeField object to combine page count field and page number field in a single field PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField); // Iterate through the pages in the document for (int i = 0; i < doc.getPages().getCount(); i++) { // Get a specific page PdfPageBase page = doc.getPages().get(i); // Get the page size Dimension2D pageSize = doc.getPages().get(i).getSize(); // Draw a line at the specified position page.getCanvas().drawLine(pen, 72, pageSize.getHeight() - 50, pageSize.getWidth() - 72, pageSize.getHeight() - 50); // Measure the size the "Page X of Y" Dimension2D pageNumberSize = font.measureString(String.format("Page %d of %d", i + 1, doc.getPages().getCount())); // Set the location of the composite field compositeField.setLocation(new Point2D.Float((float)(pageSize.getWidth() - pageNumberSize.getWidth())/2, (float)pageSize.getHeight() - 45)); // Draw the composite field on the page compositeField.draw(page.getCanvas()); } // Save to a different PDF file doc.saveToFile("Output/AddPageNumbersToCenter.pdf"); // Dispose resources doc.dispose(); } }
Add Page Numbers to the Right Corner of PDF Footer in Java
To position the page number at the right corner of the footer section, it is necessary to dynamically calculate the width of the text "Page X of Y" as well. Because the X coordinate of the page number (PdfCompositeField) will be determined by subtracting the width of the page number and the right page margin from the page width, i.e., PageWidth - PageNumberWidth - RightPageMargin.
The steps to add page numbers to the right corner of PDF footer are as follows.
- Create a Document object.
- Load a PDF file from a specified page.
- Create a PdfPageNumberField object and a PdfPageCountField object.
- Create a PdfCompositeField object to create a "Page X of Y" format.
- Specify the location of the PdfCompositeField object using PdfCompositeField.setLocation() method.
- Iterate though the pages in the document, and add "Page X of Y" to the right corner of the footer section using PdfCompositeField.draw() method.
- Save the document to a different PDF file.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.automaticfields.PdfCompositeField; import com.spire.pdf.automaticfields.PdfPageCountField; import com.spire.pdf.automaticfields.PdfPageNumberField; import com.spire.pdf.graphics.PdfBrush; import com.spire.pdf.graphics.PdfBrushes; import com.spire.pdf.graphics.PdfPen; import com.spire.pdf.graphics.PdfTrueTypeFont; import com.spire.pdf.license.LicenseProvider; import java.awt.*; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; public class AddPageNumberToRightCorner { public static void main(String[] args) { // Apply your license key LicenseProvider.setLicenseKey("License Key"); // Create a PdfDocument object PdfDocument doc = new PdfDocument(); // Load a PDF file doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf"); // Create font, brush and pen, which determine the appearance of the page numbers to be added PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 12),true); PdfBrush brush = PdfBrushes.getBlack(); PdfPen pen = new PdfPen(brush, 1.0); // Create a PdfPageNumberField object and a PdfPageCountField object PdfPageNumberField pageNumberField = new PdfPageNumberField(); PdfPageCountField pageCountField = new PdfPageCountField(); // Create a PdfCompositeField object to combine page count field and page number field in a single field PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField); // Iterate through the pages in the document for (int i = 0; i < doc.getPages().getCount(); i++) { // Get a specific page PdfPageBase page = doc.getPages().get(i); // Get the page size Dimension2D pageSize = doc.getPages().get(i).getSize(); // Draw a line at the specified position page.getCanvas().drawLine(pen, 72, pageSize.getHeight() - 50, pageSize.getWidth() - 72, pageSize.getHeight() - 50); // Measure the size the "Page X of Y" Dimension2D pageNumberSize = font.measureString(String.format("Page %d of %d", i + 1, doc.getPages().getCount())); // Set the location of the composite field compositeField.setLocation(new Point2D.Float((float)(pageSize.getWidth() - pageNumberSize.getWidth() - 72), (float)(pageSize.getHeight() - 45))); // Draw the composite field on the page compositeField.draw(page.getCanvas()); } // Save to a different PDF file doc.saveToFile("Output/AddPageNumbersToRightCorner.pdf"); // Dispose resources doc.dispose(); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Group Shapes in PowerPoint in Java
This article demonstrates how to group shapes in a PowerPoint document using Spire.Presentation for Java.
import com.spire.presentation.*; import com.spire.presentation.drawing.FillFormatType; import java.awt.geom.Rectangle2D; import java.util.ArrayList; public class GroupShapes { public static void main(String[] args) throws Exception { //create a PowerPoint document Presentation ppt = new Presentation(); //get the first slide ISlide slide = ppt.getSlides().get(0); //add a rectangle shape to the slide IShape rectangle = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Double(20,100,200,40)); rectangle.getFill().setFillType(FillFormatType.SOLID); rectangle.getFill().getSolidColor().setKnownColor(KnownColors.GOLD); rectangle.getLine().setWidth(0.1f); //add a ribbon shape to the slide IShape ribbon = slide.getShapes().appendShape(ShapeType.RIBBON_2, new Rectangle2D.Double(60, 75, 120, 80)); ribbon.getFill().setFillType(FillFormatType.SOLID); ribbon.getFill().getSolidColor().setKnownColor(KnownColors.PURPLE); ribbon.getLine().setWidth(0.1f); //add the shapes to a list ArrayList list = new ArrayList(); list.add((Shape)rectangle); list.add((Shape)ribbon); //group the shapes ppt.getSlides().get(0).groupShapes(list); //save the resultant document ppt.saveToFile("GroupShapes.pptx", FileFormat.PPTX_2013); } }
Java Create Barcode to Word Document
This article demonstrates how to add barcode to a word document in Java applications with the help of Spire.Doc for Java. Firstly, please ensure that the barcode font has been install on the system. The installed font could be found from C:\Windows\Fonts.
import com.spire.doc.*; import com.spire.doc.documents.Paragraph; import com.spire.doc.fields.TextRange; public class AddBarcodetoWord{ public static void main(String[] args) { // Create Document Document document = new Document(); //Add a section Section section = document.addSection(); //Add s paragraph to the section Paragraph para = section.addParagraph(); //Add barcode and set format TextRange tr = para.appendText("H63TWX11072"); tr.getCharacterFormat().setFontName("C39HrP60DlTt"); tr.getCharacterFormat().setFontSize(80f); //Save the document to file document.saveToFile("Barcode.docx", FileFormat.Docx); } }
Effective screenshot after add barcode to Word:
Replace Text in PowerPoint in Java
This article demonstrates how to replace text in an exising PowerPoint document with new text using Spire.Presentation for Java.
import com.spire.presentation.*; import java.util.HashMap; import java.util.Map; public class ReplaceText { public static void main(String[] args) throws Exception { //create a Presentation object Presentation presentation = new Presentation(); //load the template file presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.pptx"); //get the first slide ISlide slide= presentation.getSlides().get(0); //create a Map object Map map = new HashMap(); //add several pairs of keys and values to the map map.put("#name#","John Smith"); map.put("#age#","28"); map.put("#address#","Oklahoma City, United States"); map.put("#tel#","333 123456"); map.put("#email#","johnsmith@outlook.com"); //replace text in the slide replaceText(slide,map); //save to another file presentation.saveToFile("output/ReplaceText.pptx", FileFormat.PPTX_2013); } /** * Replace text within a slide * @param slide Specifies the slide where the replacement happens * @param map Where keys are existing strings in the document and values are the new strings to replace the old ones */ public static void replaceText(ISlide slide, Map map) { for (Object shape : slide.getShapes() ) { if (shape instanceof IAutoShape) { for (Object paragraph : ((IAutoShape) shape).getTextFrame().getParagraphs() ) { ParagraphEx paragraphEx = (ParagraphEx)paragraph; for (String key : map.keySet() ) { if (paragraphEx.getText().contains(key)) { paragraphEx.setText(paragraphEx.getText().replace(key, map.get(key))); } } } } } } }