Friday, 26 April 2019 08:26

Create Word Document in Java

This article demonstrates how to create Word document, add paragraphs and set paragraph styles in Java using Spire.Doc for Java.

import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;

import java.awt.*;

public class CreateWordDocument {
    public static void main(String[] args){
        //Create a Document instance
        Document document = new Document();

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

       //Add 3 paragraphs to the section
        Paragraph para1 = section.addParagraph();
        para1.appendText("Spire.Doc for Java");

        Paragraph para2 = section.addParagraph();
        para2.appendText("Spire.Doc for Java is a professional Java Word API that enables Java applications " +
                "to create, convert, manipulate and print Word documents without using Microsoft Office.");

        Paragraph para3 = section.addParagraph();
        para3.appendText("A plenty of Word document processing tasks can be performed by Spire.Doc for Java, " +
                "such as create, read, edit, convert and print Word documents, insert image, add header and footer, " +
                "create table, add form field and mail merge field, add bookmark and watermark, add hyperlink, " +
                "set background color/image, add footnote and endnote, encrypt Word documents.");

        //Set title style for paragraph 1
        ParagraphStyle style1 = new ParagraphStyle(document);
        style1.setName("titleStyle");
        style1.getCharacterFormat().setBold(true);
        style1.getCharacterFormat().setTextColor(Color.BLUE);
        style1.getCharacterFormat().setFontName("Arial");
        style1.getCharacterFormat().setFontSize(12f);
        document.getStyles().add(style1);
        para1.applyStyle("titleStyle");

        //Set style for paragraph 2 and 3
        ParagraphStyle style2 = new ParagraphStyle(document);
        style2.setName("paraStyle");
        style2.getCharacterFormat().setFontName("Arial");
        style2.getCharacterFormat().setFontSize(11f);
        document.getStyles().add(style2);
        para2.applyStyle("paraStyle");
        para3.applyStyle("paraStyle");

        //Horizontally align paragraph 1 to center
        para1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);

        //Set first-line indent for paragraph 2 and 3
        para2.getFormat().setFirstLineIndent(25f);
        para3.getFormat().setFirstLineIndent(25f);

        //Set spaces after paragraph 1 and 2
        para1.getFormat().setAfterSpacing(15f);
        para2.getFormat().setAfterSpacing(10f);

        //Save the document
        document.saveToFile("Output.docx", FileFormat.Docx);
    }
}

Output:

Create Word Document in Java

When you create a Word document with Spire. Doc for Java, you can format an entire paragraph by applying a ParagraphStyle, you can also format individual words or phrases by applying a CharacterFormat. This article introduces how to apply formatting to characters in Word.

Code Snippets

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class SetCharacterFormat {

    public static void main(String[] args) {

        //create a Word document
        Document document = new Document();
        Section sec = document.addSection();

        //add a paragraph
        Paragraph paragraph = sec.addParagraph();
        paragraph.appendText("Here is a paragraph with various character styles. This is ");

        //append text to the paragraph and return a TextRange object
        TextRange tr = paragraph.appendText("text with strikeout");

        //set the character format to strikeout via TextRange object
        tr.getCharacterFormat().isStrikeout(true);

        //apply shadow effect to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text with shadow");
        tr.getCharacterFormat().isShadow(true);

        //apply a large font size to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text in a large font size");
        tr.getCharacterFormat().setFontSize(20);

        //apply color to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text in red");
        tr.getCharacterFormat().setTextColor(Color.red);

        //apply bold & italic to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text in bold & italic");
        tr.getCharacterFormat().setBold(true);
        tr.getCharacterFormat().setItalic(true);

        //apply underline to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("underlined text");
        tr.getCharacterFormat().setUnderlineStyle(UnderlineStyle.Single);

        //apply background color to text
        paragraph.appendText(". This is ");
        tr = paragraph.appendText("text with background color");
        tr.getCharacterFormat().setTextBackgroundColor(Color.GREEN);

        //apply superscript to text
        paragraph.appendText(". This is a math formula: a");
        tr = paragraph.appendText("2");
        tr.getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
        paragraph.appendText(" + b");
        tr = paragraph.appendText("2");
        tr.getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
        paragraph.appendText(" = c");
        tr = paragraph.appendText("2");
        tr.getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
        paragraph.appendText(".");

        //save to file
        document.saveToFile("SetCharacterFormat.docx", FileFormat.Docx);
    }
}

Output

Apply Formatting to Characters in Word in Java

This section will demonstrate how to use Spire.Doc for Java to add text watermark and image watermark to Word document in Java applications.

Add text watermark

