This article demonstrates how to add, count, retrieve and remove variables in a Word document in Java using Spire.Doc for Java library.

Add a Variable

The following example adds a document variable named "A1" with a value of 12 to a Word document.

import com.spire.doc.Document;
import com.spire.doc.FieldType;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;

public class AddVariables {
    public static void main(String[] args){
        //Create a Document instance
        Document document = new Document();
        //Add a section
        Section section = document.addSection();

        //Add a paragraph to the section
        Paragraph paragraph = section.addParagraph();

        //Add a DocVariable field to the paragraph
        paragraph.appendField("A1", FieldType.Field_Doc_Variable);

        //Add a document variable to the DocVariable field
        document.getVariables().add("A1", "12");

        //Update fields in the document
        document.isUpdateFields(true);
        
        //Save the result document
        document.saveToFile("AddVariables.docx", FileFormat.Docx_2013);
    }
}

Add, Count, Retrieve and Remove Variables in Word in Java

Count the number of Variables

import com.spire.doc.Document;

public class CountVariables {
    public static void main(String[] args){
        //Load the Word document
        Document document = new Document();
        document.loadFromFile("AddVariables.docx");

        //Get the number of variables in the document
        int number = document.getVariables().getCount();

        StringBuilder content = new StringBuilder();
        content.append("The number of variables is: " + number);

        System.out.println(content.toString());
    }
}

Add, Count, Retrieve and Remove Variables in Word in Java

Retrieve Name and Value of a Variable

import com.spire.doc.Document;

public class RetrieveVariables {
    public static void main(String[] args){
        //Load the Word document
        Document document = new Document();
        document.loadFromFile("AddVariables.docx");

        //Retrieve the name of a variable by index
        String s1 = document.getVariables().getNameByIndex(0);

        //Retrieve the value of a variable by index
        String s2 = document.getVariables().getValueByIndex(0);

        //Retrieve the value of a variable by name
        String s3 = document.getVariables().get("A1");

        System.out.println("The name of the variable retrieved by index 0 is: " + s1);
        System.out.println("The value of the variable retrieved by index 0 is: " + s2);
        System.out.println("The value of the variable retrieved by name \"A1\" is: " + s3);
    }
}

Add, Count, Retrieve and Remove Variables in Word in Java

Remove a specific Variable

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class RemoveVariables {
    public static void main(String[] args){
        //Load the Word document
        Document document = new Document();
        document.loadFromFile("AddVariables.docx");

        //Remove a variable by name
        document.getVariables().remove("A1");
        
        //Update fields in the document
        document.isUpdateFields (true);
        
        //Save the result document
        document.saveToFile("RemoveVariables.docx", FileFormat.Docx_2013);
    }
}
Thursday, 25 June 2020 08:07

Insert Multi-level Lists in Word in Java

This article demonstrates how to insert a multi-level list in a Word document using Spire.Doc for Java.

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

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

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

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

        //Create a ListStyle object
        ListStyle listStyle = new ListStyle(document, ListType.Numbered);
        listStyle.setName("CustomStyle");

        //Set the list pattern type and number prefix of each level
        listStyle.getLevels().get(0).setPatternType(ListPatternType.Arabic);
        listStyle.getLevels().get(1).setNumberPrefix("\u0000.");
        listStyle.getLevels().get(1).setPatternType(ListPatternType.Arabic);
        listStyle.getLevels().get(2).setNumberPrefix("\u0000.\u0001.");
        listStyle.getLevels().get(2).setPatternType(ListPatternType.Arabic);

        //Add the custom list style to the list styles collection
        document.getListStyles().add(listStyle);

        //Add first paragraph and apply list style to it
        //The default list level is the first level if you don't set a list level number
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("The first item");
        paragraph.applyStyle(BuiltinStyle.Heading_1);
        paragraph.getListFormat().applyStyle(listStyle.getName());

        //Add second paragraph and apply list style to it
        paragraph = section.addParagraph();
        paragraph.appendText("The second item");
        paragraph.applyStyle(BuiltinStyle.Heading_1);
        paragraph.getListFormat().applyStyle(listStyle.getName());

        //Add third paragraph, apply list style and set the list level number
        paragraph = section.addParagraph();
        paragraph.appendText("The first sub-item");
        paragraph.applyStyle(BuiltinStyle.Heading_2);
        paragraph.getListFormat().setListLevelNumber(1);
        paragraph.getListFormat().applyStyle(listStyle.getName());

        //Add third paragraph, apply list style and set the list level number
        paragraph = section.addParagraph();
        paragraph.appendText("The second sub-item");
        paragraph.applyStyle(BuiltinStyle.Heading_2);
        paragraph.getListFormat().continueListNumbering();
        paragraph.getListFormat().applyStyle(listStyle.getName());

        //Add forth paragraph, apply list style and set the list level number
        paragraph = section.addParagraph();
        paragraph.appendText("A sub-sub-item");
        paragraph.applyStyle(BuiltinStyle.Heading_5);
        paragraph.getListFormat().setListLevelNumber(2);
        paragraph.getListFormat().applyStyle(listStyle.getName());

        //Add fifth paragraph and apply list style to it
        paragraph = section.addParagraph();
        paragraph.appendText("The third item");
        paragraph.applyStyle(BuiltinStyle.Heading_1);
        paragraph.getListFormat().applyStyle(listStyle.getName());

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

