Friday, 05 August 2022 09:36

Java: Add Hyperlinks to Word Documents

A hyperlink is the most important element that we use in digital documents to make connections between two things. When readers click on a hyperlink in a Word document, it will take them to a different location within the document, to a different file or website, or to a new email message. This article introduces how to add hyperlinks to Word documents in Java using Spire.Doc for Java.

Install Spire.Doc for Java

First, you're required to add the Spire.Doc.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.doc</artifactId>
        <version>12.4.6</version>
    </dependency>
</dependencies>
    

Insert Hyperlinks When Adding Paragraphs to Word

Spire.Doc for Java offers the Paragraph.appendHyperlink() method to add a web link, an email link, a file link, or a bookmark link to a piece of text or an image inside a paragraph. The following are the detailed steps.

  • Create a Document object.
  • Add a section and a paragraph to it.
  • Insert a hyperlink based on text using Paragraph.appendHyerplink(String link, String text, HyperlinkType type) method.
  • Add an image to the paragraph using Paragraph.appendPicture() method.
  • Add a hyperlink to the image using Paragraph.appendHyerplink(String link, DocPicture picture, HyperlinkType type) method.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.BookmarkStart;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.BreakType;
import com.spire.doc.documents.HyperlinkType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocPicture;

public class InsertHyperlinks {

    public static void main(String[] args) {

        //Create a Word document
        Document doc = new Document();

        //Add a section
        Section section = doc.addSection();

        //Add a paragraph
        Paragraph paragraph = section.addParagraph();
        paragraph.appendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.Web_Link);

        //Append line breaks
        paragraph.appendBreak(BreakType.Line_Break);
        paragraph.appendBreak(BreakType.Line_Break);

        //Add an email link
        paragraph.appendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.E_Mail_Link);

        //Append line breaks
        paragraph.appendBreak(BreakType.Line_Break);
        paragraph.appendBreak(BreakType.Line_Break);

        //Add a file link
        String filePath = "C:\\Users\\Administrator\\Desktop\\report.xlsx";
        paragraph.appendHyperlink(filePath, "Click to open the report", HyperlinkType.File_Link);

        //Append line breaks
        paragraph.appendBreak(BreakType.Line_Break);
        paragraph.appendBreak(BreakType.Line_Break);

        //Add another section and create a bookmark
        Section section2 = doc.addSection();
        Paragraph bookmarkParagraph = section2.addParagraph();
        bookmarkParagraph.appendText("Here is a bookmark");
        BookmarkStart start = bookmarkParagraph.appendBookmarkStart("myBookmark");
        bookmarkParagraph.getItems().insert(0, start);
        bookmarkParagraph.appendBookmarkEnd("myBookmark");

        //Link to the bookmark
        paragraph.appendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark);

        //Append line breaks
        paragraph.appendBreak(BreakType.Line_Break);
        paragraph.appendBreak(BreakType.Line_Break);

        //Add an image link
        String imagePath = "C:\\Users\\Administrator\\Desktop\\logo.png";
        DocPicture picture = paragraph.appendPicture(imagePath);
        paragraph.appendHyperlink("https://www.e-iceblue.com/", picture, HyperlinkType.Web_Link);

        //Save to file
        doc.saveToFile("output/InsertHyperlinks.docx", FileFormat.Docx_2013);
    }
}

Java: Add Hyperlinks to Word Documents

Add Hyperlinks to Existing Text in Word

Adding hyperlinks to existing text in a document is a bit more complicated. You need to find the target string first, and then replace it in the paragraph with a hyperlink field. The following are the steps.

  • Create a Document object.
  • Load a Word file using Document.loadFromFile() method.
  • Find all the occurrences of the target string in the document using Document.findAllString() method, and get the specific one by its index from the collection.
  • Get the string’s own paragraph and its position in it.
  • Remove the string from the paragraph.
  • Create a hyperlink field and insert it to position where the string is located.
  • Save the document to another file using Document.saveToFle() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FieldType;
