Friday, 04 January 2019 08:11

Create Chart in PowerPoint in Java

This article demonstrates how to create a chart in a PowerPoint document using Spire.Presentation for Java.

import com.spire.presentation.*;
import com.spire.pdf.tables.table.*;
import com.spire.presentation.charts.*;
import com.spire.presentation.drawing.FillFormatType;
import java.awt.geom.Rectangle2D;
import java.lang.Object;


public class CreateChart {
    public static void main(String[] args) throws Exception {
        
        //Create a presentation instance
        Presentation presentation = new Presentation();

        //Add a column clustered chart
        Rectangle2D.Double rect = new Rectangle2D.Double(40, 100, 550, 320);
        IChart chart = null;
        chart = presentation.getSlides().get(0).getShapes().appendChart(ChartType.COLUMN_CLUSTERED, rect);

        //Set chart title
        chart.getChartTitle().getTextProperties().setText("Sales Report");
        chart.getChartTitle().getTextProperties().isCentered(true);
        chart.getChartTitle().setHeight(30);
        chart.hasTitle(true);

        //Create a dataTable
        DataTable dataTable = new DataTable();
        dataTable.getColumns().add(new DataColumn("SalesPers", DataTypes.DATATABLE_STRING));
        dataTable.getColumns().add(new DataColumn("SaleAmt", DataTypes.DATATABLE_INT));
        dataTable.getColumns().add(new DataColumn("ComPct", DataTypes.DATATABLE_INT));
        dataTable.getColumns().add(new DataColumn("ComAmt", DataTypes.DATATABLE_INT));
        DataRow row1 = dataTable.newRow();
        row1.setString("SalesPers", "Joe");
        row1.setInt("SaleAmt", 250);
        row1.setInt("ComPct", 150);
        row1.setInt("ComAmt", 99);
        DataRow row2 = dataTable.newRow();
        row2.setString("SalesPers", "Robert");
        row2.setInt("SaleAmt", 270);
        row2.setInt("ComPct", 150);
        row2.setInt("ComAmt", 99);
        DataRow row3 = dataTable.newRow();
        row3.setString("SalesPers", "Michelle");
        row3.setInt("SaleAmt", 310);
        row3.setInt("ComPct", 120);
        row3.setInt("ComAmt", 49);
        DataRow row4 = dataTable.newRow();
        row4.setString("SalesPers", "Erich");
        row4.setInt("SaleAmt", 330);
        row4.setInt("ComPct", 120);
        row4.setInt("ComAmt", 49);
        DataRow row5 = dataTable.newRow();
        row5.setString("SalesPers", "Dafna");
        row5.setInt("SaleAmt", 360);
        row5.setInt("ComPct", 150);
        row5.setInt("ComAmt", 141);
        DataRow row6 = dataTable.newRow();
        row6.setString("SalesPers", "Rob");
        row6.setInt("SaleAmt", 380);
        row6.setInt("ComPct", 150);
        row6.setInt("ComAmt", 135);
        dataTable.getRows().add(row1);
        dataTable.getRows().add(row2);
        dataTable.getRows().add(row3);
        dataTable.getRows().add(row4);
        dataTable.getRows().add(row5);
        dataTable.getRows().add(row6);

        //Import data from dataTable to chart data
        for (int c = 0; c < dataTable.getColumns().size(); c++) {
            chart.getChartData().get(0, c).setText(dataTable.getColumns().get(c).getColumnName());
        }
        for (int r = 0; r < dataTable.getRows().size(); r++) {
            Object[] datas = dataTable.getRows().get(r).getArrayList();
            for (int c = 0; c < datas.length; c++) {
                chart.getChartData().get(r + 1, c).setValue(datas[c]);

            }
        }

        chart.getSeries().setSeriesLabel(chart.getChartData().get("B1", "D1"));
        chart.getCategories().setCategoryLabels(chart.getChartData().get("A2", "A7"));
        chart.getSeries().get(0).setValues(chart.getChartData().get("B2", "B7"));

        chart.getSeries().get(1).setValues(chart.getChartData().get("C2", "C7"));

        chart.getSeries().get(2).setValues(chart.getChartData().get("D2", "D7"));
        chart.getSeries().get(2).getFill().setFillType(FillFormatType.SOLID);                    
      chart.getSeries().get(2).getFill().getSolidColor().setKnownColor(KnownColors.LIGHT_BLUE);

        //Set overlap
        chart.setOverLap(-50);

        //Set gap width
        chart.setGapDepth(200);

        //Save the document
        presentation.saveToFile("output/CreateChart.pptx", FileFormat.PPTX_2010);
    }
}

