Starting from version 9.9.5, Spire.XLS supports applying style to an entire excel worksheet. This article will show you how to apply a style to an entire excel worksheet using Spire.XLS.

Detail steps:

Step 1: Instantiate a Workbook object and load the excel file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");

Step 2: Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Create a cell style, specify the cell background color, font color and font size.

CellStyle style = workbook.Styles.Add("newStyle");
style.Color = Color.DarkGray;
style.Font.Color = Color.White;
style.Font.Size = 15;

Step 4: Apply the style to the first worksheet.

sheet.ApplyStyle(style);

Step 5: Save the resultant file.

workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);

Output:

Apply a Style to an Entire Excel Worksheet in C#

Full code:

using System.Drawing;
using Spire.Xls;

namespace StyleEntireWorksheet
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance and load the excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Input.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Create a cell style
            CellStyle style = workbook.Styles.Add("newStyle");
            style.Color = Color.DarkGray;
            style.Font.Color = Color.White;
            style.Font.Size = 15;

            //Apply the style to the first worksheet
            sheet.ApplyStyle(style);

            //Save the resultant file
            workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);
        }
    }
}
Thursday, 14 March 2024 07:23

Java: Add Page Numbers to a PDF Document

Page numbers provide clarity and structure to the content, making it easier for readers to navigate through the document. By including page numbers, readers can quickly locate specific information or refer to a specific page. Adding page numbers to a PDF document is a common requirement when creating professional and organized files. Whether you're working on a report, a thesis, or any other type of PDF document, incorporating page numbers enhances the overall readability and professionalism of your work.

In this article, you will learn how to add page numbers to a PDF document at the footer section using Spire.PDF for Java.

Install Spire.PDF for Java

You're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

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

PDF Coordinate System

When using Spire.PDF for Java to manipulate an existing PDF document, the coordinate system's origin is positioned at the top left corner of the page. The x-axis extends to the right, while the y-axis extends downward.

In general, page numbers are commonly positioned in the header or footer section of a document. As a result, it is important to consider the page size and margins when deciding where to place the page numbers.

Java: Add Page Numbers to a PDF Document

Add Page Numbers to the Left Corner of PDF Footer in Java

Spire.PDF for Java offers the PdfPageNumberField class and the PdfPageCountField class, which reflect the current page number and the total page count when added to a page of a PDF document. To insert a piece of text like "Page X" or "Page X of Y", you can use a PdfCompositeField object to combine the text with one or more fields into a single field.

To add "Page X of Y" to the left corner of PDF footer, follow the steps below.

  • Create a Document object.
  • Load a PDF file from a specified page.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to create a "Page X of Y" format.
  • Specify the location of the PdfCompositeField object using PdfCompositeField.setLocation() method.
  • Iterate though the pages in the document, and add "Page X of Y" to the left corner of the footer section using PdfCompositeField.draw() method.
  • Save the document to a different PDF file.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.*;
import com.spire.pdf.license.LicenseProvider;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;

public class AddPageNumberToLeftCorner {

    public static void main(String[] args) {

        // Apply your license key
        LicenseProvider.setLicenseKey("License Key");
        
        // Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

        // Create font, brush and pen, which determine the appearance of the page numbers to be added
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 12),true);
        PdfBrush brush = PdfBrushes.getBlack();
        PdfPen pen = new PdfPen(brush, 1.0);

        // Create a PdfPageNumberField object and a PdfPageCountField object
        PdfPageNumberField pageNumberField = new PdfPageNumberField();
        PdfPageCountField pageCountField = new PdfPageCountField();

        // Create a PdfCompositeField object to combine page count field and page number field in a single field
        PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);

        // Get the page size
        Dimension2D pageSize = doc.getPages().get(0).getSize();

        // Set the location of the composite field
        compositeField.setLocation(new Point2D.Float(72, (float) pageSize.getHeight() - 45));

        // Iterate through the pages in the document
        for (int i = 0; i < doc.getPages().getCount(); i++) {

            // Get a specific page
            PdfPageBase page = doc.getPages().get(i);

            // Draw a line at the specified position
            page.getCanvas().drawLine(pen, 72, pageSize.getHeight() - 50, pageSize.getWidth() - 72, pageSize.getHeight() - 50);

            // Draw the composite field on the page
            compositeField.draw(page.getCanvas(), 0.0, 0.0);
        }

        // Save to a different PDF file
        doc.saveToFile("Output/AddPageNumbersToLeftCorner.pdf");

        // Dispose resources
        doc.dispose();
    }
}

