Thursday, 30 April 2020

Add and Delete Layers in PDF in Java


PDF layer is a feature which allows some content to be made visible or invisible in the PDF. Here I’ll use Java code to show you how to manipulate PDF layers (create and delete layers).

Before getting started, please download the latest version of Free Spire.PDF for Java pack, unzip it and import Spire.Pdf.jar in the “lib” folder to your project as a dependency.

If you are creating a Maven project, you can easily add the jar dependency by adding the following configurations to the pom.xml.



<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId> e-iceblue </groupId>
        <artifactId>spire.pdf</artifactId>
        <version>2.6.3</version>
    </dependency>
</dependencies>

Example 1 Add Layers
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfBrushes;
import com.spire.pdf.graphics.PdfCanvas;
import com.spire.pdf.graphics.PdfPen;
import com.spire.pdf.graphics.layer.PdfLayer;
import java.awt.geom.Point2D;

public class AddLayers {
   
public static void main(String[] args) {
       
//instantiate a PdfDocument object
       
PdfDocument pdf = new PdfDocument();
       
//add a page
        
PdfPageBase page = pdf.getPages().add();

       
//add 3 layers to the page
       
PdfLayer layer = pdf.getLayers().addLayer("red line1");
        PdfCanvas canvas1 = layer.createGraphics(pdf.getPages().get(
0).getCanvas());
        canvas1.drawLine(
new PdfPen(PdfBrushes.getRed(), 1), new Point2D.Float(50, 350), new Point2D.Float(200, 350));
        layer = pdf.getLayers().addLayer(
"blue line1");
        PdfCanvas canvas2 = layer.createGraphics(pdf.getPages().get(
0).getCanvas());
        canvas2.drawLine(
new PdfPen(PdfBrushes.getBlue(), 1), new Point2D.Float(50, 450), new Point2D.Float(200, 450));
        layer = pdf.getLayers().addLayer(
"green line1");
        PdfCanvas canvas3 = layer.createGraphics(pdf.getPages().get(
0).getCanvas());
        canvas3.drawLine(
new PdfPen(PdfBrushes.getGreen(), 1), new Point2D.Float(50,550), new Point2D.Float(200, 550));

       
//save the resultant document
       
pdf.saveToFile("output/addLayers.pdf");
        pdf.close();
    }
}
 

Example 2 Delete Layers
import com.spire.pdf.PdfDocument;


public class DeleteLayer {

    public static void main(String[] args) {

        //load a PDF document

        PdfDocument pdf = new PdfDocument();

        pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\addLayers.pdf");

        //remove a layer by name

        pdf.getLayers().removeLayer("red line1");

        //save the resultant document

        pdf.saveToFile("output/deleteLayer.pdf");

        pdf.close();

    }

}


Sunday, 26 April 2020

Insert, Replace and Extract Images in a PowerPoint document in Java


An image is one of the most important elements in PowerPoint documents, so it’s more than important to understand how to manipulate images. Here I’ll share with you some examples to insert, replace and extract images by using FreeSpire.Presentation for Java.

Add Spire.Presentation.jar as dependency

Method 1: Download Free Spire.Presentation for Java pack, unzip it and you’ll get Spire.Presentation.jar file from the “lib” folder. Import the .jar file in your project as a dependency.
Method 2: If you are creating a Maven project, you can easily add the .jar dependency with simple configurations. Please check the tutorial which will show you how to install it from Maven.

Example 1 Insert Images in a PowerPoint document

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;
import java.awt.geom.Rectangle2D;

public class InsetImage {
   
public static void main(String[] args) throws Exception {
       
//Create a Presentation instance
       
Presentation ppt = new Presentation();
        Rectangle2D rect =
new Rectangle2D.Double(ppt.getSlideSize().getSize().getWidth() / 2 - 280, 140, 200, 120);

       
//Get the first slide
       
ISlide slide = ppt.getSlides().get(0);
       
       //Insert an image into the slide
       
IEmbedImage image = slide.getShapes().appendEmbedImage(ShapeType.RECTANGLE, "C:\\Users\\Test1\\Desktop\\Image1.png", rect);
        image.getLine().setFillType(FillFormatType.
NONE);

       
//Append a new slide
       
slide = ppt.getSlides().append();
       
       //Insert an image into the slide
       
image = slide.getShapes().appendEmbedImage(ShapeType.RECTANGLE, "C:\\Users\\Test1\\Desktop\\Image2.jpg", rect);
        image.getLine().setFillType(FillFormatType.
NONE);

       
//Save the document
       
ppt.saveToFile("output/InsertImages.pptx", FileFormat.PPTX_2013);

    }
}