import com.spire.doc.FileFormat;
import com.spire.doc.Hyperlink;
import com.spire.doc.documents.*;
import com.spire.doc.fields.Field;
import com.spire.doc.fields.FieldMark;
import com.spire.doc.fields.TextRange;
import com.spire.doc.interfaces.IParagraphBase;
import com.spire.doc.interfaces.ITextRange;

import java.awt.*;

public class AddHyperlinksToExistingText {

    public static void main(String[] args) {

        //Create a Document object
        Document document = new Document();

        //Load a Word file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

        //Find all the occurrences of the string "Java" in the document
        TextSelection[] selections = document.findAllString("Java", true, true);

        //Get the second occurrence
        TextRange range = selections[1].getAsOneRange();

        //Get its owner paragraph
        Paragraph paragraph = range.getOwnerParagraph();

        //Get its position in the paragraph
        int index = paragraph.getItems().indexOf(range);

        //Remove it from the paragraph
        paragraph.getItems().remove(range);

        //Create a hyperlink field
        Field field = new Field(document);
        field.setType(FieldType.Field_Hyperlink);
        Hyperlink hyperlink = new Hyperlink(field);
        hyperlink.setType(HyperlinkType.Web_Link);
        hyperlink.setUri("https:\\en.wikipedia.org\\wiki\\Java_(programming_language)");
        paragraph.getItems().insert(index, field);

        //Insert a field mark "start" to the paragraph
        IParagraphBase item = document.createParagraphItem(ParagraphItemType.Field_Mark);
        FieldMark start = (FieldMark)item;
        start.setType(FieldMarkType.Field_Separator);
        paragraph.getItems().insert(index + 1, start);

        //Insert a text range between two field marks
        ITextRange textRange = new TextRange(document);
        textRange.setText("Java");
        textRange.getCharacterFormat().setFontName(range.getCharacterFormat().getFontName());
        textRange.getCharacterFormat().setFontSize(range.getCharacterFormat().getFontSize());
        textRange.getCharacterFormat().setBold(range.getCharacterFormat().getBold());
        textRange.getCharacterFormat().setTextColor(Color.blue);
        textRange.getCharacterFormat().setUnderlineStyle(UnderlineStyle.Single);
        paragraph.getItems().insert(index + 2, textRange);

        //Insert a field mark "end" to the paragraph
        IParagraphBase item2 = document.createParagraphItem(ParagraphItemType.Field_Mark);
        FieldMark end = (FieldMark)item2;
        end.setType(FieldMarkType.Field_End);
        paragraph.getItems().insert(index + 3, end);

        //Save to file
        document.saveToFile("output/AddHyperlink.docx", FileFormat.Docx_2013);
    }
}

Java: Add Hyperlinks to Word Documents

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.

Thursday, 16 June 2022 08:36

Java: Rotate Pages in PDF

Some scanned PDF documents may contain pages displayed in the wrong orientation (e.g., upside-down), which could cause great inconvenience while reading. Rotating pages can help you solve this problem and provide readers with a better reading experience. This article will introduce how to rotate pages in PDF in Java using Spire.PDF for Java.

Install Spire.PDF for Java

First, 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.4.4</version>
    </dependency>
</dependencies>
    

Rotate a Specific Page in PDF in Java

Rotation is based on 90-degree increments. You can rotate a PDF page by 0/90/180/270 degrees. The following are the steps to rotate a PDF page:

  • Create an instance of PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the desired page by its index (zero-based) using PdfDocument.getPages().get(pageIndex) method.
  • Get the original rotation angle of the page using PdfPageBase.getRotation().getValue() method.
  • Increase the original rotation angle by desired degrees.
  • Apply the new rotation angle to the page using PdfPageBase.setRotation() method.
  • Save the result document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageRotateAngle;

public class RotatePdfPage {
    public static void main(String []args){
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("Sample.pdf");

        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);