Java: Add Page Numbers to a PDF Document

Add Page Numbers to the Center of PDF Footer in Java

To center-align the page number in the footer section, it is necessary to dynamically calculate the width of the text "Page X of Y." This calculation is important because the X coordinate of the page number (PdfCompositeField) will be determined by subtracting the width of the page number from the page width and then dividing the result by 2, i.e., (PageWidth - PageNumberWidth)/2.

The steps to add page numbers to the center of PDF footer are as follows.

  • Create a Document object.
  • Load a PDF file from a specified page.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to create a "Page X of Y" format.
  • Specify the location of the PdfCompositeField object using PdfCompositeField.setLocation() method.
  • Iterate though the pages in the document, and add "Page X of Y" to the center of the footer section using PdfCompositeField.draw() method.
  • Save the document to a different PDF file.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.PdfBrush;
import com.spire.pdf.graphics.PdfBrushes;
import com.spire.pdf.graphics.PdfPen;
import com.spire.pdf.graphics.PdfTrueTypeFont;
import com.spire.pdf.license.LicenseProvider;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;

public class AddPageNumberToCenter {

    public static void main(String[] args) {

        // Apply your license key
        LicenseProvider.setLicenseKey("License Key");

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

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

        // Create font, brush and pen, which determine the appearance of the page numbers to be added
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 12),true);
        PdfBrush brush = PdfBrushes.getBlack();
        PdfPen pen = new PdfPen(brush, 1.0);

        // Create a PdfPageNumberField object and a PdfPageCountField object
        PdfPageNumberField pageNumberField = new PdfPageNumberField();
        PdfPageCountField pageCountField = new PdfPageCountField();

        // Create a PdfCompositeField object to combine page count field and page number field in a single field
        PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);

        // Iterate through the pages in the document
        for (int i = 0; i < doc.getPages().getCount(); i++) {

            // Get a specific page
            PdfPageBase page = doc.getPages().get(i);

            // Get the page size
            Dimension2D pageSize = doc.getPages().get(i).getSize();

            // Draw a line at the specified position
            page.getCanvas().drawLine(pen, 72, pageSize.getHeight() - 50, pageSize.getWidth() - 72, pageSize.getHeight() - 50);

            // Measure the size the "Page X of Y"
            Dimension2D pageNumberSize = font.measureString(String.format("Page %d of %d", i + 1, doc.getPages().getCount()));

            // Set the location of the composite field
            compositeField.setLocation(new Point2D.Float((float)(pageSize.getWidth() - pageNumberSize.getWidth())/2, (float)pageSize.getHeight() - 45));

            // Draw the composite field on the page
            compositeField.draw(page.getCanvas());
        }

        // Save to a different PDF file
        doc.saveToFile("Output/AddPageNumbersToCenter.pdf");

        // Dispose resources
        doc.dispose();
    }
}

Java: Add Page Numbers to a PDF Document

Add Page Numbers to the Right Corner of PDF Footer in Java

To position the page number at the right corner of the footer section, it is necessary to dynamically calculate the width of the text "Page X of Y" as well. Because the X coordinate of the page number (PdfCompositeField) will be determined by subtracting the width of the page number and the right page margin from the page width, i.e., PageWidth - PageNumberWidth - RightPageMargin.

The steps to add page numbers to the right corner of PDF footer are as follows.

  • Create a Document object.
  • Load a PDF file from a specified page.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to create a "Page X of Y" format.
  • Specify the location of the PdfCompositeField object using PdfCompositeField.setLocation() method.
  • Iterate though the pages in the document, and add "Page X of Y" to the right corner of the footer section using PdfCompositeField.draw() method.
  • Save the document to a different PDF file.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.PdfBrush;
import com.spire.pdf.graphics.PdfBrushes;
import com.spire.pdf.graphics.PdfPen;
import com.spire.pdf.graphics.PdfTrueTypeFont;
import com.spire.pdf.license.LicenseProvider;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;

public class AddPageNumberToRightCorner {