import com.spire.doc.*;
import com.spire.doc.documents.WatermarkLayout;
import java.awt.*;

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

        Document document = new Document();
        document.loadFromFile("Sample.docx");

        insertTextWatermark(document.getSections().get(0));

        document.saveToFile("out/result.docx",FileFormat.Docx );
    }
    private static void insertTextWatermark(Section section) {
        TextWatermark txtWatermark = new TextWatermark();
        txtWatermark.setText("Confidential");
        txtWatermark.setFontSize(40);
        txtWatermark.setColor(Color.red);
        txtWatermark.setLayout(WatermarkLayout.Diagonal);
        section.getDocument().setWatermark(txtWatermark);
    }

}

Effective screenshot of text watermark on word:

Java add text watermark and image watermark to word document

Add image watermark

import com.spire.doc.*;


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

        Document document = new Document();
        document.loadFromFile("Sample.docx");

         PictureWatermark picture = new PictureWatermark();
         picture.setPicture("logo.png");
         picture.setScaling(5);
         picture.isWashout(false);
         document.setWatermark(picture);

         document.saveToFile("out/result2.docx",FileFormat.Docx );
    }
}

Effective screenshot of image watermark on word:

Java add text watermark and image watermark to word document

With the help of Spire.Presentation, developers can easily add and get speaker notes on presentation slides. From v 4.4.3, Spire.Presentation supports to retain the notes when converting presentation slides to SVG. This article will show you how to keep the notes when saving presentation slides to SVG in C#.

using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.IO;
using System.Collections.Generic;

namespace PPT
{
    class Program
    {
        static void Main(string[] args)
        {
            //load the sample document with speaker notes
            Presentation ppt = new Presentation();
            ppt.LoadFromFile("Sample.pptx");

            //retain the notes when converting ppt to svg
            ppt.IsNoteRetained = true;


            //convert presentation slides to SVG
            Queue<byte[]> bytes = ppt.SaveToSVG();

            int length = bytes.Count;
            for (int i = 0; i < length; i++)
            {
                FileStream filestream = new FileStream(string.Format(@"output_{0}.svg", i), FileMode.Create);
                byte[] outputBytes = bytes.Dequeue();
                filestream.Write(outputBytes, 0, outputBytes.Length);
            }
            ppt.Dispose();
            ppt.SaveToSVG();
                                                       
        }
    }
}

Effective screenshot of retaining the speaker notes when converting presentation slides to SVG:

C# retain notes when converting presentation slides to SVG

Monday, 15 April 2019 09:41

Spire.Doc Program Guide Content for Java

Spire.Doc for Java is a professional Java Word API that enables Java applications to create, convert, manipulate and print Word documents without using Microsoft Office.

A plenty of Word document processing tasks can be performed by Spire.Doc for Java, such as create, read, edit, convert and print Word documents, insert image, add header and footer, create table, add form field and mail merge field, add bookmark and watermark, add hyperlink, set background color/image, add footnote and endnote, encrypt Word documents.

Monday, 15 April 2019 09:36

Insert Hyperlinks in Word in Java

This article demonstrates how to add a text hyperlink, an image hyperlink, an email link and a file link to a Word document using Spire.Doc for Java.

Code Snippets

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.HorizontalAlignment;
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();
        Section section = doc.addSection();

        //insert web link
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("Web Link: ");
        paragraph.appendHyperlink("https://www.e-iceblue.com/","Home Page", HyperlinkType.Web_Link);

        //insert email link
        paragraph = section.addParagraph();
        paragraph.appendText("Email Link: ");
        paragraph.appendHyperlink("mailto:support@e-iceblue.com","support@e-iceblue.com", HyperlinkType.E_Mail_Link);

        //insert file link
        paragraph = section.addParagraph();
        paragraph.appendText("File Link: ");
        paragraph.appendHyperlink("C:\\Users\\Administrator\\Desktop\\Report.pdf","Click to open Report.pdf", HyperlinkType.File_Link);

        //insert image hyperlink
        paragraph = section.addParagraph();
        paragraph.appendText("Image Hyper Link: ");
        paragraph = section.addParagraph();
        DocPicture picture = paragraph.appendPicture("C:\\Users\\Administrator\\Desktop\\logo-2.png");
        paragraph.appendHyperlink("https://www.e-iceblue.com/",picture, HyperlinkType.Web_Link);

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

            //align paragraph to center
            section.getParagraphs().get(i).getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            //add auto spacing after paragraph
            section.getParagraphs().get(i).getFormat().setAfterAutoSpacing(true);
        }

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

Output

Insert Hyperlinks in Word in Java

Monday, 15 April 2019 08:36

Rotate a PDF page in Java

