Monday, 22 October 2018 03:00

Fill PDF Form Fields in Java

The tutorial shows you how to access the form fields in a PDF document and how to fill each form field with value by using Spire.PDF for Java.

Entire Code:

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.widget.*;


public class FillFormField{
    public static void main(String[] args){
    	
        //create a PdfDocument object
        PdfDocument doc = new PdfDocument();
        
        //load a sample PDF containing forms
        doc.loadFromFile("G:\\java-workspace\\Spire.Pdf\\Forms.pdf");

        //get the form fields from the document
        PdfFormWidget form = (PdfFormWidget) doc.getForm();
        
        //get the form widget collection
        PdfFormFieldWidgetCollection formWidgetCollection = form.getFieldsWidget();

        //loop through the widget collection and fill each field with value
        for (int i = 0; i < formWidgetCollection.getCount(); i++) {
        	
            PdfField field = formWidgetCollection.get(i);         
            if (field instanceof PdfTextBoxFieldWidget) {
                PdfTextBoxFieldWidget textBoxField = (PdfTextBoxFieldWidget) field;
                textBoxField.setText("Kaila Smith");
            }         
            if (field instanceof PdfRadioButtonListFieldWidget) {
                PdfRadioButtonListFieldWidget radioButtonListField = (PdfRadioButtonListFieldWidget) field;
                radioButtonListField.setSelectedIndex(1);
            }
            if (field instanceof PdfListBoxWidgetFieldWidget) {
                PdfListBoxWidgetFieldWidget listBox = (PdfListBoxWidgetFieldWidget) field;
                listBox.setSelectedIndex(0);
            }
            if (field instanceof PdfCheckBoxWidgetFieldWidget) {
                PdfCheckBoxWidgetFieldWidget checkBoxField = (PdfCheckBoxWidgetFieldWidget) field;
                switch(checkBoxField.getName()){
                case "checkbox1":
                	checkBoxField.setChecked(true);
                	break;
                case "checkbox2":
                	checkBoxField.setChecked(true);
                	break;
                }
            }
            if (field instanceof PdfComboBoxWidgetFieldWidget) {
                PdfComboBoxWidgetFieldWidget comboBoxField = (PdfComboBoxWidgetFieldWidget) field;
                comboBoxField.setSelectedIndex(1);
            }
        }
        
        //Save the file
        doc.saveToFile("FillFormFields.pdf", FileFormat.PDF);
    }

}

Output:

Fill PDF Form Fields in Java

Monday, 15 October 2018 08:37

Convert PDF to Image in Java

By using Spire.PDF for JAVA, we can easily convert any specific page of PDF document to BMP and Metafile image in JAVA applications. The following sample demonstrate how to convert PDF to image in JAVA. The supported images could be in Jpeg, Jpg, Png, Bmp, Tiff, Gif, EMF format etc. We will use PDF to .png image for example.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import com.spire.pdf.PdfDocument;
import javax.imageio.ImageIO;

public class toImage {

        public static void main(String[] args) throws IOException {
            //load the sample PDF
            PdfDocument doc = new PdfDocument();
            doc.loadFromFile("Sample.pdf");

            //save every PDF to .png image
            BufferedImage image;
            for (int i = 0; i < doc.getPages().getCount(); i++) {
                image = doc.saveAsImage(i);
                File file = new File( String.format("ToImage-img-%d.png", i));
                ImageIO.write(image, "PNG", file);
            }

            doc.close();
        }

}

The sample PDF file:

Convert PDF to Image in Java

Effective screenshot of the resulted PNG image:

Convert PDF to Image in Java

Monday, 15 October 2018 07:57

Extract/Read Text from PDF in Java

This article is going to demonstrate how to extract/read text from a PDF file using Spire.PDF for JAVA.

The example PDF file:

Extract/Read Text from PDF in Java

Code snippets:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import java.io.*;

public class Extract_Text {

	public static void main(String[] args) {
		
		//Create a PdfDocument instance
		PdfDocument doc=new PdfDocument();
		//Load the PDF file
        doc.loadFromFile("test.pdf");
        
        //Create a StringBuilder instance        
        StringBuilder sb=new StringBuilder();
        
        PdfPageBase page;
        
        //Loop through PDF pages and get text of each page
        for(int i=0;i<doc.getPages().getCount();i++){
            page=doc.getPages().get(i);            
            sb.append(page.extractText(true));
        }
        FileWriter writer;
        try {
            //Write text into a .txt file
            writer = new FileWriter("ExtractText.txt");
            writer.write(sb.toString());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        doc.close();
	}
}

Output:

Extract/Read Text from PDF in Java

Monday, 15 October 2018 05:47

Draw Shapes in PDF in Java

This tutorial will show you how to use Spire. PDF for Java to draw shapes in a PDF document, as well as set shape border colors and fill colors.

Entire Code:

import java.awt.Color;
import java.awt.geom.Rectangle2D;

import com.spire.ms.System.Drawing.PointF;
import com.spire.pdf.graphics.*;


public class DrawShapes {