        //Get the original rotation angle of the page
        int rotation = page.getRotation().getValue();

        //Rotate the page 180 degrees clockwise based on the original rotation angle
        rotation += PdfPageRotateAngle.Rotate_Angle_180.getValue();
        page.setRotation(PdfPageRotateAngle.fromValue(rotation));

        //Save the result document
        pdf.saveToFile("Rotate.pdf");
    }
}

Java: Rotate Pages in PDF

Rotate All Pages in PDF in Java

The following are the steps to rotate all pages in a PDF document:

  • Create an instance of PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Loop through the pages in the document.
  • Get the original rotation angle of each page using PdfPageBase.getRotation().getValue() method.
  • Increase the original rotation angle by desired degrees.
  • Apply the new rotation angle to the page using PdfPageBase.setRotation() method.
  • Save the result document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageRotateAngle;

public class RotateAllPdfPages {
    public static void main(String []args){
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF document
        pdf.loadFromFile("Sample.pdf");

        //Loop through each page in the document
        for(PdfPageBase page :(Iterable) pdf.getPages()) {
            //Get the original rotation angle of the page
            int rotation = page.getRotation().getValue();
            //Rotate the page 180 degrees clockwise based on the original rotation angle
            rotation += PdfPageRotateAngle.Rotate_Angle_180.getValue();
            page.setRotation(PdfPageRotateAngle.fromValue(rotation));
        }

        //Save the result document
        pdf.saveToFile("RotateAll.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.

When you are collaborating on a PowerPoint document with your team members, adding comments is the most effective way to give feedbacks or communicate the changes you need to make on a particular slide. Once a comment has been added, you may also need to edit or delete it later. This article will demonstrate how to programmatically add, change or delete comments in a PowerPoint Document using Spire.Presentation for Java.

Install Spire.Presentation for Java

First of all, you're required to add the Spire.Presentation.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.presentation</artifactId>
        <version>9.4.5</version>
    </dependency>
</dependencies>
    

Add a Comment to a Presentation Slide in Java

Spire.Presentation for Java offers the ISlide.addComment() method to add comments to a specified PowerPoint slide. The following are the steps to add a PowerPoint comment.

  • Initialize an instance of Presentation class.
  • Load a PowerPoint document using Presentation.loadFromFile() method.
  • Add the author of the comment using Presentation.getCommentAuthors().addAuthor() method.
  • Get a specified slide using Presentation.getSlides().get() method, and then add a comment to the slide using ISlide.addComment(ICommentAuthor author, java.lang.String text, java.awt.geom.Point2D position, java.util.Date dateTime) method.
  • Save the result document using Presentation.saveToFile() method.
  • Java
import com.spire.presentation.*;
import java.awt.geom.Point2D;

public class AddComment {
    public static void main(String[] args) throws Exception{
        //Initialize an instance of Presentation class
        Presentation ppt = new Presentation();

        //Load a sample PowerPoint document
        ppt.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pptx");

        //Add the author of the comment
        ICommentAuthor author = ppt.getCommentAuthors().addAuthor("E-iceblue", "Comment:");

        //Add a comment to the specified slide
        ppt.getSlides().get(0).addComment(author, "The first comment", new Point2D.Float(350, 170), new java.util.Date());

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

Java: Add, Change or Delete Comments in PowerPoint

Change a Comment in a Presentation Slide in Java

To update or modify the content of an existing comment, you can use the ISlide.getComments().setText() method. The following are the steps to change a PowerPoint comment.

  • Initialize an instance of Presentation class.
  • Load a PowerPoint document using Presentation.loadFromFile() method.
  • Get a specified slide using Presentation.getSlides().get() method.
  • Replace a specified comment in the slide using ISlide.getComments().setText() method.
  • Save the result document using Presentation.saveToFile() method.
  • Java
import com.spire.presentation.*;

public class ReplaceComment {
    public static void main(String[] args) throws Exception{
        //Initialize an instance of Presentation class
        Presentation ppt = new Presentation();

        //Load a sample PowerPoint document
        ppt.loadFromFile("AddComment.pptx");

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

        //Replace a specified comment in the slide
        slide.getComments()[0].setText("Summary of Spire.Presentation for Java functions");

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

Java: Add, Change or Delete Comments in PowerPoint

Delete a Comment from a Presentation Slide in Java

Spire.Presentation for Java also allows you to remove comments from a specified slide using ISlide.deleteComment() method. The detailed steps are as follows.

  • Initialize an instance of Presentation class.
  • Load a PowerPoint document using Presentation.loadFromFile() method.
  • Get a specified slide using Presentation.getSlides().get() method.
  • Remove a specified comment from the slide using ISlide.deleteComment(Comment comment) method.
  • Save the result document using Presentation.saveToFile() method.
  • Java
import com.spire.presentation.*;

public class DeleteComment {
    public static void main(String[] args) throws Exception{
        //Initialize an instance of Presentation class
        Presentation ppt = new Presentation();

        //Load a sample PowerPoint document
        ppt.loadFromFile("AddComment.pptx");

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

        //Remove a specified comment from the slide
        slide.deleteComment(slide.getComments()[0]);

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

Java: Add, Change or Delete Comments in PowerPoint

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.

Adding, modifying, and removing footers in PowerPoint documents is crucial as footers can provide additional information and organizational structure to the document. By including page numbers, dates, author information, or custom text in the footer, it can help the audience better understand the presentation content and track document versions. Footers also enhance the professionalism and tidiness of the document, making it more visually appealing and readable. Modifying footers allows for updating information or adjusting formats as needed to ensure the document remains current and consistent. Removing footers can customize the document's appearance based on specific requirements or design preferences. This article will introduce how to use Spire.Presentation for Java to add, modify, and remove footers in PowerPoint documents within a Java project.

Install Spire.Presentation for Java

First of all, you're required to add the Spire.Presentation.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.presentation</artifactId>
        <version>9.4.5</version>
    </dependency>
</dependencies>
    

Java Add Footers in PowerPoint Documents

Using Spire.Presentation, you can easily add consistent footer content to the bottom of each page in a PowerPoint document. By adding footer placeholders, page number placeholders, and time placeholders, you can ensure that the footer content on each page remains consistent. Here are the detailed steps:

  • Create a lisentation object.
  • Load a PowerPoint document using the lisentation.loadFromFile() method.
  • Set the footer visible using lisentation.setFooterVisible(true) and set the footer text.
  • Set the slide number visible using lisentation.setSlideNumberVisible(true), iterate through each slide, check for the lisence of a page number placeholder, and modify the text to the "Page X" format if found.
  • Set the date and time visible using lisentation.setDateTimeVisible(true).
  • Set the format of the date using the lisentation.setDateTime() method.
  • Save the document to a specified path using the lisentation.saveToFile() method.
  • Java
using Spire.Presentation;

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

            // Load the presentation from a file
            presentation.LoadFromFile("Sample1.pptx");

            // Set the footer visible
            presentation.FooterVisible = true;

            // Set the footer text to "Spire.Presentation"
            presentation.SetFooterText("Spire.Presentation");

            // Set slide number visible
            presentation.SlideNumberVisible = true;

            // Iterate through each slide in the presentation
            foreach (ISlide slide in presentation.Slides)
            {
                foreach (IShape shape in slide.Shapes)
                {
                    if (shape.Placeholder != null)
                    {
                        // If it is a slide number placeholder
                        if (shape.Placeholder.Type.Equals(PlaceholderType.SlideNumber))
                        {
                            TextParagraph textParagraph = (shape as IAutoShape).TextFrame.TextRange.Paragraph;
                            String text = textParagraph.Text;

                            // Modify the slide number text to "Slide X"
                            textParagraph.Text = "Slide " + text;
                        }
                    }
                }
            }

            // Set date time visible
            presentation.DateTimeVisible = true;

            // Set date time format
            presentation.SetDateTime(DateTime.Now, "MM/dd/yyyy");

            // Save the modified presentation to a file
            presentation.SaveToFile("AddFooter.pptx", FileFormat.Pptx2016);

            // Dispose of the Presentation object resources
            presentation.Dispose();
        }
    }
}

Java: Add, Modify, or Remove Footers in PowerPoint Documents

Java Modify Footers in PowerPoint Documents

To modify the footer in a PowerPoint document, you need to inspect each shape on every slide to identify footer placeholders, page number placeholders, and so on. By recognizing these placeholders, you can set specific content and formats for each type. Here are the detailed steps:

  • Create a Presentation object.
  • Load a PowerPoint document using the Presentation.loadFromFile() method.
  • Retrieve a slide using the Presentation.getSlides().get(index) method.
  • Iterate through the shapes on the slide using a for loop, inspect each shape to determine if it is a placeholder for the footer, page number, etc., and then modify its content or format accordingly.
  • Save the document to a specified path using the Presentation.saveToFile() method.
  • Java
import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;
import java.awt.*;

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

        // Load a presentation from a file
        presentation.loadFromFile("Sample2.pptx");

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

        // Iterate through shapes on the slide
        for (int i = 0; i < slide.getShapes().getCount(); i++) {
            // Check if the shape is a placeholder
            if (slide.getShapes().get(i).getPlaceholder() != null) {
                // Get the placeholder type
                PlaceholderType type = slide.getShapes().get(i).getPlaceholder().getType();

                // If it's a footer placeholder
                if (type == PlaceholderType.FOOTER) {
                    // Convert the shape to IAutoShape type
                    IAutoShape autoShape = (IAutoShape) slide.getShapes().get(i);

                    // Set the text content to "E-ICEBLUE"
                    autoShape.getTextFrame().setText("E-ICEBLUE");

                    // Modify the font of the text
                    ChangeFont(autoShape.getTextFrame().getParagraphs().get(0));
                }
                // If it's a slide number placeholder
                if (type == PlaceholderType.SLIDE_NUMBER) {
                    // Convert the shape to IAutoShape type
                    IAutoShape autoShape = (IAutoShape) slide.getShapes().get(i);

                    // Modify the font of the text
                    ChangeFont(autoShape.getTextFrame().getParagraphs().get(0));
                }
            }
        }

        // Save the modified presentation to a file
        presentation.saveToFile("ModifiedFooter.pptx", FileFormat.PPTX_2016);

        // Dispose of the Presentation object resources
        presentation.dispose();
    }
    static void ChangeFont(ParagraphEx paragraph)
    {
        // Iterate through each text range in the paragraph
        for (int i = 0; i < paragraph.getTextRanges().getCount(); i++) {
            // Set the text style to italic
            paragraph.getTextRanges().get(i).isItalic(TriState.TRUE);

            // Set the text font
            paragraph.getTextRanges().get(i).setEastAsianFont (new TextFont("Times New Roman"));

            // Set the text font size to 34
            paragraph.getTextRanges().get(i).setFontHeight(34);

            // Set the text color
            paragraph.getTextRanges().get(i).getFill().setFillType(FillFormatType.SOLID);
            paragraph.getTextRanges().get(i).getFill().getSolidColor().setColor(Color.BLUE);
        }
    }
}

Java: Add, Modify, or Remove Footers in PowerPoint Documents

Java Remove Footers in PowerPoint Documents

To delete the footer in a PowerPoint document, you first need to retrieve content such as footer placeholders, page number placeholders, time placeholders, etc., within the slides. Once these placeholders are identified, you can locate and remove them from the collection of shapes on the slide. Here are the detailed steps:

  • Create a Presentation object.
  • Load a PowerPoint document using the Presentation.loadFromFile() method.
  • Retrieve a slide using the Presentation.getSlides().get(index) method.
  • Iterate through the shapes on the slide using a for loop, check if they are placeholders, and if they are footer placeholders, page number placeholders, time placeholders, remove them from the slide.
  • Save the document to a specified path using the Presentation.saveToFile() method.
  • Java
import com.spire.presentation.*;
public class RemoveFooter {
    public static void main(String[] args) throws Exception {
        // Create a Presentation object
        Presentation presentation = new Presentation();
        // Load the presentation from a file
        presentation.loadFromFile("Sample2.pptx");
        // Get the first slide
        ISlide slide = presentation.getSlides().get(0);
        // Iterate through the shapes on the slide
        for (int i = slide.getShapes().getCount() - 1; i >= 0; i--) {
            // Check if the shape is a placeholder
            if (slide.getShapes().get(i).getPlaceholder() != null) {
                // Get the placeholder type
                PlaceholderType type = slide.getShapes().get(i).getPlaceholder().getType();
                // If it's a footer placeholder
                if (type == PlaceholderType.FOOTER) {
                    // Remove it from the slide
                    slide.getShapes().removeAt(i);
                }
                // If it's a slide number placeholder
                if (type == PlaceholderType.SLIDE_NUMBER) {
                    // Remove it from the slide
                    slide.getShapes().removeAt(i);
                }
                // If it's a date and time placeholder
                if (type == PlaceholderType.DATE_AND_TIME) {
                    // Remove it from the slide
                    slide.getShapes().removeAt(i);
                }
            }
        }
        // Save the modified presentation to a file
        presentation.saveToFile("RemovedFooter.pptx", FileFormat.PPTX_2016);
        // Dispose of the Presentation object resources
        presentation.dispose();
    }
}

Java: Add, Modify, or Remove Footers in PowerPoint Documents

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.

With Spire.Doc for .NET, we can easily insert new text to word document at exact position, it also supports to insert new text after the certain text strings at many places. This article will show you how to insert new text strings after the searched text string in word document.

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace Word
{
    class Program
    {
        static void Main(string[] args)
        {
            //load the sample document
            Document doc = new Document();
            doc.LoadFromFile("Sample.docx", FileFormat.Docx2010);

            //find all the text string “New Zealand” from the sample document
            TextSelection[] selections = doc.FindAllString("New Zealand", true, true);
            int index = 0;

            //defines text range
            TextRange range = new TextRange(doc);


            //insert new text string (NY) after the searched text string
            foreach (TextSelection selection in selections)
            {
                range = selection.GetAsOneRange();
                TextRange newrange = new TextRange(doc);
                newrange.Text = ("(NY)");
                index = range.OwnerParagraph.ChildObjects.IndexOf(range);
                range.OwnerParagraph.ChildObjects.Insert(index + 1, newrange);

            }

            //find and highlight the newly added text string NY
            TextSelection[] text2 = doc.FindAllString("NY", false, true);
            foreach (TextSelection seletion in text2)
            {
                seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
            }

            //save the document 
            doc.SaveToFile("Result.docx", FileFormat.Docx2010);
        }
    }
}

Effective screenshot after adding the text strings to the searched text:

C# add new text strings after the searched text string in word document

A combination chart is a chart that combines at least two chart types in a single chart. This article introduces how to combine clustered column and line chart in PowerPoint using Spire.Presentation for Java.

import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;
import com.spire.presentation.charts.ChartType;
import com.spire.presentation.charts.IChart;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.geom.Rectangle2D;

public class CombinationChart {

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

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

        //insert a column clustered chart
        Rectangle2D.Double rect = new   Rectangle2D.Double(50, 100, 550, 300);
        IChart chart = presentation.getSlides().get(0).getShapes().appendChart(ChartType.COLUMN_CLUSTERED, rect);

        //set chart title
        chart.getChartTitle().getTextProperties().setText("Sales vs. Unit Price");
        chart.getChartTitle().getTextProperties().isCentered(true);
        chart.getChartTitle().setHeight(30);
        chart.hasTitle(true);

        //write data to chart as chart data
        chart.getChartData().get(0,0).setText("Month");
        chart.getChartData().get(0,1).setText("Unit Price");
        chart.getChartData().get(0,2).setText("Sales");
        chart.getChartData().get(1,0).setText("January");
        chart.getChartData().get(1,1).setNumberValue(120);
        chart.getChartData().get(1,2).setNumberValue(5600);
        chart.getChartData().get(2,0).setText("February");
        chart.getChartData().get(2,1).setNumberValue(100);
        chart.getChartData().get(2,2).setNumberValue(7300);
        chart.getChartData().get(3,0).setText("March");
        chart.getChartData().get(3,1).setNumberValue(80);
        chart.getChartData().get(3,2).setNumberValue(10200);
        chart.getChartData().get(4,0).setText("April");
        chart.getChartData().get(4,1).setNumberValue(120);
        chart.getChartData().get(4,2).setNumberValue(5900);
        chart.getChartData().get(5,0).setText("May");
        chart.getChartData().get(5,1).setNumberValue(90);
        chart.getChartData().get(5,2).setNumberValue(9500);
        chart.getChartData().get(6,0).setText("June");
        chart.getChartData().get(6,1).setNumberValue(110);
        chart.getChartData().get(6,2).setNumberValue(7200);

        //set series labels
        chart.getSeries().setSeriesLabel(chart.getChartData().get("B1", "C1"));

        //set categories labels
        chart.getCategories().setCategoryLabels(chart.getChartData().get("A2", "A7"));

        //assign data to series values
        chart.getSeries().get(0).setValues(chart.getChartData().get("B2", "B7"));
        chart.getSeries().get(1).setValues(chart.getChartData().get("C2", "C7"));

        //change the chart type of series 2 to line with markers
        chart.getSeries().get(1).setType(ChartType.LINE_MARKERS);

        //plot data of series 2 on the secondary axis
        chart.getSeries().get(1).setUseSecondAxis(true);

        //hide grid links of secondary axis
        chart.getSecondaryValueAxis().getMajorGridTextLines().setFillType(FillFormatType.NONE);

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

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

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

Create a Combination Chart in PowerPoint in Java

This article demonstrates how to replace an existing image with a new image in a PDF file using Spire.PDF for Java.

Below is the screenshot of the input PDF file we used for demonstration:

Replace image with new image in PDF in Java

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;

import java.io.IOException;

public class ReplaceImage {
    public static void main(String[] args) throws IOException {
        //Load the PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("Input.pdf");

        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);

        //Load an image
        PdfImage image = PdfImage.fromFile("Image.png");

        //Replace the first image in the first page with the loaded image
        page.replaceImage(0, image);

        //Save the file
        pdf.saveToFile("ReplaceImage.pdf");
    }
}

Output:

Replace image with new image in PDF in Java

Monday, 26 September 2022 07:03

Java: Convert PowerPoint to XPS

XPS (XML Paper Specification) is a fixed-format document described by an XML-based language. It maintains a consistent appearance for documents, which is an ideal file format for publishing, archiving and transmitting. This article will demonstrate how to programmatically convert PowerPoint to XPS using Spire.Presentation for Java.

Install Spire.Presentation for Java

First of all, you're required to add the Spire.Presentation.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.presentation</artifactId>
        <version>9.4.5</version>
    </dependency>
</dependencies>
    

Convert PowerPoint to XPS

The detailed steps are as follows:

  • Create a Presentation instance.
  • Load a sample PowerPoint document using Presentation.loadFromFile() method.
  • Save the PowerPoint document to XPS using Presentation.saveToFile(java.lang.String file, FileFormat fileFormat) method.
  • Java
import com.spire.presentation.*;

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

        //Create a Presentation instance
        Presentation ppt = new Presentation();

        //Load a sample PowerPoint file
        ppt.loadFromFile("E:\\Files\\test.pptx");

        //Save to XPS file
        ppt.saveToFile("toXPS.xps", FileFormat.XPS);
        ppt.dispose();
    }
}

Java: Convert PowerPoint to XPS

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.

Tuesday, 26 March 2019 07:12

Get PDF Page Labels in C#

Page labels are used to identify each page visually on the screen or in print. This article demonstrates how to get the PDF page labels using Spire.PDF.

Below is the screenshot of the sample PDF document:

Get PDF Page Labels in C#

Detail steps:

Step 1: Create a PdfDocument instance and load the sample.pdf file.

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("sample.pdf");

Step 2: Get the labels of the pages in the PDF file.

StringBuilder sb = new StringBuilder();
for (int i = 0; i < pdf.Pages.Count; i++)
{
    sb.AppendLine(pdf.Pages[i].PageLabel);
}

Step 3: Save to a .txt file.

File.WriteAllText("PageLabels.txt", sb.ToString());

Output:

Get PDF Page Labels in C#

Full code:

using System.IO;
using System.Text;
using Spire.Pdf;

namespace Get_PDF_Page_Labels
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();
            //Load the PDF file
            pdf.LoadFromFile("sample.pdf");

            //Create a StringBuilder instance
            StringBuilder sb = new StringBuilder();
            //Get the lables of the pages in the PDF file
            for (int i = 0; i < pdf.Pages.Count; i++)
            {
                sb.AppendLine(pdf.Pages[i].PageLabel);
            }

            //Save to a .txt file
            File.WriteAllText("PageLabels.txt", sb.ToString());
        }
    }
}
Tuesday, 26 March 2019 04:04