Insert Multi-level Lists in Word in Java

Tuesday, 23 June 2020 08:22

Set Editing Restrictions in Word in Java

This article demonstrates how to set editing restrictions in Word document in Java using Spire.Doc for Java.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.ProtectionType;

public class RestrictEditing {
    public static void main(String[] args){
        //Create a Document instance
        Document document = new Document();
        //Load the Word document
        document.loadFromFile("Sample.docx");

        //No changes (Read only)
        document.protect(ProtectionType.Allow_Only_Reading, "123456");

        //Allow only comments
        //document.protect(ProtectionType.Allow_Only_Comments, "123456");

        //Allow only filling in forms
        //document.protect(ProtectionType.Allow_Only_Form_Fields, "123456");

        //Allow only tracked changes
        //document.protect(ProtectionType.Allow_Only_Revisions, "123456");

        //Save the result document
        document.saveToFile("RestrictEditing.docx", FileFormat.Docx_2013);
    }
}

The following screenshot shows the output Word document after setting editing restrictions as no changes (read only):

Set Editing Restrictions in Word in Java

Monday, 22 June 2020 08:13

Java draw dash and solid line to PDF

This article will show you how to draw dash and solid line in Java applications.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;

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

        //Create a new PdfDocument instance and add a new page
        PdfDocument pdf = new PdfDocument();
        PdfPageBase page = pdf.getPages().add();

        //Set location and size
        float x = 150;
        float y = 100;
        float width = 300;


        //Create pens
        PdfPen pen = new PdfPen(new PdfRGBColor(Color.red), 3f);
        PdfPen pen1 = new PdfPen(new PdfRGBColor(Color.blue), 1f);

        //Set dash style and pattern
        pen.setDashStyle(PdfDashStyle.Dash);
        pen.setDashPattern(new float[]{1, 1, 1});

        //Draw lines to the PDF page
        page.getCanvas().drawLine(pen, x, y, x + width, y);
        page.getCanvas().drawLine(pen1, x, y+50, x + width, y+50);

        //Save the document
        pdf.saveToFile("output/drawLines_out.pdf");
    }
}

Effective screenshot after adding dash and solid lines to PDF:

Java draw dash and solid line to PDF

This article demonstrates how to insert math equations i.e. Latex and MathML equations and Symbols in a Word document in Java using Spire.Doc for Java.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.Table;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.omath.OfficeMath;

