Java: Add Hyperlinks to Word Documents

2022-08-05 09:36:00 Written by Koohji

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>14.4.0</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.

Java: Rotate Pages in PDF

2022-06-16 08:36:00 Written by Koohji

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>12.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>11.3.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.

page 70