Java: Create, Fill, or Remove Fillable Form Fields in PDF
A fillable PDF form is useful for collecting data from users. Being able to create interactive and fillable PDF forms is important since PDF has become one of the most popular file formats in business. This article demonstrates how to create, fill, or remove fillable form fields in PDF using Spire.PDF for Java.
- Create Fillable Form Fields in a PDF Document
- Fill Form Fields in an Existing PDF Document
- Delete a Particular Field or All Fields in an Existing PDF Document
Spire.PDF for Java offers a series of useful classes under the com.spire.pdf.fields namespace, allowing programmers to create and edit various types of form fields including text box, check box, combo box, list box, and radio button. The table below lists some of the core classes involved in this tutorial.
Class | Description |
PdfForm | Represents interactive form of the PDF document. |
PdfField | Represents field of the PDF document's interactive form. |
PdfTextBoxField | Represents text box field in the PDF form. |
PdfCheckBoxField | Represents check box field in the PDF form. |
PdfComboBoxField | Represents combo box field in the PDF Form. |
PdfListBoxField | Represents list box field of the PDF form. |
PdfListFieldItem | Represents an item of a list field. |
PdfRadioButtonListField | Represents radio button field in the PDF form. |
PdfRadioButtonListItem | Represents an item of a radio button list. |
PdfButtonField | Represents button field in the PDF form. |
PdfSignatureField | Represents signature field in the PDF form. |
Install Spire.PDF for Java
First, 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>
Create Fillable Form Fields in a PDF Document in Java
To create a field, initialize an instance of the corresponding class. Specify its size and position in the document using setBounds() method, and then add it to PDF using PdfForm.getFields().add() method. The following are the steps to create various types of form fields in a PDF document using Spire.PDF for Java.
- Create a PdfDocument object.
- Add a page using PdfDocuemnt.getPages().add() method.
- Create a PdfTextBoxField object, set the properties of the field including Bounds, Font and Text, and then add it to the document using PdFormfFieldCollection.add() method.
- Repeat the step 3 to add check box, combo box, list box, radio button, signature field and button to the document.
- Save the document to a PDF file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.FileFormat; import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.actions.PdfSubmitAction; import com.spire.pdf.fields.*; import com.spire.pdf.graphics.*; import com.spire.pdf.packages.sprcfn; import java.awt.*; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; public class CreateFillableFormFields { public static void main(String[] args) throws Exception { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Add a page PdfPageBase page = doc.getPages().add(); //Initialize x and y coordinates float baseX = 100; float baseY = 30; //Create two brush objects PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.blue)); PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.black)); //Create a font PdfFont font = new PdfFont(PdfFontFamily.Times_Roman, 12f, PdfFontStyle.Regular); //Add a textbox page.getCanvas().drawString("TextBox:", font, brush1, new Point2D.Float(10, baseY)); Rectangle2D.Float tbxBounds = new Rectangle2D.Float(baseX, baseY, 150, 15); PdfTextBoxField textBox = new PdfTextBoxField(page, "textbox"); textBox.setBounds(tbxBounds); textBox.setText("Hello World"); textBox.setFont(font); doc.getForm().getFields().add(textBox); baseY += 25; //add two checkboxes page.getCanvas().drawString("CheckBox:", font, brush1, new Point2D.Float(10, baseY)); Rectangle2D.Float checkboxBound1 = new Rectangle2D.Float(baseX, baseY, 15, 15); PdfCheckBoxField checkBoxField1 = new PdfCheckBoxField(page, "checkbox1"); checkBoxField1.setBounds(checkboxBound1); checkBoxField1.setChecked(false); page.getCanvas().drawString("Option 1", font, brush2, new Point2D.Float(baseX + 20, baseY)); Rectangle2D.Float checkboxBound2 = new Rectangle2D.Float(baseX + 70, baseY, 15, 15); PdfCheckBoxField checkBoxField2 = new PdfCheckBoxField(page, "checkbox2"); checkBoxField2.setBounds(checkboxBound2); checkBoxField2.setChecked(false); page.getCanvas().drawString("Option 2", font, brush2, new Point2D.Float(baseX + 90, baseY)); doc.getForm().getFields().add(checkBoxField1); doc.getForm().getFields().add(checkBoxField2); baseY += 25; //Add a listbox page.getCanvas().drawString("ListBox:", font, brush1, new Point2D.Float(10, baseY)); Rectangle2D.Float listboxBound = new Rectangle2D.Float(baseX, baseY, 150, 50); PdfListBoxField listBoxField = new PdfListBoxField(page, "listbox"); listBoxField.getItems().add(new PdfListFieldItem("Item 1", "item1")); listBoxField.getItems().add(new PdfListFieldItem("Item 2", "item2")); listBoxField.getItems().add(new PdfListFieldItem("Item 3", "item3")); ; listBoxField.setBounds(listboxBound); listBoxField.setFont(font); listBoxField.setSelectedIndex(0); doc.getForm().getFields().add(listBoxField); baseY += 60; //Add two radio buttons page.getCanvas().drawString("RadioButton:", font, brush1, new Point2D.Float(10, baseY)); PdfRadioButtonListField radioButtonListField = new PdfRadioButtonListField(page, "radio"); PdfRadioButtonListItem radioItem1 = new PdfRadioButtonListItem("option1"); Rectangle2D.Float radioBound1 = new Rectangle2D.Float(baseX, baseY, 15, 15); radioItem1.setBounds(radioBound1); page.getCanvas().drawString("Option 1", font, brush2, new Point2D.Float(baseX + 20, baseY)); PdfRadioButtonListItem radioItem2 = new PdfRadioButtonListItem("option2"); Rectangle2D.Float radioBound2 = new Rectangle2D.Float(baseX + 70, baseY, 15, 15); radioItem2.setBounds(radioBound2); page.getCanvas().drawString("Option 2", font, brush2, new Point2D.Float(baseX + 90, baseY)); radioButtonListField.getItems().add(radioItem1); radioButtonListField.getItems().add(radioItem2); radioButtonListField.setSelectedIndex(0); doc.getForm().getFields().add(radioButtonListField); baseY += 25; //Add a combobox page.getCanvas().drawString("ComboBox:", font, brush1, new Point2D.Float(10, baseY)); Rectangle2D.Float cmbBounds = new Rectangle2D.Float(baseX, baseY, 150, 15); PdfComboBoxField comboBoxField = new PdfComboBoxField(page, "combobox"); comboBoxField.setBounds(cmbBounds); comboBoxField.getItems().add(new PdfListFieldItem("Item 1", "item1")); comboBoxField.getItems().add(new PdfListFieldItem("Item 2", "itme2")); comboBoxField.getItems().add(new PdfListFieldItem("Item 3", "item3")); comboBoxField.getItems().add(new PdfListFieldItem("Item 4", "item4")); comboBoxField.setSelectedIndex(0); comboBoxField.setFont(font); doc.getForm().getFields().add(comboBoxField); baseY += 25; //Add a signature field page.getCanvas().drawString("Signature Field:", font, brush1, new Point2D.Float(10, baseY)); PdfSignatureField sgnField = new PdfSignatureField(page, "sgnField"); Rectangle2D.Float sgnBounds = new Rectangle2D.Float(baseX, baseY, 150, 80); sgnField.setBounds(sgnBounds); doc.getForm().getFields().add(sgnField); baseY += 90; //Add a button page.getCanvas().drawString("Button:", font, brush1, new Point2D.Float(10, baseY)); Rectangle2D.Float btnBounds = new Rectangle2D.Float(baseX, baseY, 50, 15); PdfButtonField buttonField = new PdfButtonField(page, "button"); buttonField.setBounds(btnBounds); buttonField.setText("Submit"); buttonField.setFont(font); PdfSubmitAction submitAction = new PdfSubmitAction("https://www.e-iceblue.com/getformvalues.php"); buttonField.getActions().setMouseDown(submitAction); doc.getForm().getFields().add(buttonField); //Save to file doc.saveToFile("FillableForm.pdf", FileFormat.PDF); } }
Fill Form Fields in an Existing PDF Document in Java
In order to fill out a form, we must first get all the form fields from the PDF document, determine the type of a certain field, and then input a value or select a value from a predefined list. The following are the steps to fill form fields in an existing PDF document using Spire.PDF for Java.
- Create a PdfDocument object.
- Load a sample PDF document using PdfDocument.loadFromFile() method.
- Get the form from the document through PdfDocument.getForm() method.
- Get the form field widget collection through PdfFormWidget.getFieldsWidget() method.
- Loop through the field widget collection to get a specific PdfField.
- Determine if the PdfField is a certain field type such as text box. If yes, set the text of the text box using PdfTextBoxFieldWidget.setText() method.
- Repeat the sixth step to fill radio button, check box, combo box, and list box with values.
- Save the document to a PDF file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.FileFormat; import com.spire.pdf.PdfDocument; import com.spire.pdf.fields.PdfField; import com.spire.pdf.widget.*; public class FillFormFields { public static void main(String[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Load a template containing forms doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\FormsTemplate.pdf"); //Get the form from the document PdfFormWidget form = (PdfFormWidget)doc.getForm(); //Get the form widget collection PdfFormFieldWidgetCollection formWidgetCollection = form.getFieldsWidget(); //Loop through the widgets for (int i = 0; i < formWidgetCollection.getCount(); i++) { //Get a specific field PdfField field = formWidgetCollection.get(i); //Determine if the field is a text box if (field instanceof PdfTextBoxFieldWidget) { if (field.getName().equals("name")) { //Set the text of text box PdfTextBoxFieldWidget textBoxField = (PdfTextBoxFieldWidget)field; textBoxField.setText("Kaila Smith"); } } //Determine if the field is a radio button if (field instanceof PdfRadioButtonListFieldWidget) { if (field.getName().equals("gender")) { //Set the selected index of radio button PdfRadioButtonListFieldWidget radioButtonListField = (PdfRadioButtonListFieldWidget)field; radioButtonListField.setSelectedIndex(1); } } //Determine if the field is a combo box if (field instanceof PdfComboBoxWidgetFieldWidget) { if (field.getName().equals("country")) { //Set the selected index of combo box PdfComboBoxWidgetFieldWidget comboBoxField = (PdfComboBoxWidgetFieldWidget)field; comboBoxField.setSelectedIndex(0); } } //Determine if the field is a check box if (field instanceof PdfCheckBoxWidgetFieldWidget) { //Set the "Checked" status of check box PdfCheckBoxWidgetFieldWidget checkBoxField = (PdfCheckBoxWidgetFieldWidget)field; switch (checkBoxField.getName()) { case "travel": case "movie": checkBoxField.setChecked(true); break; } } //Determine if the field is a list box if (field instanceof PdfListBoxWidgetFieldWidget) { if (field.getName().equals("degree")) { //Set the selected index of list box PdfListBoxWidgetFieldWidget listBox = (PdfListBoxWidgetFieldWidget)field; listBox.setSelectedIndex(1); } } } //Save to file doc.saveToFile("FillFormFields.pdf", FileFormat.PDF); } }
Delete a Particular Field or All Fields in an Existing PDF Document in Java
A form field in a PDF document can be accessed by its index or name and removed by PdfFieldCollection.remove() method. The following are the steps to remove a particular field or all fields from an existing PDF document using Sprie.PDF for Java.
- Create a PdfDocument object.
- Load a sample PDF document using PdfDocument.loadFromFile() method.
- Get the form from the document using PdfDocument.getForm() method.
- Get the form field widget collection using PdfFormWidget.getFieldsWidget() method.
- Loop through the widget collection to get a specific PdfField. Remove the field one by one using PdfFieldCollection.remove() method.
- To remove a certain form field, get it from the document using PdfFormFieldWidgetCollection.get() method and then call the PdfFieldCollection.remove() method.
- Save the document to a PDF file using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.fields.PdfField; import com.spire.pdf.widget.PdfFormFieldWidgetCollection; import com.spire.pdf.widget.PdfFormWidget; public class DeleteFormFields { public static void main(String[] args) { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Load a PDF file doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\FormsTemplate.pdf"); //Get the form from the document PdfFormWidget form= (PdfFormWidget)doc.getForm(); //Get form widgets from the form PdfFormFieldWidgetCollection widgets = form.getFieldsWidget(); //Loop through the widgets for (int i = widgets.getCount() - 1; i >= 0; i--) { //Get a specific field PdfField field = (PdfField)widgets.getList().get(i) ; //Remove the field widgets.remove(field); } //Get a specific field by its name //PdfField field = widgets.get("name"); //Remove the field //widgets.remove(field); //Save to file doc.saveToFile("DeleteAllFields.pdf"); } }
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.
Split Table Cells in PowerPoint in C#
This article is going to demonstrate how to split a specific table cell in PowerPoint using Spire.Presentation.
The original table:
Detail steps:
Step 1: Instantiate a Presentation object and load the PowerPoint file.
Presentation ppt = new Presentation(); ppt.LoadFromFile("Input.pptx");
Step 2: Get the first slide.
ISlide slide = ppt.Slides[0];
Step 3: Get the table on the slide.
ITable table = slide.Shapes[0] as ITable;
Step 4: Split the cell [1, 2] into 3 rows and 2 columns.
table[1, 2].Split(3, 2);
Step 5: Save the file.
ppt.SaveToFile("Split.pptx", FileFormat.Pptx2013);
Screenshot after splitting:
Full code:
using Spire.Presentation; namespace Split_Table_Cells_in_PPT { class Program { static void Main(string[] args) { //Instantiate a Presentation object Presentation ppt = new Presentation(); //Load the PowerPoint file ppt.LoadFromFile("Input.pptx"); //Get the first slide ISlide slide = ppt.Slides[0]; //Get the table ITable table = slide.Shapes[0] as ITable; //Split cell [1, 2] into 3 rows and 2 columns table[1, 2].Split(3, 2); //Save the file ppt.SaveToFile("Split.pptx", FileFormat.Pptx2013); } } }
Java: Create a PDF Document
Generating PDFs through code provides various advantages. It enables integration of dynamic content such as real-time data, database records, and user input. Code-based PDF creation offers greater customization and automation, reducing manual involvement in developing personalized documents. In this article, you will learn how to create a simple PDF document from scratch in Java using Spire.PDF for Java.
Install Spire.PDF for Java
First, 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>
Background Knowledge
A page in Spire.PDF for Java (represented by PdfPageBase class) consists of client area and margins all around. The content area is for users to write various contents, and the margins are usually blank edges.
As shown in the figure below, the origin of the coordinate system on the page is located at the top left corner of the client area, with the x-axis extending horizontally to the right and the y-axis extending vertically down. All elements added to the client area must be based on the specified coordinates.
In addition, the following table lists the important classes and methods, which can help you easily understand the code snippet provided in the following section.
Member | Description |
PdfDocument class | Represents a PDF document model. |
PdfPageBase class | Represents a page in a PDF document. |
PdfSolidBrush class | Represents a brush that fills any object with a solid color. |
PdfTrueTypeFont class | Represents a true type font. |
PdfStringFormat class | Represents text format information, such as alignment, characters spacing and indent. |
PdfTextWidget class | Represents the text area with the ability to span several pages. |
PdfTextLayout class | Represents the text layout information. |
PdfDocument.getPages().add() method | Adds a page to a PDF document. |
PdfPageBase.getCanvas().drawString() method | Draws string on a page at the specified location with specified font and brush objects. |
PdfTextWidget.draw() method | Draws the text widget on a page at the specified location. |
PdfDocument.save() method | Saves the document to a PDF file. |
Create a PDF Document from Scratch in Java
Despite the fact that Spire.PDF for Java enables users to add various elements to PDF documents, this article demonstrates how to create a simple PDF document with only plain text. The following are the detailed steps.
- Create a PdfDocument object.
- Add a page using PdfDocument.getPages().add() method.
- Create brush and font objects.
- Draw string on the page at a specified coordinate using PdfPageBase.getCanvas().drawString() method.
- Create a PdfTextWidget object to hold a chunk of text.
- Draw the text widget on the page at a specified location using PdfTextWidget.draw() method
- Save the document to a PDF file using PdfDocument.save() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.PdfPageSize; import com.spire.pdf.graphics.*; import java.awt.*; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.*; public class CreatePdfDocument { public static void main(String[] args) throws IOException { //Create a PdfDocument object PdfDocument doc = new PdfDocument(); //Add a page PdfPageBase page = doc.getPages().add(PdfPageSize.A4, new PdfMargins(35f)); //Specify title text String titleText = "What is MySQL"; //Create solid brushes PdfSolidBrush titleBrush = new PdfSolidBrush(new PdfRGBColor(Color.BLUE)); PdfSolidBrush paraBrush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK)); //Create true type fonts PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("Times New Roman",Font.BOLD,18)); PdfTrueTypeFont paraFont = new PdfTrueTypeFont(new Font("Times New Roman",Font.PLAIN,12)); //Set the text alignment via PdfStringFormat class PdfStringFormat format = new PdfStringFormat(); format.setAlignment(PdfTextAlignment.Center); //Draw title on the page page.getCanvas().drawString(titleText, titleFont, titleBrush, new Point2D.Float((float)page.getClientSize().getWidth()/2, 20),format); //Get paragraph text from a .txt file String paraText = readFileToString("C:\\Users\\Administrator\\Desktop\\content.txt"); //Create a PdfTextWidget object to hold the paragraph content PdfTextWidget widget = new PdfTextWidget(paraText, paraFont, paraBrush); //Create a rectangle where the paragraph content will be placed Rectangle2D.Float rect = new Rectangle2D.Float(0, 50, (float)page.getClientSize().getWidth(),(float)page.getClientSize().getHeight()); //Set the PdfLayoutType to Paginate to make the content paginated automatically PdfTextLayout layout = new PdfTextLayout(); layout.setLayout(PdfLayoutType.Paginate); //Draw paragraph text on the page widget.draw(page, rect, layout); //Save to file doc.saveToFile("output/CreatePdfDocument.pdf"); doc.dispose(); } //Convert a .txt file to String private static String readFileToString(String filepath) throws FileNotFoundException, IOException { StringBuilder sb = new StringBuilder(); String s =""; BufferedReader br = new BufferedReader(new FileReader(filepath)); while( (s = br.readLine()) != null) { sb.append(s + "\n"); } br.close(); String str = sb.toString(); return str; } }
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#/VB.NET: Convert Charts in Excel to Images
Charts are commonly used in Microsoft Excel files to visualize numeric data. In some cases, you may need to save the charts in an Excel file as images in order to use them in other programs or other files such as PDFs and PowerPoint presentations. In this article, we will demonstrate how to convert charts in Excel to images in C# and VB.NET using Spire.XLS for .NET.
- Convert a Specific Chart in an Excel Worksheet to Image
- Convert All Charts in an Excel Worksheet to Images
- Convert a Chart Sheet to Image in Excel
Install Spire.XLS for .NET
To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.XLS
Convert a Specific Chart in an Excel Worksheet to Image in C# and VB.NET
Spire.XLS provides the Workbook.SaveChartAsImage(Worksheet worksheet, int chartIndex) method which enables you to convert a specific chart in a worksheet as image. The following are the detailed steps:
- Initialize an instance of the Workbook class.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet by its index through Workbook.Worksheets[int worksheetIndex] property.
- Save a specific chart in the worksheet as image using Workbook.SaveChartAsImage(Worksheet worksheet, int chartIndex) method.
- Save the image to a PNG file.
- C#
- VB.NET
using Spire.Xls; using System.Drawing; using System.Drawing.Imaging; namespace ConvertAExcelChartToImage { internal class Program { static void Main(string[] args) { //Initialize an instance of the Workbook class Workbook workbook = new Workbook(); //Load a sample Excel file workbook.LoadFromFile("Charts.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Save the first chart in the first worksheet as image Image image = workbook.SaveChartAsImage(sheet, 0); //Save the image to .png file image.Save(@"output\chart.png", ImageFormat.Png); } } }
Convert All Charts in an Excel Worksheet to Images in C# and VB.NET
To convert all charts in an Excel worksheet to images, you can use the Workbook.SaveChartAsImage(Worksheet worksheet) method. The following are the detailed steps:
- Initialize an instance of the Workbook class.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet by its index through Workbook.Worksheets[int worksheetIndex] property.
- Save all charts in the worksheet as images using Workbook.SaveChartAsImage(Worksheet worksheet) method.
- Save the images to PNG files.
- C#
- VB.NET
using Spire.Xls; using System.Drawing; using System.Drawing.Imaging; namespace ConvertAllExcelChartsToImages { internal class Program { static void Main(string[] args) { //Initialize an instance of the Workbook class Workbook workbook = new Workbook(); //Load a sample Excel file workbook.LoadFromFile("Charts.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Save charts in the first worksheet as images Image[] imgs = workbook.SaveChartAsImage(sheet); //Save the images to png files for (int i = 0; i < imgs.Length; i++) { imgs[i].Save(string.Format(@"output\chart-{0}.png", i), ImageFormat.Png); } } } }
Convert a Chart Sheet to Image in Excel in C# and VB.NET
You can use the Workbook.SaveChartAsImage(ChartSheet chartSheet) method to convert a chart sheet in Excel to image. The following are the detailed steps:
- Initialize an instance of the Workbook class.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specific chart sheet by its index through Workbook.Chartsheets[int chartSheetIndex] property.
- Save the chart sheet as image using Workbook.SaveChartAsImage(ChartSheet chartSheet) method.
- Save the image to .png file.
- C#
- VB.NET
using Spire.Xls; using System.Drawing; using System.Drawing.Imaging; namespace ConvertExcelChartSheetToImage { internal class Program { static void Main(string[] args) { //Initialize an instance of the Workbook class Workbook workbook = new Workbook(); //Load a sample Excel file workbook.LoadFromFile("ChartSheet.xlsx"); //Get the first chart sheet ChartSheet chartSheet = workbook.Chartsheets[0]; //Save the first chart sheet as image Image image = workbook.SaveChartAsImage(chartSheet); //Save the image to .png file image.Save(@"output\chartSheet.png", 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.
Replace Image with New Image in PowerPoint in C#
This article demonstrates how to replace an existing image with a new image in a PowerPoint document using Spire.Presentation.
The original image:
Detail steps:
Step 1: Instantiate a Presentation object and load the PowerPoint file.
Presentation ppt = new Presentation(); ppt.LoadFromFile("Input.pptx");
Step 2: Get the first slide.
ISlide slide = ppt.Slides[0];
Step 3: Append a new image to replace an existing image.
IImageData image = ppt.Images.Append(Image.FromFile("timg.jpg"));
Step 4: Replace the image which title is "image1" with the new image.
foreach (IShape shape in slide.Shapes) { if (shape is SlidePicture) { if (shape.AlternativeTitle == "image1") { (shape as SlidePicture).PictureFill.Picture.EmbedImage = image; } } }
Step 5: Save the file.
ppt.SaveToFile("Output.pptx", FileFormat.Pptx2013);
Screenshot after replacing image:
Full code:
using Spire.Presentation; using Spire.Presentation.Drawing; using System.Drawing; namespace ReplaceImage { class Program { static void Main(string[] args) { { Presentation ppt = new Presentation(); ppt.LoadFromFile("Input.pptx"); ISlide slide = ppt.Slides[0]; IImageData image = ppt.Images.Append(Image.FromFile("timg.jpg")); foreach (IShape shape in slide.Shapes) { if (shape is SlidePicture) { if (shape.AlternativeTitle == "image1") { (shape as SlidePicture).PictureFill.Picture.EmbedImage = image; } } } ppt.SaveToFile("Output.pptx", FileFormat.Pptx2013); } } } }
Detect the used themes in PowerPoint in C#
This article demonstrates how to detect the used themes in a PowerPoint document using Spire.Presentation.
Detail steps:
Step 1: Instantiate a Presentation object and load the PowerPoint document.
Presentation ppt = new Presentation(); ppt.LoadFromFile(@"Sample.pptx");
Step 2: Get the theme name of each slide in the document.
StringBuilder sb = new StringBuilder(); string themeName = null; foreach (ISlide slide in ppt.Slides) { themeName = slide.Theme.Name; sb.AppendLine(themeName); }
Step 3: Save to a .txt file.
File.WriteAllText("themeName.txt", sb.ToString());
Output:
Full code:
using Spire.Presentation; using System.IO; using System.Text; namespace DetectThemes { class Program { static void Main(string[] args) { //Instantiate a Presentation object Presentation ppt = new Presentation(); //Load the PowerPoint document ppt.LoadFromFile(@"Sample.pptx"); StringBuilder sb = new StringBuilder(); string themeName = null; //Get the theme name of each slide in the document foreach (ISlide slide in ppt.Slides) { themeName = slide.Theme.Name; sb.AppendLine(themeName); } //Save to a .txt file File.WriteAllText("themeName.txt", sb.ToString()); } } }
Filter cells by cell color in Excel in C#
In Excel, cells can be filtered based on the cell color. This article is going to show you how to filter rows by cell color using Spire.XLS.
The example Excel file:
Detail steps:
Step 1: Instantiate a Workbook object and load the Excel file.
Workbook workbook = new Workbook(); workbook.LoadFromFile("sample.xlsx");
Step 2: Get the first worksheet.
Worksheet sheet = workbook.Worksheets[0];
Step 3: Add a color filter to filter cells based on cell color.
//Create an auto filter in the sheet and specify the range to be filterd sheet.AutoFilters.Range = sheet.Range["A1:A9"]; //Get the coloumn to be filterd FilterColumn filtercolumn = (FilterColumn)sheet.AutoFilters[0]; //Add a color filter to filter the column based on cell color sheet.AutoFilters.AddFillColorFilter(filtercolumn, Color.Red);
Step 4: Filter the data.
sheet.AutoFilters.Filter();
Step 5: Save the file.
workbook.SaveToFile("ColorFilter.xlsx", ExcelVersion.Version2013);
Screenshot:
Full code:
using Spire.Xls; using Spire.Xls.Core.Spreadsheet.AutoFilter; namespace FilterCells { class Program { static void Main(string[] args) { //Instantiate a Workbook object Workbook workbook = new Workbook(); //Load the Excel file workbook.LoadFromFile("sample.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Create an auto filter in the sheet and specify the range to be filterd sheet.AutoFilters.Range = sheet.Range["A1:A9"]; //Get the coloumn to be filterd FilterColumn filtercolumn = (FilterColumn)sheet.AutoFilters[0]; //Add a color filter to filter the column based on cell color sheet.AutoFilters.AddFillColorFilter(filtercolumn, Color.Red); //Filter the data sheet.AutoFilters.Filter(); //Save the file workbook.SaveToFile("ColorFilter.xlsx", ExcelVersion.Version2013); } } }
C#: Add or Remove AutoFilter in Excel
Excel's AutoFilter is a simple yet effective tool for managing data, especially when working with large datasets. By using AutoFilters, you can quickly narrow down your focus to specific subsets of information, making it easier to identify trends, make decisions, and keep your spreadsheets organized. Upon completion of the analysis, you may need to remove the AutoFilters to restore visibility to the full dataset. In this article, you will learn how to add or remove AutoFilter in Excel in C# using Spire.XLS for .NET.
- Add AutoFilter to Excel Cells in C#
- Apply Date AutoFilter in Excel in C#
- Apply Custom AutoFilter in Excel in C#
- Remove AutoFilter in Excel in C#
Install Spire.XLS for .NET
To begin with, you need to add the DLL files included in the Spire.XLS 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.XLS
Add AutoFilter to Excel Cells in C#
Spire.XLS for .NET allows you to apply AutoFilter on a specific cell range through the Worksheet.AutoFilters.Range property. The following are the detailed steps:
- Create a Workbook instance.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specified worksheet using Workbook.Worksheets[] property.
- Add an AutoFilter to a specified cell range using Worksheet.AutoFilters.Range property.
- Save the result file using Workbook.SaveToFile() method.
- C#
using Spire.Xls; namespace AddAutoFilter { class Program { static void Main(string[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Load an Excel file workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Data.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Create an AutoFilter in the sheet and specify the range to be filtered sheet.AutoFilters.Range = sheet.Range["A1:C1"]; //Save the result file workbook.SaveToFile("ExcelAutoFilter.xlsx", ExcelVersion.Version2016); } } }
Apply Date AutoFilter in Excel in C#
If you need to explore information related to specific dates or time, you can apply a date filter to the selected range using the Workbook.AutoFilters.AddDateFilter(IAutoFilter column, DateTimeGroupingType dateTimeGroupingType, int year, int month, int day, int hour, int minute, int second) method. The following are detailed steps.
- Create a Workbook instance.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specified worksheet using Workbook.Worksheets[] property.
- Add an AutoFilter to a specified range using Workbook.AutoFilters.Range property.
- Get the column to be filtered.
- Call the Workbook.AutoFilters.AddDateFilter() method to add a date filter to the column to filter data related to a specified year/month/date, etc.
- Apply the filter using Workbook.AutoFilters.Filter() method.
- Save the result file using Workbook.SaveToFile() method.
- C#
using Spire.Xls; using Spire.Xls.Core; using Spire.Xls.Core.Spreadsheet.AutoFilter; namespace AddAutoFilter { class Program { static void Main(string[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Load an Excel file workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Data.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Create an auto filter in the sheet and specify the range to be filtered sheet.AutoFilters.Range = sheet.Range["A1:A12"]; //Get the column to be filtered IAutoFilter filtercolumn = sheet.AutoFilters[0]; //Add a date filter to filter data related to February 2022 sheet.AutoFilters.AddDateFilter(filtercolumn, DateTimeGroupingType.Month, 2022, 2, 0, 0, 0, 0); //Apply the filter sheet.AutoFilters.Filter(); //Save the result file workbook.SaveToFile("DateAutoFilter.xlsx", ExcelVersion.Version2016); } } }
Apply Custom AutoFilter in Excel in C#
The Workbook.AutoFilters.CustomFilter(FilterColumn column, FilterOperatorType operatorType, Object criteria) method allows you to create custom filters based on certain criteria. For example, you can filter data that contains specific text. The following are detailed steps.
- Create a Workbook instance.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specified worksheet using Workbook.Worksheets[] property.
- Add an AutoFilter to a specified range using Workbook.AutoFilters.Range property.
- Get the column to be filtered.
- Add a custom filter to the column to filter data containing the specified string using Workbook.AutoFilters.CustomFilter() method.
- Apply the filter using Workbook.AutoFilters.Filter() method.
- Save the result file using Workbook.SaveToFile() method.
- C#
using Spire.Xls; using Spire.Xls.Core.Spreadsheet.AutoFilter; namespace AddAutoFilter { class Program { static void Main(string[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Load an Excel file workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Data.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Create an auto filter in the sheet and specify the range to be filtered sheet.AutoFilters.Range = sheet.Range["G1:G12"]; //Get the column to be filtered FilterColumn filtercolumn = (FilterColumn)sheet.AutoFilters[0]; //Add a custom filter to filter data containing the string "Grocery" string strCrt = "Grocery"; sheet.AutoFilters.CustomFilter(filtercolumn, FilterOperatorType.Equal, strCrt); //Apply the filter sheet.AutoFilters.Filter(); //Save the result file workbook.SaveToFile("CustomAutoFilter.xlsx", ExcelVersion.Version2016); } } }
Remove AutoFilter in Excel in C#
In addition to adding AutoFilters in Excel files, Spire.XLS for .NET also support removing or deleting the AutoFilters from Excel through the Worksheet.AutoFilters.Clear() method. The following are detailed steps.
- Create a Workbook instance.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
- Remove AutoFilter from the worksheet using Worksheet.AutoFilters.Clear() method.
- Save the result file using Workbook.SaveToFile() method.
- C#
using Spire.Xls; namespace AddAutoFilter { class Program { static void Main(string[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Load an Excel file workbook.LoadFromFile("CustomAutoFilter.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Delete AutoFilter from the sheet sheet.AutoFilters.Clear(); //Save the result file workbook.SaveToFile("RemoveAutoFilter.xlsx", ExcelVersion.Version2016); } } }
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.
Adjust the Height of Headers and Footers in a Word document in C#
The height of headers and footers can be adjusted by using the HeaderDistance and the FooterDistance properties. The detail steps of how to adjust the height of headers and footers in a word document using Spire.Doc are shown below.
Detail steps:
Step 1: Instantiate a Document object and load the word document.
Document doc = new Document(); doc.LoadFromFile("Headers and Footers.docx");
Step 2: Get the first section.
Section section = doc.Sections[0];
Step 3: Adjust the height of headers and footers in the section.
section.PageSetup.HeaderDistance = 100; section.PageSetup.FooterDistance = 100;
Step 4: Save the file.
doc.SaveToFile("Output.docx", FileFormat.Docx2013);
Screenshot:
Header:
Footer:
Full code:
//Instantiate a Document object Document doc = new Document(); //Load the word document doc.LoadFromFile("Headers and Footers.docx"); //Get the first section Section section = doc.Sections[0]; //Adjust the height of headers in the section section.PageSetup.HeaderDistance = 100; //Adjust the height of footers in the section section.PageSetup.FooterDistance = 100; //Save the document doc.SaveToFile("Output.docx", FileFormat.Docx2013);
Add a Total Row to Table in Excel in C#
We can quickly total data in an Excel table by adding a total row. This article demonstrates how to add a total row to a table in Excel using Spire.XLS.
Blow is the screenshot of the example file:
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 table with the data from the specific cell range.
IListObject table = sheet.ListObjects.Create("Table", sheet.Range["A1:D4"]);
Step 4: Display total row.
table.DisplayTotalRow = true;
Step 5: Add a total row.
table.Columns[0].TotalsRowLabel = "Total"; table.Columns[1].TotalsCalculation = ExcelTotalsCalculation.Sum; table.Columns[2].TotalsCalculation = ExcelTotalsCalculation.Sum; table.Columns[3].TotalsCalculation = ExcelTotalsCalculation.Sum;
Step 6: Save the file.
workbook.SaveToFile("AddTotalRow.xlsx", ExcelVersion.Version2013);
Output:
Full code:
using Spire.Xls; using Spire.Xls.Core; namespace AddTotalRow { class Program { static void Main(string[] args) { //Instantiate a Workbook object Workbook workbook = new Workbook(); //Load the Excel file workbook.LoadFromFile("Input.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Create a table with the data from the specific cell range IListObject table = sheet.ListObjects.Create("Table", sheet.Range["A1:D4"]); //Display total row table.DisplayTotalRow = true; //Add a total row table.Columns[0].TotalsRowLabel = "Total"; table.Columns[1].TotalsCalculation = ExcelTotalsCalculation.Sum; table.Columns[2].TotalsCalculation = ExcelTotalsCalculation.Sum; table.Columns[3].TotalsCalculation = ExcelTotalsCalculation.Sum; //Save the file workbook.SaveToFile("AddTotalRow.xlsx", ExcelVersion.Version2013); } } }