Monday, 08 October 2018 07:18

Create Fillable Form Fields in PDF in Java

PDF fillable forms, also known as the interaction forms, are mainly used to collect user information. The most common form fields include text box, radio button, check box, list box and combo box. The code snippets below demonstrate how to add fillable form fields to PDF using Spire.PDF for Java.

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.EnumSet;

import com.spire.pdf.fields.*;
import com.spire.pdf.graphics.*;

public class AddFormFieldsToPdf {

	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 = 0;

        //create brush objects
        PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
        PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.black));
         
        //create font 
        PdfFont font = new PdfFont(PdfFontFamily.Times_Roman, 12f, EnumSet.of(PdfFontStyle.Regular));

        //add a textbox to pdf
        String text = "TextBox:"; 
        page.getCanvas().drawString(text, font, brush1, new Point2D.Float(0, 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 checkboxes to pdf
        page.getCanvas().drawString("CheckBox:", font, brush1, new Point2D.Float(0, baseY));
        java.awt.geom.Rectangle2D.Float rec1 = new java.awt.geom.Rectangle2D.Float(baseX, baseY, 15, 15);
        PdfCheckBoxField checkBoxField = new PdfCheckBoxField(page, "checkbox1");
        checkBoxField.setBounds(rec1);
        checkBoxField.setChecked(false);
        page.getCanvas().drawString("Option 1", font, brush2, new Point2D.Float(baseX + 20, baseY));
        java.awt.geom.Rectangle2D.Float rec2 = new java.awt.geom.Rectangle2D.Float(baseX + 70, baseY, 15, 15);
        PdfCheckBoxField checkBoxField1 = new PdfCheckBoxField(page, "checkbox2");
        checkBoxField1.setBounds(rec2);
        checkBoxField1.setChecked(false);
        page.getCanvas().drawString("Option 2", font,  brush2, new Point2D.Float(baseX+90, baseY));
        doc.getForm().getFields().add(checkBoxField);
        doc.getForm().getFields().add(checkBoxField1);
        baseY += 25;

        //add a listbox to pdf
        page.getCanvas().drawString("ListBox:", font, brush1, new Point2D.Float(0, baseY));
        java.awt.geom.Rectangle2D.Float rec = new java.awt.geom.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(rec);
        listBoxField.setFont(font);
        listBoxField.setSelectedIndex(0);
        doc.getForm().getFields().add(listBoxField);
        baseY += 60;

        //add radiobuttons to pdf
        page.getCanvas().drawString("RadioButton:", font, brush1, new Point2D.Float(0, baseY));
        PdfRadioButtonListField radioButtonListField = new PdfRadioButtonListField(page, "radio");
        PdfRadioButtonListItem radioItem1 = new PdfRadioButtonListItem("option1");
        radioItem1.setBounds(new Rectangle2D.Float(baseX, baseY, 15, 15));
        page.getCanvas().drawString("Option 1", font, brush2, new Point2D.Float(baseX + 20, baseY));
        PdfRadioButtonListItem radioItem2 = new PdfRadioButtonListItem("option2");
        radioItem2.setBounds(new Rectangle2D.Float(baseX + 70, baseY, 15, 15));
        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 to pdf
        page.getCanvas().drawString("ComboBox:", font, brush1, new Point2D.Float(0, 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 to pdf
        page.getCanvas().drawString("Signature:", font, brush1, new Point2D.Float(0, 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 to pdf
        page.getCanvas().drawString("Button:", font, brush1, new Point2D.Float(0, baseY));
        Rectangle2D.Float btnBounds = new Rectangle2D.Float(baseX, baseY, 50, 15);
        PdfButtonField buttonField = new PdfButtonField(page, "button");
        buttonField.setBounds(btnBounds);
        buttonField.setText("Sumbit");
        buttonField.setFont(font);
        doc.getForm().getFields().add(buttonField);

        //save to file
        doc.saveToFile("AddFormField-2.pdf", FileFormat.PDF);
	}

}

Create Fillable Form Fields in PDF in Java

Wednesday, 26 September 2018 08:02

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:

Split Table Cells in PowerPoint in C#

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:

Split Table Cells in PowerPoint in C#

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);
        }
    }
}
Thursday, 20 September 2018 07:29

Create a PDF Document in Java

This following code snippets demonstrate how to use Spire. PDF for Java to create PDF documents in Java programs, including how to create fonts, how to center text, how to draw text in a specified rectangular area, how to paginate content automatically, and so on.

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 FileNotFoundException, IOException  {

        //create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //add a page
        PdfPageBase page = doc.getPages().add();

        //heading text
        String heading = "Java - Overview";

        //create solid brush objects
        PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
        PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.BLACK));

        //create true type font objects
        PdfTrueTypeFont font1= new PdfTrueTypeFont(new Font("Times New Roman",Font.PLAIN,20));
        PdfTrueTypeFont font2= new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,12));

        //set the text alignment via PdfStringFormat class
        PdfStringFormat format1 = new PdfStringFormat();
        format1.setAlignment(PdfTextAlignment.Center);

        //draw heading on the center of the page
        page.getCanvas().drawString(heading, font1, brush1, new Point2D.Float((float)page.getActualBounds(true).getWidth()/2, 0),format1);

        //get body text from a .txt file
        String body = readFileToString("C:\\Users\\Administrator\\Desktop\\body.txt");

        //create a PdfTextWidget object
        PdfTextWidget widget = new PdfTextWidget(body, font2, brush2);

        //create a rectangle where the body text will be placed
        Rectangle2D.Float rect = new Rectangle2D.Float(0, 30, (float)page.getActualBounds(true).getWidth(),(float)page.getActualBounds(true).getHeight());

        //set the PdfLayoutType to Paginate to make the content paginated automatically
        PdfTextLayout layout = new PdfTextLayout();
        layout.setLayout(PdfLayoutType.Paginate);

        //draw body text on the page
        widget.draw(page, rect, layout);

        //save to file
        doc.saveToFile("output/CreatePdf.pdf");
    }

    //customize a function to read 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;
    }
}