	public static void main(String[] args) {
		
		//create a PdfDocument object
        PdfDocument doc = new PdfDocument();
        
        //add a page
        PdfPageBase page = doc.getPages().add();      
        
        //draw a rectangle
        PdfPen pen =new PdfPen(new PdfRGBColor(Color.black),0.1);
        Rectangle2D.Float rect1 = new Rectangle2D.Float(0, 20, 120, 50);
        PdfLinearGradientBrush linearGradientBrush = new PdfLinearGradientBrush(rect1,new PdfRGBColor(Color.white),new PdfRGBColor(Color.blue),PdfLinearGradientMode.Horizontal);          
        page.getCanvas().drawRectangle(pen, linearGradientBrush, rect1);
        
        //draw an ellipse
        PointF centerStart= new PointF(205,45);
        PointF centerEnd= new PointF(205,45);
        PdfRadialGradientBrush radialGradientBrush = new PdfRadialGradientBrush(centerStart,0,centerEnd,25,new PdfRGBColor(Color.pink),new PdfRGBColor(Color.red));
        Rectangle2D.Float rect2= new Rectangle2D.Float(180, 20, 50, 50);
        page.getCanvas().drawEllipse(pen,radialGradientBrush,rect2);
        
        //draw a polygon
        PointF p1=new PointF(290,70);
        PointF p2=new PointF(310,45);
        PointF p3=new PointF(325,60);
        PointF p4=new PointF(340,20);
        PointF p5=new PointF(370,70);
        PointF[] points = {p1, p2, p3, p4, p5};
        PdfBrush brush= PdfBrushes.getGreenYellow();
        page.getCanvas().drawPolygon(pen,brush, points);
        
        //draw an arc
        float startAngle = 0;
        float sweepAngle = 270;
        Rectangle2D.Float rect3= new Rectangle2D.Float(0, 110, 50, 50);
        page.getCanvas().drawArc(pen, rect3, startAngle, sweepAngle);
        
        //draw a pie graph   
        Rectangle2D.Float rect4= new Rectangle2D.Float(70, 110, 50, 50);
        page.getCanvas().drawPie(pen, rect4, startAngle, sweepAngle);
        
        //draw a line
        PointF pStart=new PointF(205,110);
        PointF pEnd=new PointF(205,160);
        page.getCanvas().drawLine(pen, pStart, pEnd);
  
        //draw a Bezier curve
        PointF startPoint = new PointF(290, 135);
        PointF firstControlPoint = new PointF(330, 70);
        PointF secondControlPoint = new PointF(330, 200);
        PointF endPoint = new PointF(370, 135);
        page.getCanvas().drawBezier(pen, startPoint, firstControlPoint, secondControlPoint, endPoint);
        
        //save to file
        doc.saveToFile("DrawShapes.pdf", FileFormat.PDF);       
	}

}

Output:

Draw Shapes in PDF in Java

We have demonstrated how to use Spire.Presentation to add and get speaker notes in presentation slides. This article will show how to remove the speaker notes in presentation slides in C#.

Firstly, view the sample document contains the speaker notes.

How to remove speaker notes from a presentation slide in C#

Step 1: Create a presentation document and load the document from the file.

Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx", FileFormat.Pptx2013);

Step 2: Get the first slide from the sample document.

ISlide slide = ppt.Slides[0];

Step 3: Remove the first speak notes:

slide.NotesSlide.NotesTextFrame.Paragraphs.RemoveAt(1);

Remove all the speak notes from the first slide:

slide.NotesSlide.NotesTextFrame.Paragraphs.Clear();

Step 4: Save the document to file.

ppt.SaveToFile("Result.pptx",FileFormat.Pptx2013);

Effective screenshot of removing the first note:

How to remove speaker notes from a presentation slide in C#

Effective screenshot of removing all the notes:

How to remove speaker notes from a presentation slide in C#

Full codes:

Remove the first note in presentation slide:

Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx", FileFormat.Pptx2013);

ISlide slide = ppt.Slides[0];
           
slide.NotesSlide.NotesTextFrame.Paragraphs.RemoveAt(1);
ppt.SaveToFile("Result.pptx",FileFormat.Pptx2013);

Clear all notes in presentation slide:

Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx", FileFormat.Pptx2013);

ISlide slide = ppt.Slides[0];
           
slide.NotesSlide.NotesTextFrame.Paragraphs.Clear();
ppt.SaveToFile("Result2.pptx",FileFormat.Pptx2013);

This article demonstrates how to determine the number of pages in a PDF file using Spire.PDF for JAVA.

The following screenshot shows a PDF file which contains 73 pages:

Get the Number of Pages in a PDF File in Java

Code snippets:

import com.spire.pdf.PdfDocument;

		public class CountPagesOfPDF {

		public static void main(String[] args) {
		
		//Instantiate a PdfDocument object
		PdfDocument doc=new PdfDocument();
		//Load the PDF file
		doc.loadFromFile("Test.pdf");

		//Get the number of pages in the PDF file        
		int pageCount = doc.getPages().getCount();
        
		System.out.print(pageCount);

	}
}

Outout:

Get the Number of Pages in a PDF File in Java

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