Create Chart in PowerPoint in Java

This article demonstrates how to add, read and delete speaker notes in a PowerPoint document using Spire.Presentation for Java.

Add Speaker Notes

import com.spire.presentation.*;

public class SpeakerNotes {
    public static void main(String[] args) throws Exception {
        //Load the PowerPoint document
        Presentation ppt = new Presentation();
        ppt.loadFromFile("Sample.pptx");

        //Get the first slide
        ISlide slide = ppt.getSlides().get(0);
        //Add note slide
        NotesSlide notesSlide = slide.addNotesSlide();

        //Add a paragraph to the note slide
        ParagraphEx paragraph = new ParagraphEx();
        paragraph.setText("Tips for making effective presentations:");
        notesSlide.getNotesTextFrame().getParagraphs().append(paragraph);

        //Add a paragraph to the note slide
        paragraph = new ParagraphEx();
        paragraph.setText("Use the slide master feature to create a consistent and simple design template.");
        notesSlide.getNotesTextFrame().getParagraphs().append(paragraph);
        //Set the bullet type and style for the paragraph
        notesSlide.getNotesTextFrame().getParagraphs().get(1).setBulletType(TextBulletType.NUMBERED);
        notesSlide.getNotesTextFrame().getParagraphs().get(1).setBulletStyle(NumberedBulletStyle.BULLET_ARABIC_PERIOD);

        //Add a paragraph to the note slide
        paragraph = new ParagraphEx();
        paragraph.setText("Simplify and limit the number of words on each screen.");
        notesSlide.getNotesTextFrame().getParagraphs().append(paragraph);
        //Set the bullet type and style for the paragraph
        notesSlide.getNotesTextFrame().getParagraphs().get(2).setBulletType(TextBulletType.NUMBERED);
        notesSlide.getNotesTextFrame().getParagraphs().get(2).setBulletStyle(NumberedBulletStyle.BULLET_ARABIC_PERIOD);

        //Add a paragraph to the note slide
        paragraph = new ParagraphEx();
        paragraph.setText("Use contrasting colors for text and background.");
        notesSlide.getNotesTextFrame().getParagraphs().append(paragraph);
        //Set the bullet and style type for the paragraph
        notesSlide.getNotesTextFrame().getParagraphs().get(3).setBulletType(TextBulletType.NUMBERED);
        notesSlide.getNotesTextFrame().getParagraphs().get(3).setBulletStyle(NumberedBulletStyle.BULLET_ARABIC_PERIOD);

        //Save the document
        ppt.saveToFile("SpeakerNotes.pptx", FileFormat.PPTX_2013);
    }
}

Add, Read and Delete Speaker Notes in PowerPoint in Java

Read Speaker Notes

import com.spire.presentation.*;

import java.io.FileWriter;

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

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

        //Get the content of notes from note slide
        StringBuilder buffer = new StringBuilder();
        String notes = slide.getNotesSlide().getNotesTextFrame().getText();
        buffer.append(notes);

        //Save to .txt file
        FileWriter writer = new FileWriter("SpeakerNotes.txt");
        writer.write(buffer.toString());
        writer.flush();
        writer.close();

    }
}

Add, Read and Delete Speaker Notes in PowerPoint in Java

Delete Speaker Notes

import com.spire.presentation.*;

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

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

        //Delete all speaker notes from the note slide
        slide.getNotesSlide().getNotesTextFrame().getParagraphs().clear();

        //Save the document
        ppt.saveToFile("DeleteSpeakerNotes.pptx", FileFormat.PPTX_2013);
    }
}

Add, Read and Delete Speaker Notes in PowerPoint in Java

Thursday, 03 January 2019 06:34

Add Shapes to PowerPoint in Java

This article demonstrates how to add a variety of shapes to a PowerPoint slide and how to fill the shapes with a solid color, a picture, a pattern or a gradient.

Entire Code

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

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

public class AddShapes {

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

        //create a PowerPoint document
        Presentation presentation = new Presentation();