Align Text in PowerPoint Table in Java

This article demonstrates how to align text within a table cell in PowerPoint using Spire.Presenatation for Java.

Code Snippets

import com.spire.presentation.*;

public class AlignTextInTableCell {

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

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

        //add a table
        Double[] widths = new Double[]{100d, 200d, 100d, 100d};
        Double[] heights = new Double[]{30d, 70d, 70d};
        ITable table = presentation.getSlides().get(0).getShapes().appendTable(30,80, widths, heights);
        table.setStylePreset(TableStylePreset.NONE);

        //set the horizontal alignment for the cells in the first row
        table.get(0, 0).getTextFrame().setText("Left");
        table.get(0, 0).getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.LEFT);
        table.get(1, 0).getTextFrame().setText("Horizontal Center");
        table.get(1, 0).getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.CENTER);
        table.get(2, 0).getTextFrame().setText("Right");
        table.get(2, 0).getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.RIGHT);
        table.get(3, 0).getTextFrame().setText("Justify");
        table.get(3, 0).getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.JUSTIFY);

        //Set the vertical alignment for the cells in the second row
        table.get(0, 1).getTextFrame().setText("Top");
        table.get(0, 1).setTextAnchorType(TextAnchorType.TOP);
        table.get(1, 1).getTextFrame().setText("Vertical Center");
        table.get(1, 1).setTextAnchorType(TextAnchorType.CENTER);
        table.get(2, 1).getTextFrame().setText("Bottom");
        table.get(2, 1).setTextAnchorType(TextAnchorType.BOTTOM);

        //set the both horizontal and vertical alignment for the cells in the third row
        table.get(0, 2).getTextFrame().setText("Top Left");
        table.get(0, 2).getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.LEFT);
        table.get(0, 2).setTextAnchorType(TextAnchorType.TOP);
        table.get(1, 2).getTextFrame().setText("Center");
        table.get(1, 2).getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.CENTER);
        table.get(1, 2).setTextAnchorType(TextAnchorType.CENTER);
        table.get(2, 2).getTextFrame().setText("Bottom Right");
        table.get(2, 2).getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.RIGHT);
        table.get(2, 2).setTextAnchorType(TextAnchorType.BOTTOM);

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

Output

Align Text in PowerPoint Table in Java