Create a PDF Document in Java

Tuesday, 18 September 2018 07:58

Convert a Chart Sheet to Image in C#

A chart sheet is a separate worksheet that only contains chart, at some times we may need to convert chart sheet to image. This article is going to elaborates how we can convert a chart sheet to image using Spire.XLS.

Screenshot of the Chart sheet:

Convert a Chart Sheet to Image in C#

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 chart sheet.

ChartSheet chartSheet = workbook.Chartsheets[0];

Step 3: Save the chart sheet to image and save the image to disk.

Image image = workbook.SaveChartAsImage(chartSheet);
image.Save("ChartSheet.png", ImageFormat.Png);

Output image:

Convert a Chart Sheet to Image in C#

Full code:

//Instantiate a Workbook object
Workbook workbook = new Workbook();
//Load the excel file
workbook.LoadFromFile("Input.xlsx");

//Get the first chart sheet
ChartSheet chartSheet = workbook.Chartsheets[0];

//Save the chart sheet as image
Image image = workbook.SaveChartAsImage(chartSheet);
//Save image
image.Save("ChartSheet.png", ImageFormat.Png);

This article demonstrates how to replace an existing image with a new image in a PowerPoint document using Spire.Presentation.

The original image:

Replace Image with New Image in PowerPoint in C#

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:

Replace Image with New Image in PowerPoint in C#

Full code:

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);
Friday, 07 September 2018 07:20

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:

Detect the used themes in PowerPoint in C#

Full code:

//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());
Friday, 31 August 2018 09:21

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:

Filter cells by cell color in Excel in C#

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:

Filter cells by cell color in Excel in C#

Full code:

//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);

When working with large data sets in Excel, it can be a challenge not only to calculate data, but also to find the relevant information. Luckily, we can add AutoFilter in a range of cells or table to display the data you want and hid the rest. This article will show you how to filter data in Excel using Spire.XLS with C# and VB.NET.

Code Snippets

Step 1: Create a Workbook object and load an existing Excel file.

Workbook workbook = new Workbook();
workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.xlsx");

Step 2: Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Get the AutoFilters object.

AutoFiltersCollection filters = sheet.AutoFilters;

Step 4: Set the range to be filtered.

filters.Range = sheet.Range[1, 2, sheet.LastRow, 2];

Step 5: Add a filter criteria.

filters.AddFilter(0, "Laptop");

Step 6: Filter the data.

filters.Filter();

Step 7: Save to file.

workbook.SaveToFile("output.xlsx", ExcelVersion.Version2010);

Output:

How to Add Autofilter to Excel in C#, VB.NET

Full Code:

[C#]
Workbook workbook = new Workbook();
workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.xlsx");
Worksheet sheet = workbook.Worksheets[0];
AutoFiltersCollection filters = sheet.AutoFilters;
filters.Range = sheet.Range[1, 2, sheet.LastRow, 2];   
filters.AddFilter(0, "Laptop"); 
filters.Filter(); 
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2010); 
[VB.NET]
Dim workbook As Workbook = New Workbook()
workbook.LoadFromFile("C:\Users\Administrator\Desktop\sample.xlsx")
Dim sheet As Worksheet = workbook.Worksheets(0)
Dim filters As AutoFiltersCollection = sheet.AutoFilters
filters.Range = sheet.Range(1, 2, sheet.LastRow, 2)
filters.AddFilter(0, "Laptop")
filters.Filter()
workbook.SaveToFile("output.xlsx", ExcelVersion.Version2010)

This article demonstrates how to add a picture as a custom bullet style in a PowerPoint file using Spire.Presentation.

Below is the screenshot of the example PowerPoint file:

Add a Picture as a Custom Bullet Style in PowerPoint in C#

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 shape on the first slide.

IAutoShape shape = ppt.Slides[0].Shapes[0] as IAutoShape;

Step 3: Add a picture as the bullet style of the paragraphs in the shape.

foreach (TextParagraph paragraph in shape.TextFrame.Paragraphs)
{
    paragraph.BulletType = TextBulletType.Picture;
    Image bulletPicture = Image.FromFile(@"timg.jpg");
    paragraph.BulletPicture.EmbedImage = ppt.Images.Append(bulletPicture);
}

Step 4: Save the file.

ppt.SaveToFile(@"Output.pptx", FileFormat.Pptx2010);

Screenshot:

Add a Picture as a Custom Bullet Style in PowerPoint in C#

Full code:

using System.Drawing;
using Spire.Presentation;

namespace Add_Picture_as_Custom_Bullet_Style_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 shape on the first slide
            IAutoShape shape = ppt.Slides[0].Shapes[0] as IAutoShape;

            //Traverse through the paragraphs in the shape
            foreach (TextParagraph paragraph in shape.TextFrame.Paragraphs)
            {
                //Set the bullet style of paragraph as picture
                paragraph.BulletType = TextBulletType.Picture;
                //Load a picture
                Image bulletPicture = Image.FromFile(@"timg.jpg");
                //Add the picture as the bullet style of paragraph
                paragraph.BulletPicture.EmbedImage = ppt.Images.Append(bulletPicture);
            }

            //Save the file
            ppt.SaveToFile(@"Output.pptx", FileFormat.Pptx2010);
        }
    }
}

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:

Adjust the Height of Headers and Footers in a Word document in C#

Footer:

Adjust the Height of Headers and Footers in a Word document in C#

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);