Example 2 Replace Images

import com.spire.presentation.*;

import com.spire.presentation.drawing.IImageData;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;

import java.io.FileInputStream;


public class ReplaceImage {

    public static void main(String[] args) throws Exception {

        //create a Presentation object

        Presentation presentation= new Presentation();


        //load the sample PowerPoint file

        presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\InsertImages.pptx");


        //add an image to the image collection

        String imagePath = "C:\\Users\\Test1\\Desktop\\Image3.png";

        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imagePath));

        IImageData image = presentation.getImages().append(bufferedImage);


        //get the shape collection from the first slide

        ShapeCollection shapes = presentation.getSlides().get(0).getShapes();


        //loop through the shape collection

        for (int i = 0; i < shapes.getCount(); i++) {


        //determine if a shape is a picture

        if (shapes.get(i) instanceof SlidePicture) {


        //fill the shape with a new image

        ((SlidePicture) shapes.get(i)).getPictureFill().getPicture().setEmbedImage(image);

            }

        }


        //save to file

        presentation.saveToFile("output/ReplaceImage.pptx", FileFormat.PPTX_2013);

    }
 
} 

Example 3 Extract Images

Part 1 Extract All Images from a PowerPoint document
import com.spire.presentation.Presentation;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;

import java.io.File;


public class ExtractAllImage {

    public static void main(String[] args) throws Exception {

        //Create a Presentation instance

        Presentation ppt = new Presentation();
      
       //Load the PowerPoint document

        ppt.loadFromFile("C:\\Users\\Test1\\Desktop\\InsertImages.pptx");

        for (int i = 0; i < ppt.getImages().getCount(); i++) {
            
       //Extract images from the PowerPoint document

            BufferedImage image = ppt.getImages().get(i).getImage();

            ImageIO.write(image, "PNG"new File(String.format("output/" + "extractAllImage-%1$s.png", i)));

        }

    }
 
} 
Part 2 Extract Images from a specific slide
import com.spire.presentation.*;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;

import java.io.File;

public class ExtractSpecificImage {

    public static void main(String[] args) throws Exception {

        //Create a Presentation instance

        Presentation ppt = new Presentation();

        //Load the PowerPoint document

        ppt.loadFromFile("C:\\Users\\Test1\\Desktop\\InsertImages.pptx");


        //Get the first slide

        ISlide slide = ppt.getSlides().get(0);

        for(int i = 0; i< slide.getShapes().getCount(); i++)

        {
            IShape shape = slide.getShapes().get(i);

        //Extract images from the slide

        if(shape instanceof SlidePicture)

            {
                SlidePicture pic = (SlidePicture) shape;

                BufferedImage image = pic.getPictureFill().getPicture().getEmbedImage().getImage();

                ImageIO.write(image, "PNG"new File(String.format("output/" + "extractSpecificImage-%1$s.png", i)));

            }

         if(shape instanceof PictureShape)

            {

                PictureShape ps = (PictureShape) shape;

                BufferedImage image = ps.getEmbedImage().getImage();

                ImageIO.write(image, "PNG"new File(String.format("output/" + "extractSpecificImage-%1$s.png", i)));

            }

        }

    }

}


Thursday, 23 April 2020

Insert and Read Formulas in Excel in Java


Excel formulas play a very important role in making excel have powerful data analysis and processing capabilities. Therefore, mastering the ability to handle formulas is conducive to enhancing the level of using excel and improving work efficienty. In this article, I’ll introduce how to insert and read formulas in excel by using Free Spire.XLS for Java.

Before Start

