This article demonstrates how to insert images to table cells in a Word document using Spire.Doc for Java.

import com.spire.doc.AutoFitBehaviorType;
import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.Table;
import com.spire.doc.fields.DocPicture;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class InsertImageToTableCell {

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

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

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

        //Add a table
        Table table = section.addTable(true);
        table.resetCells(2,2);
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

        //Load an image to InputStream
        InputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\company-logo.png");
        
        //Insert the image to the cell(0,0)
        DocPicture picture = table.get(0,0).addParagraph().appendPicture(inputStream);
        
        //Set the width and height of the image
        picture.setWidth(100);
        picture.setHeight(100);

        //Insert another image to the cell(1,1)
        inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\intro.png");
        picture = table.get(1,1).addParagraph().appendPicture(inputStream);
        picture.setWidth(100);
        picture.setHeight(100);

        //Save the document
        document.saveToFile("InsertImgToCell.docx");
    }
}

Insert Images to a Table in Word in Java

Thursday, 09 July 2020 03:58

Convert PDF to Excel in C#, VB.NET

This article demonstrates how to convert a PDF file to Excel file format in C# and VB.NET by using Spire.PDF for .NET.

Below is the screenshot of the input PDF file:

Convert PDF to Excel in C#, VB.NET

Code Snippets:

C#
using Spire.Pdf;

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

            //Save to Excel
            pdf.SaveToFile("PDFToExcel.xlsx", FileFormat.XLSX);
        }
    }
}
VB.NET
Imports Spire.Pdf

Namespace ConvertPDFToExcel
    Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a PdfDocument instance
            Dim pdf As PdfDocument = New PdfDocument()
            'Load the PDF file
pdf.LoadFromFile("Shopping list.pdf")
'Save to Excel	
            pdf.SaveToFile("PDFToExcel.xlsx", FileFormat.XLSX)
        End Sub
    End Class
End Namespace

Output:

Convert PDF to Excel in C#, VB.NET

Thursday, 02 July 2020 08:54

Create a Nested Table in Word in Java

This article demonstrates how to insert a nested table in a table cell using Spire.Doc for Java.

import com.spire.doc.*;

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

        //Create a Document object
        Document doc = new Document();
        
        //Add a section
        Section section = doc.addSection();

        //Add a table
        Table table = section.addTable(true);
        table.resetCells(2, 3);

        //Set column width
        table.getRows().get(0).getCells().get(0).setWidth(50f);
        table.getRows().get(0).getCells().get(2).setWidth(50f);
        table.getRows().get(1).getCells().get(0).setWidth(50f);
        table.getRows().get(1).getCells().get(2).setWidth(50f);
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window);

        //Insert content to cells
        table.get(0,0).addParagraph().appendText("SI.No.");
        String text = "Earthwork excavation for foundation of buildings, water supply, "
                + "sanitary lines and electrical conduits either in pits or in "
                + "trenches 1.5m and above in width, in ordinary soil not exceeding "
                + "1.5m in depth including dressing the bottom and sides of pits and  "
                + "trenches, stacking the excavated soil clear.";
        table.get(0,1).addParagraph().appendText(text);
        table.get(0,2).addParagraph().appendText("Qty");

        //Add a nested table to cell(0,1)
        Table nestedTable = table.get(0,1).addTable();
        nestedTable.resetCells(3, 4);
        nestedTable.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

        //Add content to the cells of nested table
        nestedTable.get(0,0).addParagraph().appendText("SI.No.");
        nestedTable.get(0,1).addParagraph().appendText("Item");
        nestedTable.get(0,2).addParagraph().appendText("Qty");
        nestedTable.get(0,3).addParagraph().appendText("Rate");
        nestedTable.get(1,0).addParagraph().appendText("1");
        nestedTable.get(1,1).addParagraph().appendText("Sand");
        nestedTable.get(1,2).addParagraph().appendText("30");
        nestedTable.get(1,3).addParagraph().appendText("45");
        nestedTable.get(2,0).addParagraph().appendText("2");
        nestedTable.get(2,1).addParagraph().appendText("Cement");
        nestedTable.get(2,2).addParagraph().appendText("30");
        nestedTable.get(2,3).addParagraph().appendText("50");

        //Save the document
        doc.saveToFile("NestedTable.docx", FileFormat.Docx_2013);
    }
}

Create a Nested Table in Word in Java

This article will demonstrate how to add page break and remove page break for Excel worksheets on Java applications.

Add page break on Excel worksheet:

import com.spire.xls.*;

public class ExcelPageBreak {
    public static void main(String[] args) {
        //Create a Workbook and load the sample file 
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx");

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

        //Set Excel Page Break Horizontally
        sheet.getHPageBreaks().add(sheet.getRange().get("A8"));
        sheet.getHPageBreaks().add(sheet.getRange().get("A14"));

        //Set Excel Page Break Vertically
        sheet.getVPageBreaks().add(sheet.getRange().get("B1"));
        sheet.getVPageBreaks().add(sheet.getRange().get("C1"));

        //Set view mode to Preview mode
        workbook.getWorksheets().get(0).setViewMode(ViewMode.Preview);

        //Save the document
        String output = "output/AddPageBreak.xlsx";
        workbook.saveToFile(output, ExcelVersion.Version2013);
    }
}

Effective screenshot after set Excel page break horizontally and vertically:

Java set or remove page break on Excel worksheet

Remove the page break:

import com.spire.xls.*;

public class ExcelPageBreak {
    public static void main(String[] args) {
        //Create a Workbook and load the sample file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("output/AddPageBreak.xlsx");

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

        //Clear all the vertical page breaks
        sheet.getVPageBreaks().clear();

        //Remove the first horizontal Page Break
        sheet.getHPageBreaks().removeAt(0);

        //Set the ViewMode as Preview mode
        sheet.setViewMode(ViewMode.Preview);

        //Save the document
        String output = "output/removePageBreak.xlsx";
        workbook.saveToFile(output, ExcelVersion.Version2013);
      }
}

Effective screenshot after remove the vertical page breaks and horizontal page break:

Java set or remove page break on Excel worksheet

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

Page 1 of 123