    public static void main(String[] args) {

        // Apply your license key
        LicenseProvider.setLicenseKey("License Key");

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

        // Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

        // Create font, brush and pen, which determine the appearance of the page numbers to be added
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 12),true);
        PdfBrush brush = PdfBrushes.getBlack();
        PdfPen pen = new PdfPen(brush, 1.0);

        // Create a PdfPageNumberField object and a PdfPageCountField object
        PdfPageNumberField pageNumberField = new PdfPageNumberField();
        PdfPageCountField pageCountField = new PdfPageCountField();

        // Create a PdfCompositeField object to combine page count field and page number field in a single field
        PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);

        // Iterate through the pages in the document
        for (int i = 0; i < doc.getPages().getCount(); i++) {

            // Get a specific page
            PdfPageBase page = doc.getPages().get(i);

            // Get the page size
            Dimension2D pageSize = doc.getPages().get(i).getSize();

            // Draw a line at the specified position
            page.getCanvas().drawLine(pen, 72, pageSize.getHeight() - 50, pageSize.getWidth() - 72, pageSize.getHeight() - 50);

            // Measure the size the "Page X of Y"
            Dimension2D pageNumberSize = font.measureString(String.format("Page %d of %d", i + 1, doc.getPages().getCount()));

            // Set the location of the composite field
            compositeField.setLocation(new Point2D.Float((float)(pageSize.getWidth() - pageNumberSize.getWidth() -  72), (float)(pageSize.getHeight() - 45)));

            // Draw the composite field on the page
            compositeField.draw(page.getCanvas());
        }

        // Save to a different PDF file
        doc.saveToFile("Output/AddPageNumbersToRightCorner.pdf");

        // Dispose resources
        doc.dispose();
    }
}

Java: Add Page Numbers to a PDF Document

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.

Wednesday, 11 September 2019 09:38

Group Shapes in PowerPoint in Java

This article demonstrates how to group shapes in a PowerPoint document using Spire.Presentation for Java.

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

public class GroupShapes {
    public static void main(String[] args) throws Exception {
        //create a PowerPoint document
        Presentation ppt = new Presentation();
        //get the first slide
        ISlide slide = ppt.getSlides().get(0);

        //add a rectangle shape to the slide
        IShape rectangle = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Double(20,100,200,40));
        rectangle.getFill().setFillType(FillFormatType.SOLID);
        rectangle.getFill().getSolidColor().setKnownColor(KnownColors.GOLD);
        rectangle.getLine().setWidth(0.1f);

        //add a ribbon shape to the slide
        IShape ribbon = slide.getShapes().appendShape(ShapeType.RIBBON_2, new Rectangle2D.Double(60, 75, 120, 80));
        ribbon.getFill().setFillType(FillFormatType.SOLID);
        ribbon.getFill().getSolidColor().setKnownColor(KnownColors.PURPLE);
        ribbon.getLine().setWidth(0.1f);

        //add the shapes to a list
        ArrayList list = new ArrayList();
        list.add((Shape)rectangle);
        list.add((Shape)ribbon);

        //group the shapes
        ppt.getSlides().get(0).groupShapes(list);

        //save the resultant document
        ppt.saveToFile("GroupShapes.pptx", FileFormat.PPTX_2013);
    }
}

Group Shapes in PowerPoint in Java

Wednesday, 11 September 2019 03:29

Java Create Barcode to Word Document

This article demonstrates how to add barcode to a word document in Java applications with the help of Spire.Doc for Java. Firstly, please ensure that the barcode font has been install on the system. The installed font could be found from C:\Windows\Fonts.

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;

public class AddBarcodetoWord{
    public static void main(String[] args) {

        // Create Document
        Document document = new Document();
        //Add a section
        Section section = document.addSection();
        //Add  s paragraph to the section
        Paragraph para = section.addParagraph();

        //Add barcode and set format
        TextRange tr = para.appendText("H63TWX11072");
        tr.getCharacterFormat().setFontName("C39HrP60DlTt");
        tr.getCharacterFormat().setFontSize(80f);

        //Save the document to file
        document.saveToFile("Barcode.docx", FileFormat.Docx);
    }
}

Effective screenshot after add barcode to Word:

Java create Barcode to Word document

Tuesday, 10 September 2019 07:51

Replace Text in PowerPoint in Java