        //append a Triangle and fill the shape with a solid color
        IAutoShape shape = presentation.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);

        //append an Ellipse and fill the shape with a picture
        shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.ELLIPSE, new Rectangle2D.Double(290, 130, 150, 100));
        shape.getFill().setFillType(FillFormatType.PICTURE);
        shape.getFill().getPictureFill().setFillType(PictureFillType.STRETCH);
        BufferedImage image = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\logo.png"));
        shape.getFill().getPictureFill().getPicture().setEmbedImage(presentation.getImages().append(image));
        shape.getShapeStyle().getLineColor().setColor(Color.white);

        //append a Heart and fill the shape with a pattern
        shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.HEART, new Rectangle2D.Double(515, 130, 130, 100));
        shape.getFill().setFillType(FillFormatType.PATTERN);
        shape.getFill().getPattern().setPatternType(PatternFillType.CROSS);
        shape.getShapeStyle().getLineColor().setColor(Color.white);

        //append a Five-Pointed Star and fill the shape with a gradient color
        shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.FIVE_POINTED_STAR, new Rectangle2D.Double(115, 300, 100, 100));
        shape.getFill().setFillType(FillFormatType.GRADIENT);
        shape.getFill().getGradient().getGradientStops().append(0, KnownColors.BLACK);
        shape.getShapeStyle().getLineColor().setColor(Color.white);

        //append a Rectangle and fill the shape with gradient colors
        shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Double(290, 300, 150, 100));
        shape.getFill().setFillType(FillFormatType.GRADIENT);
        shape.getFill().getGradient().getGradientStops().append(0, KnownColors.LIGHT_SKY_BLUE);
        shape.getFill().getGradient().getGradientStops().append(1, KnownColors.ROYAL_BLUE);
        shape.getShapeStyle().getLineColor().setColor(Color.white);

        //append a Bent Up Arrow and fill the shape with gradient colors
        shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.BENT_UP_ARROW, new Rectangle2D.Double(515, 300, 130, 100));
        shape.getFill().setFillType(FillFormatType.GRADIENT);
        shape.getFill().getGradient().getGradientStops().append(1f, KnownColors.OLIVE);
        shape.getFill().getGradient().getGradientStops().append(0, KnownColors.POWDER_BLUE);
        shape.getShapeStyle().getLineColor().setColor(Color.white);

        //save the document
        presentation.saveToFile("output/AddShapes.pptx", FileFormat.PPTX_2010);
    }
}

Output

Add Shapes to PowerPoint in Java

Spire.Presentation for Java supports to add numbered lists as well as bulleted lists to PowerPoint document. This article demonstrates how to add a numbered list, a symbol bulleted list and a custom picture bulleted list using Spire.Presentation for Java.

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

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

public class AddBullets {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();

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

        Rectangle2D rect = new Rectangle2D.Double(50, 70, 300, 200);
        //Append a shape to the slide and set shape style
        IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, rect);
        shape.getShapeStyle().getLineColor().setColor(Color.white);
        shape.getFill().setFillType(FillFormatType.NONE);

        //Clear the default paragragh
        shape.getTextFrame().getParagraphs().clear();

        String[] str = new String[] {"Item 1", "Item 2", "Item 3" ,"Item 4", "Item 5", "Item 6","Item 7", "Item 8", "Item 9" };

        //Add a numbered bulleted list
        for(int i = 0; i < 3; i ++)
        {
            ParagraphEx paragraph = new ParagraphEx();
            shape.getTextFrame().getParagraphs().append(paragraph);
            paragraph.setText(str[i]);
            paragraph.getTextRanges().get(0).getFill().setFillType(FillFormatType.SOLID);
            paragraph.getTextRanges().get(0).getFill().getSolidColor().setColor(Color.black);
            paragraph.setBulletType(TextBulletType.NUMBERED);
            paragraph.setBulletStyle(NumberedBulletStyle.BULLET_ROMAN_LC_PERIOD);
        }

        //Add a symbol bulleted list
        for(int j = 3; j < 6; j ++)
        {
            ParagraphEx paragraph = new ParagraphEx();
            shape.getTextFrame().getParagraphs().append(paragraph);
            paragraph.setText(str[j]);
            paragraph.getTextRanges().get(0).getFill().setFillType(FillFormatType.SOLID);
            paragraph.getTextRanges().get(0).getFill().getSolidColor().setColor(Color.black);
            paragraph.setBulletType(TextBulletType.SYMBOL);
        }

        //Add a custom bulleted list with picture
        for(int k = 6; k < str.length; k ++)
        {
            ParagraphEx paragraph = new ParagraphEx();
            shape.getTextFrame().getParagraphs().append(paragraph);
            paragraph.setText(str[k]);
            paragraph.getTextRanges().get(0).getFill().setFillType(FillFormatType.SOLID);
            paragraph.getTextRanges().get(0).getFill().getSolidColor().setColor(Color.black);
            paragraph.setBulletType(TextBulletType.PICTURE);
            BufferedImage image = ImageIO.read(new File("timg.jpg"));
            paragraph.getBulletPicture().setEmbedImage(ppt.getImages().append(image));
        }

        //Save the document
        ppt.saveToFile("AddBullets.pptx", FileFormat.PPTX_2013);
    }
}