Download the latest version of Free Spire.XLS for Java, unzip the package, and you’ll find the Spire.Xls.jar file in the lib folder. Then import the jar file in your Java IED. The following screenshot is what it finally looks like.
Example 1  Insert Formulas
import com.spire.xls.*;
public class InsertFormulas {
   
public static void main(String[] args) {
       
//Create a Workbook object
       
Workbook workbook = new Workbook();

       
//Get the first worksheet
       
Worksheet sheet = workbook.getWorksheets().get(0);

       
//Declare two variables: currentRowcurrentFormula
       
int currentRow = 1;
        String currentFormula =
null;

       
//Set the column width
       
sheet.setColumnWidth(1, 32);
        sheet.setColumnWidth(
2, 16);

       
//Write test data into cells
       
sheet.getCellRange(currentRow,1).setValue("Test data:");
        sheet.getCellRange(currentRow,
2).setNumberValue(1);
        sheet.getCellRange(currentRow,
3).setNumberValue(2);
        sheet.getCellRange(currentRow,
4).setNumberValue(3);
        sheet.getCellRange(currentRow,
5).setNumberValue(4);
        sheet.getCellRange(currentRow,
6).setNumberValue(5);

       
//Write text in cells
       
currentRow += 2;
        sheet.getCellRange(currentRow,
1).setValue("Formulas:") ; ;
        sheet.getCellRange(currentRow,
2).setValue("result:");

       
//Format cells
       
CellRange range = sheet.getCellRange(currentRow,1,currentRow,2);
        range.getStyle().getFont().isBold(
true);
        range.getStyle().setKnownColor(ExcelColors.
LightGreen1);
        range.getStyle().setFillPattern(ExcelPatternType.
Solid);
        range.getStyle().getBorders().getByBordersLineType(BordersLineType.
EdgeBottom).setLineStyle(LineStyleType.Medium);

       
//Arithmetic operation
       
currentFormula = "=1/2+3*4";
        sheet.getCellRange(++currentRow,
1).setText(currentFormula);
        sheet.getCellRange(currentRow,
2).setFormula(currentFormula);

       
//Date function
       
currentFormula = "=TODAY()";
        sheet.getCellRange(++currentRow,
1).setText(currentFormula);
        sheet.getCellRange(currentRow,
2).setFormula(currentFormula);
        sheet.getCellRange(currentRow,
2).getStyle().setNumberFormat("YYYY/MM/DD");

       
//Time function
       
currentFormula = "=NOW()";
        sheet.getCellRange(++currentRow,
1).setText(currentFormula);
        sheet.getCellRange(currentRow,
2).setFormula(currentFormula);
        sheet.getCellRange(currentRow,
2).getStyle().setNumberFormat("H:MM AM/PM");

       
//IF function
       
currentFormula = "=IF(B1=5,\"Yes\",\"No\")";
        sheet.getCellRange(++currentRow,
1).setText(currentFormula);
        sheet.getCellRange(currentRow,
2).setFormula(currentFormula);

       
//PI function
       
currentFormula = "=PI()";
        sheet.getCellRange(++currentRow,
1).setText(currentFormula);
        sheet.getCellRange(currentRow,
2).setFormula(currentFormula);

       
//Trigonometric function
       
currentFormula = "=SIN(PI()/6)";
        sheet.getCellRange(++currentRow,
1).setText(currentFormula);
        sheet.getCellRange(currentRow,
2).setFormula(currentFormula);

       
//Count function
       
currentFormula = "=Count(B1:F1)";
        sheet.getCellRange(++currentRow,
1).setText(currentFormula);
        sheet.getCellRange(currentRow,
2).setFormula(currentFormula);

       
//Maximum function
       
currentFormula = "=MAX(B1:F1)";
        sheet.getCellRange(++currentRow,
1).setText(currentFormula);
        sheet.getCellRange(currentRow,
2).setFormula(currentFormula);

       
//Average function
       
currentFormula = "=AVERAGE(B1:F1)";
        sheet.getCellRange(++currentRow,
1).setText(currentFormula);
        sheet.getCellRange(currentRow,
2).setFormula(currentFormula);

       
//Summation function
       
currentFormula = "=SUM(B1:F1)";
        sheet.getCellRange(++currentRow,
1).setText(currentFormula);
        sheet.getCellRange(currentRow,
2).setFormula(currentFormula);

       
//Save to file
       
workbook.saveToFile("output/InsertFormulas.xlsx",FileFormat.Version2013);
    }
}
output:
Example 2 Read Formulas
import com.spire.xls.CellRange;