This article demonstrates how to replace text in an exising PowerPoint document with new text using Spire.Presentation for Java.

import com.spire.presentation.*;

import java.util.HashMap;
import java.util.Map;

public class ReplaceText {

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

        //create a Presentation object
        Presentation presentation = new Presentation();

        //load the template file
        presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.pptx");

        //get the first slide
        ISlide slide= presentation.getSlides().get(0);

        //create a Map object
        Map map = new HashMap();

        //add several pairs of keys and values to the map
        map.put("#name#","John Smith");
        map.put("#age#","28");
        map.put("#address#","Oklahoma City, United States");
        map.put("#tel#","333 123456");
        map.put("#email#","johnsmith@outlook.com");

        //replace text in the slide
        replaceText(slide,map);

        //save to another file
        presentation.saveToFile("output/ReplaceText.pptx", FileFormat.PPTX_2013);
    }

    /**
     * Replace text within a slide
     * @param slide Specifies the slide where the replacement happens
     * @param map Where keys are existing strings in the document and values are the new strings to replace the old ones
     */
    public static void replaceText(ISlide slide, Map map) {

        for (Object shape : slide.getShapes()
        ) {
            if (shape instanceof IAutoShape) {

                for (Object paragraph : ((IAutoShape) shape).getTextFrame().getParagraphs()
                ) {
                    ParagraphEx paragraphEx = (ParagraphEx)paragraph;
                    for (String key : map.keySet()
                    ) {
                        if (paragraphEx.getText().contains(key)) {

                            paragraphEx.setText(paragraphEx.getText().replace(key, map.get(key)));
                         }
                    }
                }
            }
        }
    }
}

Replace Text in PowerPoint in Java

Wednesday, 04 September 2019 07:38

Set 3D effect for the text in PowerPoint in C#

With the help of Spire.Presentation for .NET, we could set 3D effect to the shapes and text in the PowerPoint document to make it attractive. We have already demonstrated how to use Spire.Presentation to set 3D format for shapes. In this article, I will introduce how to create three dimensional effects text in PowerPoint in C#.

using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;

namespace 3DEffectForText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a new presentation object
            Presentation presentation = new Presentation();

            //Get the first slide
            ISlide slide = presentation.Slides[0];

            //Append a new shape to slide and set the line color and fill type
            IAutoShape shape = slide.Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(30, 40, 600, 200));
            shape.ShapeStyle.LineColor.Color = Color.White;
            shape.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.None;

            //Add text to the shape
            shape.AppendTextFrame("This demo shows how to add 3D effect text to Presentation slide");

            //set the color of text in shape
            TextRange textRange = shape.TextFrame.TextRange;
            textRange.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid;
            textRange.Fill.SolidColor.Color = Color.Green;

            //set the Font of text in shape
            textRange.FontHeight = 30;
            textRange.LatinFont = new TextFont("Gulim");


            //Set 3D effect for text
            shape.TextFrame.TextThreeD.ShapeThreeD.PresetMaterial = PresetMaterialType.Matte;
            shape.TextFrame.TextThreeD.LightRig.PresetType = PresetLightRigType.Sunrise;
            shape.TextFrame.TextThreeD.ShapeThreeD.TopBevel.PresetType = BevelPresetType.Circle;
            shape.TextFrame.TextThreeD.ShapeThreeD.ContourColor.Color = Color.Green;
            shape.TextFrame.TextThreeD.ShapeThreeD.ContourWidth = 3;                    
          
            //Save the document to file.
            presentation.SaveToFile("3DEffectForText_result.pptx", FileFormat.Pptx2010);                                                        
        }
    }
}

Effective screenshot for 3-D effect text on Presentation slides:

Set 3D effect for the text in PowerPoint in C#

Alternative text (Alt Text) can help people with vision or cognitive impairments understand shapes, pictures or other graphical content. This article demonstrates how to set and get the alternative text of a shape in a PowerPoint document using Spire.Presentation for Java.

Set alternative text

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.*;
import java.awt.geom.Rectangle2D;