This article demonstrates how to rotate a PDF page using Spire.PDF for Java.

Below is the screenshot of the input.pdf file:

Rotate a PDF page in Java

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageRotateAngle;

import java.io.IOException;

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

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

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

        //Rotate the PDF page 90 degrees clockwise based on the original rotation angle
        rotateAngle += PdfPageRotateAngle.Rotate_Angle_90.getValue();
        page.setRotation((PdfPageRotateAngle.fromValue(rotateAngle)));

        //Save the PDF document
        pdf.saveToFile("Rotated.pdf");
    }
}

Output:

Rotate a PDF page in Java

This article demonstrates how to add, replace and delete comments in a PowerPoint document using Spire.Presentation for Java.

Add Comments:

import com.spire.presentation.*;
import java.awt.geom.Point2D;


public class PPTComment {
    public static void main(String[] args) throws Exception{
        //load the sample PowerPoint file
        Presentation ppt = new Presentation();
        ppt.loadFromFile("Sample.pptx");

        ICommentAuthor author = ppt.getCommentAuthors().addAuthor("E-iceblue", "comment:");

        //Add comment
        ppt.getSlides().get(0).addComment(author, "The first comment", new Point2D.Float(48, 9), new java.util.Date());

        ppt.getSlides().get(0).addComment(author, "The second added comment", new Point2D.Float(24, 20), new java.util.Date());

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

Add, Replace and Delete Comment in PowerPoint in Java

Replace and delete the comment:

public class PPTComment2{
    public static void main(String[] args) throws Exception{
        //load the sample PowerPoint file
        Presentation ppt = new Presentation();
        ppt.loadFromFile("output/result.pptx");

        //Replace comment
        ppt.getSlides().get(0).getComments()[0].setText("Replace comment");
        //Delete comment
        ppt.getSlides().get(1).deleteComment(ppt.getSlides().get(0).getComments()[1]);

        //Save the document
        ppt.saveToFile("output/result2.pptx", FileFormat.PPTX_2010);
        ppt.dispose();
    }
}

Add, Replace and Delete Comment in PowerPoint in Java

This article demonstrates how to add footer to PowerPoint document in Java application using Spire.Presentation for Java.

import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;

public class AddFooter {
    public static void main(String[] args) throws Exception {
        //Load a PPT document
        Presentation presentation = new Presentation();
        presentation.loadFromFile("Input.pptx");

        //Add footer
        presentation.setFooterText("Demo of Spire.Presentation");
        //Set the footer visible
        presentation.setFooterVisible(true);
        //Set the page number visible
        presentation.setSlideNumberVisible(true);
        //Set the date visible
        presentation.setDateTimeVisible(true);
        
        //Save the document
        presentation.saveToFile("AddFooter.pptx", FileFormat.PPTX_2010);
    }
}

Output:

Add-Footer-to-PowerPoint-Document-in-Java

Some long text, such as a phrase or a sentence, is likely to span two or more lines. When we try to highlight it, it’s required to be able to detect the whole phrase or sentence even if it spans two lines. This article is going to introduce how to find and highlight long text spanning multiple lines by using Spire.PDF with C# and VB.NET.

Code Snippets

[C#]
//load the sample PDF file
PdfDocument doc = new PdfDocument(@"C:\Users\Administrator\Desktop\Hello.pdf");

//find all matching strings from the first page, even if some of them span multiple lines
PdfTextFind[] findResults = doc.Pages[0].FindText("Besides, Spire.PDF for JAVA can be applied easily to convert PDF to XPS, XPS to PDF, PDF to SVG, and PDF to PDF/A in high quality.", TextFindParameter.CrossLine).Finds;

//highlight the first search result
findResults[0].ApplyHighLight(Color.Yellow);

//save to file
doc.SaveToFile("output.pdf", FileFormat.PDF);
[VB.NET]
'load the sample PDF file
Dim doc As PdfDocument =  New PdfDocument("C:\Users\Administrator\Desktop\Hello.pdf") 
 
'find all matching strings from the first page, even if some of them span multiple lines
Dim findResults() As PdfTextFind =  doc.Pages(0).FindText("Besides, Spire.PDF for JAVA can be applied easily to convert PDF to XPS, XPS to PDF, PDF to SVG, and PDF to PDF/A in high quality.",TextFindParameter.CrossLine).Finds 
 
'highlight the first search result
findResults(0).ApplyHighLight(Color.Yellow)
 
'save to file
doc.SaveToFile("output.pdf", FileFormat.PDF)

Output

Find and Highlight Text Spanning Multiple Lines in PDF in C#, VB.NET

Page 9 of 113