This article demonstrates how to insert superscripts and subscripts 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.BreakType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.SubSuperScript;
import com.spire.doc.fields.TextRange;

public class InsertSubSuperScript {

    public static void main(String[] args) {

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

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

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

        //Insert text
        paragraph.appendText("E = mc");

        //Insert text and set it as superscript
        TextRange textRange = paragraph.appendText("2");
        textRange.getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);

        //Add a line break
        paragraph.appendBreak(BreakType.Line_Break);

        //Insert text and set some of the characters as subscript
        paragraph.appendText("F");
        paragraph.appendText("n").getCharacterFormat().setSubSuperScript(SubSuperScript.Sub_Script);
        paragraph.appendText(" = F");
        paragraph.appendText("n-1").getCharacterFormat().setSubSuperScript(SubSuperScript.Sub_Script);
        paragraph.appendText(" + F");
        paragraph.appendText("n-2").getCharacterFormat().setSubSuperScript(SubSuperScript.Sub_Script);

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

Insert Superscripts and Subscripts in Word in Java

This article will demonstrate how to insert text and image watermark to Excel worksheet in Java applications. The watermark in Excel worksheet could only be viewed under layout view mode.

import com.spire.xls.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;

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

        //Initialize a new instance of workbook and load the test file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Sample.xlsx");

        //Set the text string and size
        Font font = new Font("Arial", Font.PLAIN, 40);
        String watermark = "Draft Version";

        for (Worksheet sheet : (Iterable) workbook.getWorksheets()) {
            //Call DrawText() method to insert the image
            BufferedImage imgWtrmrk = drawText(watermark, font, Color.pink, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());

            //Set the image as header
            sheet.getPageSetup().setLeftHeaderImage(imgWtrmrk);
            sheet.getPageSetup().setLeftHeader("&G");

            //Set the viewmode as Layout
            sheet.setViewMode(ViewMode.Layout);
        }