public class SetAltText {
    public static void main(String[] args) throws Exception {
        //instantiate a Presentation object
        Presentation ppt = new Presentation();throws Exception 

        //add a shape to the first slide
        IAutoShape shape = ppt.getSlides().get(0).getShapes().appendShape(ShapeType.TRIANGLE, new Rectangle2D.Double(115, 130, 100, 100));
        shape.getFill().setFillType(FillFormatType.SOLID);
        shape.getFill().getSolidColor().setColor(Color.orange);
        shape.getShapeStyle().getLineColor().setColor(Color.white);

        //set alt text (title and description) for the shape
        shape.setAlternativeTitle("Triangle");
        shape.setAlternativeText("This is a triangle.");

        //save the resultant document
        ppt.saveToFile("Output.pptx", FileFormat.PPTX_2013);
    }
}

Set and Get Alternative Text (Alt Text) of PowerPoint Shapes in Java

Get alternative text

import com.spire.presentation.*;

public class GetAltText {
    public static void main(String[] args) throws Exception {
        //load PowerPoint document
        Presentation ppt = new Presentation();
        ppt.loadFromFile("Output.pptx");

        //get the first shape in the first slide
        IShape shape = ppt.getSlides().get(0).getShapes().get(0);

        //get the alt text (title and description) of the shape
        String altTitle = shape.getAlternativeTitle();
        String altDescription = shape.getAlternativeText();

        System.out.println("Title: " + altTitle);
        System.out.println("Description: " + altDescription);
    }
}

Set and Get Alternative Text (Alt Text) of PowerPoint Shapes in Java

Tuesday, 03 September 2019 06:59

Replace an Image in PowerPoint in Java

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

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\\Administrator\\Desktop\\input.pptx");

        //add an image to the image collection
        String imagePath = "C:\\Users\\Administrator\\Desktop\\Microsoft-PowerPoint-logo.jpg";
        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);
    }
}

Replace an Image in PowerPoint in Java

Monday, 16 January 2023 08:38

Java: Add, Hide or Delete Layers in PDF

PDF layers are supported through the usage of Optional Content Group (OCG) objects. As its name implies, optional content refers to the content in a PDF document that can be made visible or invisible dynamically by the user of PDF viewer applications. In this article, you will learn how to programmatically add, hide or delete layers in a PDF file using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, 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.3.4</version>
    </dependency>
</dependencies>
    

Add Layers to a PDF Document in Java

Spire.PDF for Java provides PdfDocument.getLayers().addLayer() method to add a layer in a PDF document, and you can then draw text, lines, images or shapes on the PDF layer. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a sample PDF file using PdfDocument.loadFromFile() method.
  • Add a layer with specified name in the PDF using PdfDocument.getLayers().addLayer(java.lang.String name) method. Or you can also set the visibility of the layer while adding it using PdfDocument. getLayers().addLayer(java.lang.String name, PdfVisibility state) method.
  • Create a canvas for the layer using PdfLayer.createGraphics() method.
  • Draw text, image or other elements on the canvas.
  • Save the result document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;
import com.spire.pdf.graphics.layer.PdfLayer;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.io.IOException;

public class AddLayersToPdf {

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

        //Create a PdfDocument instance and load the sample PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf");

        //Invoke AddLayerWatermark method to add a watermark layer
        AddLayerWatermark(pdf);

        //Invoke AddLayerHeader method to add a header layer
        AddLayerHeader(pdf);