Create Numbered and Bulleted Lists in PowerPoint in Java

Wednesday, 26 December 2018 03:55

Add Attachments to PDF in Java

There are two ways in Spire.PDF to attach files to a PDF document – add attachments to background and add attachments as annotations. This article demonstrates the same.

import com.spire.pdf.annotations.*;
import com.spire.pdf.attachments.PdfAttachment;
import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class AttachFiles {

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

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

        //load a sample PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf");

        //add an attachment to pdf
        PdfAttachment attachment = new PdfAttachment("C:\\Users\\Administrator\\Desktop\\ReadMe.txt");
        doc.getAttachments().add(attachment);

        //draw a label on pdf
        String label = "Report.docx";
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 14));
        double x = 30;
        double y = doc.getPages().get(0).getActualSize().getHeight() - 100;
        doc.getPages().get(0).getCanvas().drawString(label, font, PdfBrushes.getOrange(), x, y);

        //add an attachment annotation to pdf
        String filePath = "C:\\Users\\Administrator\\Desktop\\Report.docx";
        byte[] data = toByteArray(filePath);
        Dimension2D size = font.measureString(label);
        Rectangle2D bound = new Rectangle2D.Float((float) (x + size.getWidth() + 2), (float) y, 10, 15);
        PdfAttachmentAnnotation annotation = new PdfAttachmentAnnotation(bound, filePath, data);
        annotation.setColor(new PdfRGBColor(new Color(0, 128, 128)));
        annotation.setFlags(PdfAnnotationFlags.Default);
        annotation.setIcon(PdfAttachmentIcon.Graph);
        annotation.setText("Click to open Report.docx");
        doc.getPages().get(0).getAnnotationsWidget().add(annotation);

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

    //read file to byte array
    public static byte[] toByteArray(String filePath) throws IOException {

        File file = new File(filePath);
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            System.out.println("file too big...");
            return null;
        }
        FileInputStream fi = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
                && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }

        if (offset != buffer.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        fi.close();
        return buffer;
    }
}

Output:

Add Attachments to PDF in Java

In this article, we will show you how to read/extract text from a PowerPoint document using Spire.Presentation for Java.

The sample PowerPoint document:

Read/Extract Text from a PowerPoint Document in Java

import com.spire.presentation.*;

import java.io.FileWriter;

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

        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //Load the PowerPoint document
        ppt.loadFromFile("Input.pptx");

        StringBuilder buffer = new StringBuilder();

        //Loop through the slides in the document and extract text
        for (Object slide : ppt.getSlides()) {
            for (Object shape : ((ISlide) slide).getShapes()) {
                if (shape instanceof IAutoShape) {
                    for (Object tp : ((IAutoShape) shape).getTextFrame().getParagraphs()) {
                        buffer.append(((ParagraphEx) tp).getText());
                    }
                }
            }
        }
        //Save text
        FileWriter writer = new FileWriter("ExtractText.txt");
        writer.write(buffer.toString());
        writer.flush();
        writer.close();
    }
}

Output:

Read/Extract Text from a PowerPoint Document in Java

Tuesday, 25 December 2018 06:40

Protect presentation slides in Java

Spire.Presentation for Java enables developers to encrypt the PowerPoint files with password, set write protection to make the presentation read only, modify the password and decrypted the presentation slides. This article will show you how to protect the presentation slides in Java applications as below:

  • Encrypt the presentation slides
  • Set the presentation slides read only
  • Decrypt the presentation slides
  • Load an encrypted PowerPoint document and modify its password

Encrypt PowerPoint file

Presentation presentation = new Presentation();
presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pptx");

presentation.encrypt("e-iceblue");

presentation.saveToFile("output/Encrypted.pptx", FileFormat.PPTX_2010);

Protect presentation slides in Java

Set the presentation slides read only

Presentation presentation = new Presentation();
presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pptx");

presentation.protect("123456");

presentation.saveToFile("output/Readonly.pptx", FileFormat.PPTX_2010);

Protect presentation slides in Java