public class AddMathEquationsAndSymbols {
    public static void main(String[] args){
        //Latex code
        String[] latexMathCode1 = {
                "x^{2}+\\sqrt{{x^{2}+1}}+1",
                "2\\alpha - \\sin y + x",
        };

        //MathML code
        String[] mathMLCode = {
                "<mml:math xmlns:mml=\"http://www.w3.org/1998/Math/MathML\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"><mml:msup><mml:mrow><mml:mi>x</mml:mi></mml:mrow><mml:mrow><mml:mn>2</mml:mn></mml:mrow></mml:msup><mml:mo>+</mml:mo><mml:msqrt><mml:msup><mml:mrow><mml:mi>x</mml:mi></mml:mrow><mml:mrow><mml:mn>2</mml:mn></mml:mrow></mml:msup><mml:mo>+</mml:mo><mml:mn>1</mml:mn></mml:msqrt><mml:mo>+</mml:mo><mml:mn>1</mml:mn></mml:math>",
                "<mml:math xmlns:mml=\"http://www.w3.org/1998/Math/MathML\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"><mml:mn>2</mml:mn><mml:mi>α</mml:mi><mml:mo>-</mml:mo><mml:mi>s</mml:mi><mml:mi>i</mml:mi><mml:mi>n</mml:mi><mml:mi>y</mml:mi><mml:mo>+</mml:mo><mml:mi>x</mml:mi></mml:math>",
        };

        //Latex code
        String[] latexMathCode2 = {
                "\\alpha",
                "\\beta",
        };

        //Create a Document instance
        Document doc = new Document();
        //Load the Word document
        doc.loadFromFile("MathEquationTemplate.docx");
        //Get the first section
        Section section = doc.getSections().get(0);

        Paragraph paragraph = null;
        OfficeMath officeMath;

        //Insert Latex equations
        Table table1 = section.getTables().get(0);
        for (int i = 0; i < latexMathCode1.length; i++) {
            paragraph = table1.getRows().get(i + 1).getCells().get(0).addParagraph();
            paragraph.setText(latexMathCode1[i]);
            paragraph = table1.getRows().get(i + 1).getCells().get(1).addParagraph();
            officeMath = new OfficeMath(doc);
            officeMath.fromLatexMathCode(latexMathCode1[i]);
            paragraph.getItems().add(officeMath);
        }

        //Insert MathML equations
        Table table2 = section.getTables().get(1);
        for (int i = 0; i < mathMLCode.length; i++) {
            paragraph = table2.getRows().get(i + 1).getCells().get(0).addParagraph();
            paragraph.setText(mathMLCode[i]);
            paragraph = table2.getRows().get(i + 1).getCells().get(1).addParagraph();
            officeMath = new OfficeMath(doc);
            officeMath.fromMathMLCode(mathMLCode[i]);
            paragraph.getItems().add(officeMath);
        }

        //Insert Symbols
        Table table3 = section.getTables().get(2);
        for (int i = 0; i < latexMathCode2.length; i++) {
            //Insert Latex code to the first column of the table
            paragraph = table3.getRows().get(i + 1).getCells().get(0).addParagraph();
            paragraph.setText(latexMathCode2[i]);
            //Insert symbols to the second column of the table
            paragraph = table3.getRows().get(i + 1).getCells().get(1).addParagraph();
            officeMath = new OfficeMath(doc);
            officeMath.fromLatexMathCode(latexMathCode2[i]);
            paragraph.getItems().add(officeMath);
        }

        //Save the document
        String result = "addMathEquationAndSymbols.docx";
        doc.saveToFile(result, FileFormat.Docx_2013);
    }
}

Output:

Insert Math Equations and Symbols in Word Document in Java

This article demonstrates how to apply multiple font styles in a single Excel cell using Spire.XLS for Java.

import com.spire.xls.*;

import java.awt.*;

public class ApplyMultiFontsInCell {

    public static void main(String[] args) {

        //Create a Workbook instance
        Workbook wb = new Workbook();

        //Get the first worksheet
        Worksheet sheet = wb.getWorksheets().get(0);

        //Create one Excel font
        ExcelFont font1 = wb.createFont();
        font1.setFontName("Calibri");
        font1.setColor(Color.blue);
        font1.setSize(12f);
        font1.isBold(true);

        //Create another Excel font
        ExcelFont font2 = wb.createFont();
        font2.setFontName("Times New Roman");
        font2.setColor(Color.red);
        font2.setSize(14f);
        font2.isBold(true);
        font2.isItalic(true);

        //Insert text to cell B5
        RichText richText = sheet.getCellRange("B5").getRichText();
        richText.setText("This document was created with Spire.XLS for Java.");

        //Apply two fonts to the text in the cell B5
        richText.setFont(0, 30, font1);
        richText.setFont(31, 50, font2);

        //Save the document
        wb.saveToFile("MultiFonts.xlsx", ExcelVersion.Version2016);
    }
}