        //Save to file
        pdf.saveToFile("AddLayers.pdf");
        pdf.close();
    }

    private static void AddLayerWatermark(PdfDocument doc) throws IOException {

        //Create a layer named "watermark"
        PdfLayer layer = doc.getLayers().addLayer("Watermark");

        //Create a font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,48),true);

        //Specify watermark text
        String watermarkText = "CONFIDENTIAL";

        //Get text size
        Dimension2D fontSize = font.measureString(watermarkText);

        //Calculate two offsets
        float offset1 = (float)(fontSize.getWidth() * Math.sqrt(2) / 4);
        float offset2 = (float)(fontSize.getHeight() * Math.sqrt(2) / 4);

        //Get page count
        int pageCount = doc.getPages().getCount();

        //Declare two variables
        PdfPageBase page;
        PdfCanvas canvas;

        //Loop through the pages
        for (int i = 0; i < pageCount; i++) {

            page = doc.getPages().get(i);

            //Create a canvas from layer
            canvas = layer.createGraphics(page.getCanvas());
            canvas.translateTransform(canvas.getSize().getWidth() / 2 - offset1 - offset2, canvas.getSize().getHeight() / 2 + offset1 - offset2);
            canvas.setTransparency(0.4f);
            canvas.rotateTransform(-45);

            //Draw sting on the canvas of layer
            canvas.drawString(watermarkText, font, PdfBrushes.getDarkBlue(), 0, 0);
        }
    }

    private static void AddLayerHeader(PdfDocument doc) {

        //Create a layer named "header"
        PdfLayer layer = doc.getLayers().addLayer("Header");

        //Get page size
        Dimension2D size = doc.getPages().get(0).getSize();

        //Specify the initial values of X and y
        float x = 90;
        float y = 40;

        //Get page count
        int pageCount = doc.getPages().getCount();

        //Declare two variables
        PdfPageBase page;
        PdfCanvas canvas;

        //Loop through the pages
        for (int i = 0; i < pageCount; i++) {

            //Draw an image on the layer
            PdfImage pdfImage = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\img.jpg");
            float width = pdfImage.getWidth();
            float height = pdfImage.getHeight();
            page = doc.getPages().get(i);
            canvas = layer.createGraphics(page.getCanvas());
            canvas.drawImage(pdfImage, x, y, width, height);

            //Draw a line on the layer
            PdfPen pen = new PdfPen(PdfBrushes.getDarkGray(), 2f);
            canvas.drawLine(pen, x, y + height + 5, size.getWidth() - x, y + height + 2);
        }
    }
}

Java: Add, Hide or Delete Layers in PDF

Set Visibility of Layers in a PDF Document in Java

To set the visibility of an existing layer, you'll need to get a specified layer by its index or name using PdfDocument.getLayers().get() method, and then show or hide the layer using PdfLayer.setVisibility(PdfVisibility value) method. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a sample PDF document using PdfDocument.loadFromFile() method.
  • Set the visibility of a specified layer using PdfDocument.getLayers().get().setVisibility() method.
  • Save the result document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.layer.PdfVisibility;

public class SetLayerVisibility {
    public static void main(String[] args) {

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load a sample PDF file
        pdf.loadFromFile("AddLayers.pdf");

        //Set the visibility of the first layer to off
        pdf.getLayers().get(0).setVisibility(PdfVisibility.Off);

        //Save to file
        pdf.saveToFile("HideLayer.pdf", FileFormat.PDF);
        pdf.dispose();
    }
}

Java: Add, Hide or Delete Layers in PDF

Delete Layers in a PDF Document in Java

Spire.PDF for Java also allows you to remove an existing layer by its name using PdfDocument.getLayers().removeLayer(java.lang.String name) method. But kindly note that the names of PDF layers may not be unique and this method will remove all PDF layers with the same name. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Delete a specified layer by its name using PdfDocument.getLayers().removeLayer() method.
  • Save the result document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;

public class DeleteLayers {

    public static void main(String[] args) {

        //Create a PdfDocument object and load the sample PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("AddLayers.pdf");

        //Delete the specific layer by its name
        pdf.getLayers().removeLayer("Watermark");

        //Save to file
        pdf.saveToFile("DeleteLayer.pdf");
        pdf.close();
    }
}

Java: Add, Hide or Delete Layers in 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.

This article demonstrates how to add a hyperlink to an image in a PowerPint slide using Spire.Presentation for Java.

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.geom.Rectangle2D;

public class AddHyperlinkToImage {

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

        //create a Presentation object
        Presentation presentation = new Presentation();

        //get the first slide
        ISlide slide = presentation.getSlides().get(0);

        //add an image to slide
        String imaPath = "C:\\Users\\Administrator\\Desktop\\logo.png";
        Rectangle2D.Float rect = new Rectangle2D.Float(50, 50, 220, 60);
        IEmbedImage image = slide.getShapes().appendEmbedImage(ShapeType.RECTANGLE, imaPath, rect);

        //set the line of image shape to none
        image.getLine().setFillType(FillFormatType.NONE);

        //add a hyperlink to image
        ClickHyperlink hyperlink = new ClickHyperlink("https://www.e-iceblue.com");
        image.setClick(hyperlink);

        //save the file
        presentation.saveToFile("output/ImageHyperLink.pptx", FileFormat.PPTX_2013);
    }
}

Add Hyperlinks to Images in PowerPoint in Java