Remove Encryption on Password-Protected PowerPoint File

Presentation presentation = new Presentation();
//load the encrypted document with password
presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\Encrypted.pptx", FileFormat.PPTX_2010,"e-iceblue");

//Remove encryption
presentation.removeEncryption();

presentation.saveToFile("output/Decrypted.pptx", FileFormat.PPTX_2010);

Modify the password of the protected PowerPoint document

Presentation presentation = new Presentation();

//load the encrypted document with password
presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\Encrypted.pptx", FileFormat.PPTX_2010,"e-iceblue");

//Remove the Encryption
presentation.removeEncryption();
//Set the new password to encrypt the document
presentation.encrypt("Newpass");

presentation.saveToFile("output/Modifypass.pptx", FileFormat.PPTX_2010);
Friday, 21 December 2018 06:46

Create Table in PowerPoint in Java

This article demonstrates how to create a table and set table style in a PowerPoint document using Spire.Presentation for Java.

import com.spire.presentation.*;

public class AddTable {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation presentation = new Presentation();

        Double[] widths = new Double[]{100d, 100d, 150d, 100d, 100d};
        Double[] heights = new Double[]{15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d};

        //Add a table 
        ITable table = presentation.getSlides().get(0).getShapes().appendTable((float) presentation.getSlideSize().getSize().getWidth() / 2 - 275, 90, widths, heights);
        String[][] dataStr = new String[][]
                {
                        {"Name", "Capital", "Continent", "Area", "Population"},
                        {"Venezuela", "Caracas", "South America", "912047", "19700000"},
                        {"Bolivia", "La Paz", "South America", "1098575", "7300000"},
                        {"Brazil", "Brasilia", "South America", "8511196", "150400000"},
                        {"Canada", "Ottawa", "North America", "9976147", "26500000"},
                        {"Chile", "Santiago", "South America", "756943", "13200000"},
                        {"Colombia", "Bagota", "South America", "1138907", "33000000"},
                        {"Cuba", "Havana", "North America", "114524", "10600000"},
                        {"Ecuador", "Quito", "South America", "455502", "10600000"},
                        {"Paraguay", "Asuncion", "South America", "406576", "4660000"},
                        {"Peru", "Lima", "South America", "1285215", "21600000"},
                        {"Jamaica", "Kingston", "North America", "11424", "2500000"},
                        {"Mexico", "Mexico City", "North America", "1967180", "88600000"}
                };
        //Add data to table
        for (int i = 0; i < 13; i++) {
            for (int j = 0; j < 5; j++) {
                //Fill the table with data
                table.get(j, i).getTextFrame().setText(dataStr[i][j]);

                //Set font
                table.get(j, i).getTextFrame().getParagraphs().get(0).getTextRanges().get(0).setLatinFont(new TextFont("Arial Narrow"));
            }
        }
        //Set the alignment of the first table row to Center
        for (int i = 0; i < 5; i++) {
            table.get(i, 0).getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.CENTER);
        }
        //Set the style of table
        table.setStylePreset(TableStylePreset.LIGHT_STYLE_3_ACCENT_1);

        //Save the document
        presentation.saveToFile("AddTable.pptx", FileFormat.PPTX_2013);
    }
}

Output:

Create Table in PowerPoint in Java

Wednesday, 19 December 2018 09:01

Add Links to PDF in Java

This article demonstrates how to add links, including ordinary link, hypertext link, email link and document link, to a PDF document by using Spire.PDF for Java.

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

import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.HashMap;

public class AddLinksToPdf {

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

        //create a pdf document
        PdfDocument doc = new PdfDocument();
        PdfPageBase page = doc.getPages().add();

        //initialize x, y coordinates
        float y = 30;
        float x = 0;