import com.spire.xls.Workbook;

import com.spire.xls.Worksheet;

public class ReadFormulas {

    public static void main(String[] args) {

        //Create a Workbook object

        Workbook workbook = new Workbook();


        //Load an Excel file

        workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\InsertFormulas.xlsx");

        //Get the first worksheet

        Worksheet sheet = workbook.getWorksheets().get(0);

        //Loop through the cells within B1:B13

        for (Object cell: sheet.getCellRange("B1:B13")

        ) {

         CellRange cellRange = (CellRange)cell;

        //Detect if a cell range has formula

        if (cellRange.hasFormula()){

        //Print out the cell containing a formula and the formula itself

        String certainCell = String.format("Cell[%d, %d] has a formula: ",cellRange.getRow(),cellRange.getColumn());

        System.out.println(certainCell + cellRange.getFormula());

            }

        }

    }

}
output:




Monday, 20 April 2020

Set Background Image and Background Color for Word document in Java


In a Word document, you can quickly add visual appeal to your text by adding a background image or color. Adding a colorful background image can be helpful when creating a brochure, Word document, or marketing materials. In this article, I’ll share with you how to set background image and background color for Word document by using Free Spire.Doc for Java.



Installation
Before coding, please download the latest version of Free Spire.Doc for Java through this link, unzip the package and then add Spire.Doc.jar in lib folder into your application as dependency. The following screenshot is what it finally looks like.
Example 1 Set background image

import com.spire.doc.*;
import com.spire.doc.documents.BackgroundType;

public class BackgroundImage {
   
public static void main(String[] args) {
        String inputFile=
"C:\\Users\\Test1\\Desktop\\Sample.docx";
        String backgroundImg=
"C:\\Users\\Test1\\Desktop\\Image.jpg";
        String outputFile=
"output/BackgroundImage.docx";

       
//load a word document
       
Document document= new Document(inputFile);

       
//set the background type as picture
       
document.getBackground().setType(BackgroundType.Picture);

       
//set the background picture
       
document.getBackground().setPicture(backgroundImg);

       
//save the file
       
document.saveToFile(outputFile, FileFormat.Docx);
    }
}
Output

Example 2 Set background color

Part 1 Set background solid color
import com.spire.doc.*;import com.spire.doc.documents.BackgroundType;import java.awt.*;

public class BackgroundSolidColor {

    public static void main(String[] args) {

        String inputFile="C:\\Users\\Test1\\Desktop\\Sample.docx";

        String outputFile="output/BackgroundSolidClor.docx";

               //load a word document

        Document document= new Document(inputFile);

               document.getBackground().setType(BackgroundType.Color);

        document.getBackground().setColor(Color.lightGray);


        //save the file

        document.saveToFile(outputFile, FileFormat.Docx);

    }

}
Output


Part 2 Set background gradient color
import com.spire.doc.*;
import com.spire.doc.documents.BackgroundType;
import com.spire.doc.documents.GradientShadingStyle;
import com.spire.doc.documents.GradientShadingVariant;
import java.awt.*;

public class BackgroundGradientColor {

    public static void main(String[] args) {

        String inputFile="C:\\Users\\Test1\\Desktop\\Sample.docx";

        String outputFile="output/BackgroundGradientColor.docx";

        //load a word document

        Document document= new Document(inputFile);

        document.getBackground().setType(BackgroundType.Gradient);

        document.getBackground().getGradient().setColor1(Color.white);

        document.getBackground().getGradient().setColor2(Color.cyan);

        document.getBackground().getGradient().setShadingVariant(GradientShadingVariant.Shading_Down);

        document.getBackground().getGradient().setShadingStyle(GradientShadingStyle.Horizontal);

        //save the file

        document.saveToFile(outputFile, FileFormat.Docx_2013);

    }

}
Output


Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...