        //Save the document
        workbook.saveToFile("Watermark.xlsx", ExcelVersion.Version2010);
    }
    private static BufferedImage drawText (String text, Font font, Color textColor, Color backColor,double height, double width)
    {
        //define the width and height of image
        BufferedImage img = new BufferedImage((int) width, (int) height, TYPE_INT_ARGB);
        Graphics2D loGraphic = img.createGraphics();

        //set the font size
        FontMetrics loFontMetrics = loGraphic.getFontMetrics(font);
        int liStrWidth = loFontMetrics.stringWidth(text);
        int liStrHeight = loFontMetrics.getHeight();

        //set the text format
        loGraphic.setColor(backColor);
        loGraphic.fillRect(0, 0, (int) width, (int) height);
        loGraphic.translate(((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);
        loGraphic.rotate(Math.toRadians(-45));

        loGraphic.translate(-((int) width - liStrWidth) / 2, -((int) height - liStrHeight) / 2);
        loGraphic.setFont(font);
        loGraphic.setColor(textColor);
        loGraphic.drawString(text, ((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);
        loGraphic.dispose();
        return img;
    }
}

Effective screenshot of Excel text watermark:

Java insert text and image watermark to Excel worksheet

Monday, 03 August 2020 07:16

Convert Excel to TIFF in Java

This article demonstrates how to convert an Excel worksheet to TIFF and convert a particular cell range in the Excel worksheet to TIFF by using Spire.XLS for Java.

The input Excel file:

Convert Excel to TIFF in Java

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

public class ConvertExcelToTIFF {
    public static void main(String[] args) {
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load the Excel file
        workbook.loadFromFile("Input.xlsx");

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

        //Save the first worksheet to TIFF
        sheet.saveToTiff("SheetToTiff.tiff");

        //Save a particular cell range in the first worksheet to TIFF
        //sheet.saveToTiff("CellRangeToTiff.tiff",1,1,5,2);
    }
}

The output file after converting the first worksheet to TIFF:

Convert Excel to TIFF in Java

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

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Table;
import com.spire.doc.documents.RowAlignment;

public class AlignTable {

    public static void main(String[] args) {

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

        //Add a table
        Table table =doc.addSection().addTable(true);

        //Set column width
        table.setColumnWidth(new float[]{100f,150f});

        //Set column number and row number
        table.resetCells(2,2);

        //Add text to cells
        table.get(0,0).addParagraph().appendText("Product Code");
        table.get(0,1).addParagraph().appendText("Description");
        table.get(1,0).addParagraph().appendText("T1052");
        table.get(1,1).addParagraph().appendText("AdvoCareSlim Tropical Swirl");

        //Align table to center
        table.getTableFormat().setHorizontalAlignment(RowAlignment.Center);

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

Align a Table Horizontally in Word in Java

Monday, 27 July 2020 07:54

Convert Word to PDF in Java

This article demonstrates how to use the Document.saveToFile() method offered by Spire.Doc for Java to convert a Word document to PDF. By using this method, you can also convert Word documents to XPS, SVG, XML, RTF, etc. Furthermore, the ToPdfParameterList class is introduced to control how Word documents will be converted to PDF. For example, whether to compress image quality or not while converting.

Below is a screenshot of the input Word document.

Convert Word to PDF in Java

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

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

        //Create Document object
        Document doc = new Document();

        //Load the file from disk.
        doc.loadFromFile("input.docx");

        //Create an instance of ToPdfParameterList.
        ToPdfParameterList ppl=new ToPdfParameterList();

        //Embeds full fonts by default when IsEmbeddedAllFonts is set to true.
        ppl.isEmbeddedAllFonts(true);

        //Set setDisableLink to true to remove the hyperlink effect for the result PDF page.
        //Set setDisableLink to false to preserve the hyperlink effect for the result PDF page.
        ppl.setDisableLink(true);

        //Set the output image quality as 40% of the original image. 80% is the default setting.
        doc.setJPEGQuality(40);

        //Save to file.
        doc.saveToFile("ToPDF.pdf", ppl);
    }
}

Convert Word to PDF in Java

Monday, 27 July 2020 06:52

Delete Bookmarks in PDF in Java

Spire.PDF for Java supports deleting a specific child bookmark, a parent bookmark along with its child bookmark(s) or delete all the bookmarks from a PDF file. In this article, you will learn how to delete PDF bookmarks using Spire.PDF for Java.

The input PDF file:

Delete Bookmarks in PDF in Java

import com.spire.pdf.PdfDocument;

public class DeleteBookmarks {
    public static void main(String[] args) {
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load the PDF file
        pdf.loadFromFile("AddBookmarks.pdf");

        //Delete the first child bookmark
        pdf.getBookmarks().get(0).removeAt(0);

        //Delete the first bookmark along with its child bookmark
        //pdf.getBookmarks().removeAt(0);

        //Delete all the bookmarks
        //pdf.getBookmarks().clear();

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

The output PDF file after deleting the first child bookmark:

Delete Bookmarks in PDF in Java

Friday, 24 July 2020 05:43

How to Autofit a Word Table in Java

This article demonstrates how to auto fit a Word table to content or to window, as well as how to fix the cloumn widths, by using Spire.Doc for Java.

Autofit to content

import com.spire.doc.*;

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

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

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

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

        //Add content to the cells
        table.get(0,0).addParagraph().appendText("Product Code");
        table.get(0,1).addParagraph().appendText("Description");
        table.get(1,0).addParagraph().appendText("T1052");
        table.get(1,1).addParagraph().appendText("AdvoCareSlim Tropical Swirl");
        table.get(2,0).addParagraph().appendText("T1062");
        table.get(2,1).addParagraph().appendText("AdvoCareSlim Caffeine Free Strawberry Kiwi");

        //Autofit column widths to contents
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

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

How to Autofit a Word Table in Java

Autofit to window

import com.spire.doc.*;

public class AutofitToWindow {

    public static void main(String[] args) {

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

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

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

        //Add content to the cells
        table.get(0,0).addParagraph().appendText("Product Code");
        table.get(0,1).addParagraph().appendText("Description");
        table.get(1,0).addParagraph().appendText("T1052");
        table.get(1,1).addParagraph().appendText("AdvoCareSlim Tropical Swirl");
        table.get(2,0).addParagraph().appendText("T1062");
        table.get(2,1).addParagraph().appendText("AdvoCareSlim Caffeine Free Strawberry Kiwi");

        //Autofit column widths to window
        table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Window);

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

How to Autofit a Word Table in Java

Fix column width

import com.spire.doc.*;

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

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

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

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

        //Add content to the cells
        table.get(0, 0).addParagraph().appendText("Product Code");
        table.get(0, 1).addParagraph().appendText("Description");
        table.get(1, 0).addParagraph().appendText("T1052");
        table.get(1, 1).addParagraph().appendText("AdvoCareSlim Tropical Swirl");
        table.get(2, 0).addParagraph().appendText("T1062");
        table.get(2, 1).addParagraph().appendText("AdvoCareSlim Caffeine Free Strawberry Kiwi");

        //Set the column widths
        for (int i = 0; i < table.getRows().getCount(); i++) {

            table.get(i,0).setCellWidth(80f,CellWidthType.Point);
            table.get(i,1).setCellWidth(160f,CellWidthType.Point);
        }

        //Fix the column widths so that the column width does not increases when the content exceeds the width
        table.autoFit(AutoFitBehaviorType.Fixed_Column_Widths);

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

How to Autofit a Word Table in Java

This article demonstrates how to set the transparency of image on a PDF file using Spire.PDF for Java.

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

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

        //Create a PDFDocument
        PdfDocument doc = new PdfDocument();
        //Add a section
        PdfSection section = doc.getSections().add();

        // Load image and set its width and height
        PdfImage image = PdfImage.fromFile("logo.png");
        double imageWidth = image.getPhysicalDimension().getWidth() / 3;
        double imageHeight = image.getPhysicalDimension().getHeight() / 3;

        //Add a page
        PdfPageBase page = section.getPages().add();
        float pageWidth = (float) page.getCanvas().getClientSize().getWidth();
        float y = 10;

        //Draw Title and set the font and format
        y = y + 5;
        PdfBrush brush = new PdfSolidBrush(new PdfRGBColor(new Color(255,69,0)));
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD,12));
        PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center);
        String text = String.format(" Set image Transparency ");
        page.getCanvas().drawString(text, font, brush, pageWidth / 2, y, format);
        Dimension2D size = font.measureString(text, format);
        y = y + (float) size.getHeight() + 6;

        //Set image transparency
        page.getCanvas().setTransparency(0.2f, 0.2f, PdfBlendMode.Normal);

        //Add image to the page
        page.getCanvas().drawImage(image, 0, y, imageWidth, imageHeight);
        page.getCanvas().save();

        // Save pdf file.
        doc.saveToFile("output/Transparency.pdf");
        // Close pdf file
        doc.close();
    }
}

Effective screenshot after adding the image to PDF and set the image transparency:

Set image transparency on PDF file in Java

Monday, 20 July 2020 07:58

Edit Bookmarks in PDF in Java

This article demonstrates how to edit the existing bookmarks in a PDF file, for example, change the bookmark title, font color and text style using Spire.PDF for Java.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfTextStyle;
import com.spire.pdf.graphics.PdfRGBColor;

import java.awt.*;

public class EditBookmarks {
    public static void main(String[] args) {
        //Create a PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Load the PDF file
        doc.loadFromFile("Bookmarks.pdf");

        //Get the first bookmark
        PdfBookmark bookmark = doc.getBookmarks().get(0);
        //Change the title of the bookmark
        bookmark.setTitle("New Title");
        //Change the font color of the bookmark
        bookmark.setColor(new PdfRGBColor(new Color(255,0,0)));
        //Change the outline text style of the bookmark
        bookmark.setDisplayStyle(PdfTextStyle.Italic);

        //Edit child bookmarks of the first bookmark
        for (PdfBookmark childBookmark : (Iterable) bookmark) {
            childBookmark.setColor(new PdfRGBColor(new Color(0,0,255)));
            childBookmark.setDisplayStyle(PdfTextStyle.Bold);

            for (PdfBookmark childBookmark2 : (Iterable) childBookmark) {
                childBookmark2.setColor(new PdfRGBColor(new Color(160,160,122)) );
                childBookmark2.setDisplayStyle(PdfTextStyle.Bold);
            }
        }

        //Save the result file
        doc.saveToFile("EditBookmarks.pdf");
        doc.close();
    }
}

Output:

Edit Bookmarks in PDF in Java

This article will show you how to extract text from the specific area of a PDF page or a particular page of PDF.

Extract text from the defined area from one page of PDF:

import com.spire.pdf.*;
import java.awt.geom.Rectangle2D;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

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

        //Create a new txt file to save the extracted text
        String result = "output/extractTextFromSpecificArea.txt";
        File file=new File(result);
        if(!file.exists()){
            file.delete();
        }
        file.createNewFile();
        FileWriter fw=new FileWriter(file,true);
        BufferedWriter bw=new BufferedWriter(fw);

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

        //Extract text from a specific rectangular area within the page
        String text = page.extractText(new Rectangle2D.Float(80, 20, 500, 260));

        bw.write(text);

        bw.flush();
        bw.close();
        fw.close();
    }
}

Effective screenshot:

Java extract text from specific area or particular page of PDF

Extract text from a particular page of PDF:

import com.spire.pdf.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

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

        //Create a new txt file to save the extracted text
        String result = "output/extractTextFromParticularPage.txt";
        File file=new File(result);
        if(!file.exists()){
            file.delete();
        }
        file.createNewFile();
        FileWriter fw=new FileWriter(file,true);
        BufferedWriter bw=new BufferedWriter(fw);

        //Get the third page
        PdfPageBase page = pdf.getPages().get(2);

        // Extract text from page keeping white space
        String text = page.extractText(true);

        // Extract text from page without keeping white space
        //String text = page.extractText(false);

        bw.write(text);

        bw.flush();
        bw.close();
        fw.close();
    }
}

Effective screenshot of the extract text from the third page:

Java extract text from specific area or particular page of PDF