        //create a plain font
        PdfTrueTypeFont plainFont = new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,13),true);

        //create a underlined font
        HashMap<TextAttribute, Object> hm = new HashMap<TextAttribute, Object>();
        hm.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        hm.put(TextAttribute.SIZE, 13);
        hm.put(TextAttribute.FAMILY, "Arial");
        Font font = new Font(hm);
        PdfTrueTypeFont underlineFont = new PdfTrueTypeFont(font);

        //add a simply link to pdf
        String label = "Simply Link: ";
        PdfStringFormat format = new PdfStringFormat();
        format.setMeasureTrailingSpaces(true);
        page.getCanvas().drawString(label, plainFont, PdfBrushes.getOrange(), 0, y,format);
        x = (float)plainFont.measureString(label,format).getWidth();
        page.getCanvas().drawString("https://www.e-iceblue.com", underlineFont, PdfBrushes.getBlue(), x, y+2);
        y = y + 26;

        //add a hyper text link to pdf
        label= "Hypertext Link: ";
        page.getCanvas().drawString(label, plainFont, PdfBrushes.getOrange(), 0, y, format);
        x = (float)plainFont.measureString(label,format).getWidth();
        PdfTextWebLink webLink = new PdfTextWebLink();
        webLink.setText("Home Page");
        webLink.setUrl("https://www.e-iceblue.com");
        webLink.setFont(plainFont);
        webLink.setBrush(PdfBrushes.getBlue());
        webLink.drawTextWebLink(page.getCanvas(), new Point2D.Float(x, y));
        y= y + 26;

        //add an email link to pdf
        label = "Email Link:  ";
        page.getCanvas().drawString(label, plainFont, PdfBrushes.getOrange(), 0, y, format);
        x = (float)plainFont.measureString(label, format).getWidth();
        webLink = new PdfTextWebLink();
        webLink.setText("Contact Us");
        webLink.setUrl("mailto:support@e-iceblue.com");
        webLink.setFont(plainFont);
        webLink.setBrush(PdfBrushes.getBlue());
        webLink.drawTextWebLink(page.getCanvas(), new Point2D.Float(x, y));
        y = y + 26;

        //add a document link to pdf
        label = "Document Link: ";
        page.getCanvas().drawString(label, plainFont, PdfBrushes.getOrange(), 0, y, format);
        x = (float)plainFont.measureString(label, format).getWidth();
        page.getCanvas().drawString("Open File", plainFont, PdfBrushes.getBlue(), x, y, format);
        Rectangle2D rect = new Rectangle2D.Float(x,y+2,60,15);
        PdfFileLinkAnnotation fileLinkAnnotation = new PdfFileLinkAnnotation(rect,"C:\\Users\\Administrator\\Desktop\\Image.png");
        fileLinkAnnotation.setBorder(new PdfAnnotationBorder(0f));
        ((PdfNewPage) ((page instanceof PdfNewPage) ? page : null)).getAnnotations().add(fileLinkAnnotation);

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

Output:

Add Links to PDF in Java

This article will demonstrate how to use Spire.Presentaion for Java to operate the presentation slides. Such as adding new slide in PowerPoint document, removing an existing slide, hiding slide from a PowerPoint document and changing the Slide Order within a Presentation in Java applications.

Add new slides to an existing PowerPoint document.

import com.spire.presentation.*;

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

        //Create a PPT document and load file
        Presentation presentation = new Presentation();
        presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pptx");
        
        //add new slide at the end of the document
        presentation.getSlides().append();

        //insert a blank slide before the second slide
        presentation.getSlides().insert(1);

       //Save the document
        presentation.saveToFile("output/AddSlide.pptx", FileFormat.PPTX_2010);
    }

}

Operate the presentation slide on Java applications

Hide a slide that we don't want to present to audiences without deleting it.

import com.spire.presentation.*;
public class Slides {
    public static void main(String[] args) throws Exception {
        //Create a PPT document and load file
        Presentation presentation = new Presentation();
        presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pptx");
        
        //Hide the second slide
        presentation.getSlides().get(1).setHidden(true);

        //Save the document
        presentation.saveToFile("output/HideSlide.pptx", FileFormat.PPTX_2010);
    }
}

Operate the presentation slide on Java applications

Delete a slide from the PowerPoint document

import com.spire.presentation.*;
public class Slides {
    public static void main(String[] args) throws Exception {
        
        //Create a PPT document and load file
        Presentation presentation = new Presentation();
        presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pptx");
        
        //Remove the third slide
        presentation.getSlides().removeAt(2);
      
        //Save the document
        presentation.saveToFile("output/Removeslide.pptx", FileFormat.PPTX_2010);
    }
}

Operate the presentation slide on Java applications

Change the Slide Order within a PowerPoint document

import com.spire.presentation.*;

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

        //Create a PPT document and load file
        Presentation presentation = new Presentation();
        presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pptx");

        //Move the first slide to the second slide position
        ISlide slide = presentation.getSlides().get(0);
        slide.setSlideNumber(2);

       //Save the document
        presentation.saveToFile("output/Reorderslide.pptx", FileFormat.PPTX_2010);
    }

}

Operate the presentation slide on Java applications

Page 8 of 108