Appy Multiple Fonts in One Cell in Java

Thursday, 18 June 2020 08:44

Java convert HTML to PDF

This article will show you how to convert HTML to PDF in Java applications. Ensure that you are using Spire.PDF for Java v3.6.6 or above. You could get the new plugin from the download file directly: windows-x86.zip, windows-x64.zip, macosx_x64.zip, and linux_x64.zip and then unzip it.

import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.htmlconverter.qt.HtmlConverter;
import com.spire.pdf.htmlconverter.qt.Size;

public class HtmltoPDF {
    public static void main(String[] args) {
        //define the HTML link and result PDF 
        String url = "https://www.e-iceblue.com/";
        String fileName = "Result.pdf";
        //Set the plugin path
        String pluginPath = "D:/Qt/plugins_32";
        HtmlConverter.setPluginPath(pluginPath);
        //convert HTML to PDF and set the size of the result PDF page
        HtmlConverter.convert(url, fileName, true, 1000000, new Size(600f, 900f), new PdfMargins(0));
    }
}

Please check the effective screenshot of the PDF as below:

Java convert HTML to PDF

Friday, 12 June 2020 08:44

Get Worksheet Names in Java

This article demonstrates how to get names of worksheets in a workbook using Spire.XLS for Java.

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

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

        //Create a Workbook object
        Workbook wb = new Workbook();

        //Load a sample Excel file
        wb.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.xlsx");

        //Loop through the worksheets 
        for (Object sheet: wb.getWorksheets()
             ) {

            //Get worksheet name
            String sheetName = ((Worksheet) sheet).getName();
            System.out.println(sheetName);
        }
    }
}

Get Worksheet Names in Java

This article demonstrates how to adjust the header and footer distance in a Word document using Spire.Doc for Java.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;

public class AdjustHeaderFooterDistance {
    public static void main(String[] args){
        //Create a Document instance
        Document doc = new Document();
        //Load a Word document
        doc.loadFromFile("Headers and Footers.docx");

        //Get the first section
        Section section = doc.getSections().get(0);

        //Adjust the header distance
        section.getPageSetup().setHeaderDistance(100);

        //Adjust the footer distance
        section.getPageSetup().setFooterDistance(100);

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

Screenshot

Header:

Adjust the Header and Footer Distance in Word in Java

Footer:

Adjust the Header and Footer Distance in Word in Java

This article demonstrates how to extract OLE objects from an Excel document using Spire.XLS for Java.

import com.spire.xls.*;
import com.spire.xls.core.IOleObject;

import java.io.*;

public class ExtractOLEObjects {
    public static void main(String[] args){
        //Create a Workbook instance
        Workbook workbook = new Workbook();

        //Load the Excel document
        workbook.loadFromFile("OLEObjectsExample.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Extract ole objects
        if (sheet.hasOleObjects()) {
            for (int i = 0; i < sheet.getOleObjects().size(); i++) {
                IOleObject object = sheet.getOleObjects().get(i);
                OleObjectType type = sheet.getOleObjects().get(i).getObjectType();
                switch (type) {
                    //Word document
                    case WordDocument:
                        byteArrayToFile(object.getOleData(), "output/extractOLE.docx");
                        break;
                    //PowerPoint document
                    case PowerPointSlide:
                        byteArrayToFile(object.getOleData(), "output/extractOLE.pptx");
                        break;
                    //PDF document
                    case AdobeAcrobatDocument:
                        byteArrayToFile(object.getOleData(), "output/extractOLE.pdf");
                        break;
                    //Excel document
                    case ExcelWorksheet:
                        byteArrayToFile(object.getOleData(), "output/extractOLE.xlsx");
                        break;
                }
            }
        }
    }
    public static void byteArrayToFile(byte[] datas, String destPath) {
        File dest = new File(destPath);
        try (InputStream is = new ByteArrayInputStream(datas);
             OutputStream os = new BufferedOutputStream(new FileOutputStream(dest, false));) {
            byte[] flush = new byte[1024];
            int len = -1;
            while ((len = is.read(flush)) != -1) {
                os.write(flush, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The following screenshot shows the extracted OLE documents:

Extract OLE Objects from an Excel Document in Java

Page 6 of 127