Wednesday, 10 July 2019 03:44

Convert Word to Images in Java

This following code snippets demonstrate how to convert Word documents to image files using Spire.Doc for Java.

Convert a particular page to an image

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

//load a Word file
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

//save the first page to a BufferedImage
BufferedImage image= doc.saveToImages(0, ImageType.Bitmap);

//write the image data to a .png file
File file= new File("output/ToPNG.png");
ImageIO.write(image, "PNG", file);

Convert the whole document to multiple images

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

//load a Word file
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

//loop through the pages
for (int i = 0; i < doc.getPageCount(); i++) {

    //save the specific page to a BufferedImage
    BufferedImage image= doc.saveToImages(i, ImageType.Bitmap);

    //write the image data to a .png file
    File file = new File( "output/" + String.format(("Img-%d.png"), i));
    ImageIO.write(image, "PNG", file);
}

Spire.Presentation for Java supports to save the whole presentation slides with table, chart and shape to image. And it also supports to save the single element in the presentation slides, such as chart, table and shape into image. This article will show you how to save shape and chart on Presentation Slide as image in Java.

import com.spire.presentation.ISlide;
import com.spire.presentation.Presentation;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class ShapeAsImage {
    public static void main(String[] args) throws Exception {
        String inputFile = "Sample.pptx";
        String outputFile = "output/";

        //Create a Presentation instance and load sample file
        Presentation presentation = new Presentation();
        presentation.loadFromFile(inputFile);

        //Traverse every slides and every shapes on the slides
        int k = 0;
        for (int i = 0; i < presentation.getSlides().getCount(); i++) {
            ISlide slide = presentation.getSlides().get(i);
            for (int j = 0; j < slide.getShapes().getCount(); j++) {
                String fileName = outputFile + String.format("shapeToImage-%1$s.png", k);
                //Save every single shape as image
                BufferedImage image = slide.getShapes().saveAsImage(j);
                ImageIO.write(image, "PNG", new File(fileName));
                k++;
            }
        }
    }
}

Save Chart, Table and Shape on Presentation slides as Image in Java

Save Chart, Table and Shape on Presentation slides as Image in Java

Save Chart, Table and Shape on Presentation slides as Image in Java

Animation can make a PowerPoint document more dynamic. In this article, we'll introduce how to add animations to shapes in a PowerPoint document using Spire.Presentation for Java.

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;
import com.spire.presentation.drawing.animation.AnimationEffectType;

import java.awt.*;

import java.awt.geom.Rectangle2D;

public class SetAnimation {
    public static void main(String[] args) throws Exception {
        //create a PowrePoint document 
        Presentation ppt = new Presentation();
        //add a slide
        ISlide slide = ppt.getSlides().get(0);

        //Add a shape to slide
        IAutoShape shape = slide.getShapes().appendShape(ShapeType.CUBE, new Rectangle2D.Double(50, 150, 150, 150));
        shape.getFill().setFillType(FillFormatType.SOLID);
        shape.getFill().getSolidColor().setColor(Color.orange);
        shape.getShapeStyle().getLineColor().setColor(Color.white);

        //Add animation to the shape
        slide.getTimeline().getMainSequence().addEffect(shape, AnimationEffectType.FADED_SWIVEL);

        //save the document
        ppt.saveToFile("AddAnimationToShape.pptx", FileFormat.PPTX_2013);
    }
}

Add Animations to Shapes in PowerPoint in Java

Embedding and applying private fonts in Word or PDF documents can make your documents unique. This article demonstrates how to embed fonts in a Word document as well as a converted PDF document, by using Spire.Doc for Java.

Embed Font in Word Document

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.PrivateFontPath;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;

public class EmbedPrivateFontInWord {

    public static void main(String[] args) {

        //create a Word document
        Document document = new Document();
        
        //add a paragraph
        Paragraph paragraph = document.addSection().addParagraph();
        
        //embed a private font in Word document
        document.setEmbedFontsInFile(true);
        PrivateFontPath fontPath = new PrivateFontPath();
        fontPath.setFontName("Otto");
        fontPath.setFontPath("C:\\Users\\Administrator\\Desktop\\Otto.ttf");
        document.getPrivateFontList().add(fontPath);

        //add text to the paragraph and apply the embedded font 
        TextRange tr = paragraph.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.");
        tr.getCharacterFormat().setFontName("Otto");
        tr.getCharacterFormat().setFontSize(26f);

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

Embed Private Fonts When Saving Word to DOCX and PDF in Java

Embed Font in Converted PDF Document

import com.spire.doc.Document;
import com.spire.doc.PrivateFontPath;
import com.spire.doc.ToPdfParameterList;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextRange;

import java.util.*;

public class EmbedPrivateFontInConvertedPDF {

    public static void main(String[] args) {

        //create a Word document
        Document document = new Document();

        //add a paragraph
        Paragraph paragraph = document.addSection().addParagraph();

        //initialize PrivateFontPath object
        PrivateFontPath fontPath = new PrivateFontPath("Otto","C:\\Users\\Administrator\\Desktop\\Otto.ttf");

        //add text to paragraph and apply the private font
        TextRange tr = paragraph.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.");
        tr.getCharacterFormat().setFontName("Otto");
        tr.getCharacterFormat().setFontSize(26f);

        //create a ToPdfParameterList object
        ToPdfParameterList toPdfParameterList = new ToPdfParameterList();

        //set private fonts as a parameter for converting Word to PDF
        List pathList = new LinkedList<>();
        pathList.add(fontPath);
        toPdfParameterList.setPrivateFontPaths(pathList);

        //save to PDF file
        document.saveToFile("output/EmbedFont.pdf",toPdfParameterList);
    }
}

Embed Private Fonts When Saving Word to DOCX and PDF in Java

Wednesday, 03 July 2019 09:23

Compress PDF document in Java

This article will demonstrate how to use Spire.PDF for Java to compress PDF document by compressing the PDF contents and compressing the images in the PDF document.

Compressing content

import com.spire.pdf.*;

public class CompressPDF {

    public static void main(String[] args) {

        String inputFile = "Sample.pdf";
        String outputFile = "output/CompressPDFcontent.pdf";

        PdfDocument document = new PdfDocument();
        document.loadFromFile(inputFile);

        document.getFileInfo().setIncrementalUpdate(false);

        document.setCompressionLevel(PdfCompressionLevel.Best);

        document.saveToFile(outputFile, FileFormat.PDF);
        document.close();
        }
    }

Effective screenshot after compressing the PDF content:

Compress PDF document in Java

Compressing image

import com.spire.pdf.*;
import com.spire.pdf.exporting.PdfImageInfo;
import com.spire.pdf.graphics.PdfBitmap;

public class CompressPDF {

    public static void main(String[] args) {

        String inputFile = "Sample.pdf";
        String outputFile = "output/CompressPDFImage.pdf";

        PdfDocument document = new PdfDocument();
        document.loadFromFile(inputFile);

        document.getFileInfo().setIncrementalUpdate(false);

        for (int i = 0; i < document.getPages().getCount(); i++) {

            PdfPageBase page = document.getPages().get(i);
            PdfImageInfo[] images = page.getImagesInfo();
            if (images != null && images.length > 0)
                for (int j = 0; j < images.length; j++) {
                    PdfImageInfo image = images[j];
                    PdfBitmap bp = new PdfBitmap(image.getImage());
                    bp.setQuality(20);
                    page.replaceImage(j, bp);

                }
        }
        document.saveToFile(outputFile, FileFormat.PDF);
        document.close();
    }
}

Effective screenshot after compressing the PDF image:

Compress PDF document in Java

This article will show you have to replace the content of a bookmark in Word using Spire.Doc for Java.

Replace bookmark content with text

import com.spire.doc.*;
import com.spire.doc.documents.*;

public class ReplaceBookmark {
    public static void main(String[] args){
        //load the Word document
        Document doc = new Document("Bookmark.docx");

        //locate the bookmark."SimpleBookmark"
        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
        bookmarkNavigator.moveToBookmark("SimpleBookmark");

        //replace the content of the bookmark with text
        bookmarkNavigator.replaceBookmarkContent("This is new content", false);

        //save the resultant document
        doc.saveToFile("ReplaceWithText.docx", FileFormat.Docx);
    }
}

Replace Bookmark Content in Word in Java

Replace bookmark content with HTML string

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.ParagraphBase;

public class ReplaceBookmark {
    public static void main(String[] args){
        //load the Word document
        Document doc = new Document("Bookmark.docx");

        //add a temp section
        Section tempSection = doc.addSection();
        //add a paragraph and append Html string
        String html = "

This Bookmark has been edited

"; tempSection.addParagraph().appendHTML(html); //Get the first item and the last item of the paragraph ParagraphBase firstItem = (ParagraphBase)tempSection.getParagraphs().get(0).getItems().getFirstItem(); ParagraphBase lastItem = (ParagraphBase)tempSection.getParagraphs().get(0).getItems().getLastItem(); //create a TextBodySelection object TextBodySelection selection = new TextBodySelection(firstItem, lastItem); //create a TextBodyPart object TextBodyPart bodyPart = new TextBodyPart(selection); //locate the bookmark "SimpleBookmark" BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc); bookmarkNavigator.moveToBookmark("SimpleBookmark"); //replace the content of the bookmark with Html string bookmarkNavigator.replaceBookmarkContent(bodyPart); //remove the temp section doc.getSections().remove(tempSection); //save the resultant document doc.saveToFile("ReplaceWithHTMLString.docx", FileFormat.Docx); } }

Replace Bookmark Content in Word in Java

Replace bookmark content with table

import com.spire.doc.*;
import com.spire.doc.documents.*;

public class ReplaceBookmark {
    public static void main(String[] args){
        //load the Word document
        Document doc = new Document("Bookmark.docx");

        String[][] data =
                {
                        new String[]{"Name", "Capital", "Continent", "Area"},
                        new String[]{"Bolivia", "La Paz", "South America", "1098575"},
                        new String[]{"Brazil", "Brasilia", "South America", "8511196"},
                        new String[]{"Canada", "Ottawa", "North America", "9976147"},
                        new String[]{"Chile", "Santiago", "South America", "756943"},
                };

        //create a table
        Table table = new Table(doc,true);
        table.resetCells(5, 4);
        for (int i = 0; i < data.length; i++) {
            TableRow dataRow = table.getRows().get(i);
            for (int j = 0; j < data[i].length; j++) {
                dataRow.getCells().get(j).addParagraph().appendText(data[i][j]);
            }
        }

        //create a TextBodyPart object
        TextBodyPart bodyPart= new TextBodyPart(doc);
        bodyPart.getBodyItems().add(table);

        //locate the bookmark "SimpleBookmark"
        BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(doc);
        bookmarkNavigator.moveToBookmark("SimpleBookmark");

        //replace the content of the bookmark with table
        bookmarkNavigator.replaceBookmarkContent(bodyPart);

        //save the resultant document
        doc.saveToFile("ReplaceWithTable.docx", FileFormat.Docx);
    }
}

Replace Bookmark Content in Word in Java

When there are overlapping shapes/images in your presentation slide, you can control which shape is under or above which shape by bring a shape forward or to front, or sending a shape backward or to back. The following example shows you how to bring a shape forward using Spire.Presentation with C# and VB.NET.

Code Snippets

[C#]
//load the sample PowerPoint file
Presentation presentation = new Presentation();
presentation.LoadFromFile(@"C:\Users\Administrator\Desktop\input.pptx");

//get the specified shape
IShape shape = presentation.Slides[0].Shapes[0];

//bring the shape forward through SetShapeArrange method
shape.SetShapeArrange(ShapeArrange.BringForward);

//save to file
presentation.SaveToFile("output.pptx", FileFormat.Pptx2013);
[VB.NET]
'load the sample PowerPoint file
Dim presentation As Presentation =  New Presentation() 
presentation.LoadFromFile("C:\Users\Administrator\Desktop\input.pptx")
 
'get the specified shape
Dim shape As IShape =  presentation.Slides(0).Shapes(0) 
 
'bring the shape forward through SetShapeArrange method
shape.SetShapeArrange(ShapeArrange.BringForward)
 
'save to file
presentation.SaveToFile("output.pptx", FileFormat.Pptx2013)

Output

Arrange Shapes in PowerPoint in C#, VB.NET

This article demonstrates how to read and remove built-in and custom document properties in Word document using Spire.Doc for Java.

Read document properties

Read built-in document properties

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

public class SetDocumentProperties {
    public static void main(String[] args){
        //Load Word document
        Document document = new Document("SetBuiltInProperties.docx");

        //Read built-in properties
        System.out.println("Title: " + document.getBuiltinDocumentProperties().getTitle());
        System.out.println("Subject: " + document.getBuiltinDocumentProperties().getSubject());
        System.out.println("author: " + document.getBuiltinDocumentProperties().getAuthor());
        System.out.println("company: " + document.getBuiltinDocumentProperties().getCompany());
        System.out.println("manager: " + document.getBuiltinDocumentProperties().getManager());
        System.out.println("category: " + document.getBuiltinDocumentProperties().getCategory());
        System.out.println("keyWords: " + document.getBuiltinDocumentProperties().getKeywords());
        System.out.println("comments: " + document.getBuiltinDocumentProperties().getComments());
    }
}

Read and Remove Document Properties in Word in Java

Read custom document properties

Remove built-in properties

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


public class SetDocumentProperties {
    public static void main(String[] args){
        //Load Word document
        Document document = new Document("SetBuiltInProperties.docx");

        //Remove built-in properties by setting the value to null
        document.getBuiltinDocumentProperties().setTitle("");
        document.getBuiltinDocumentProperties().setSubject("");
        document.getBuiltinDocumentProperties().setAuthor("");
        document.getBuiltinDocumentProperties().setCompany("");
        document.getBuiltinDocumentProperties().setManager("");
        document.getBuiltinDocumentProperties().setCategory("");
        document.getBuiltinDocumentProperties().setKeywords("");
        document.getBuiltinDocumentProperties().setComments("");

        //Save the resultant document
        document.saveToFile("RemoveBuiltInProperties.docx", FileFormat.Docx_2013);
    }
}

Read and Remove Document Properties in Word in Java

Remove custom document properties

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

public class SetDocumentProperties {
    public static void main(String[] args){
        //Load Word document
        Document document = new Document("SetCustomProperties.docx");

        //Remove specific custom property by name
        document.getCustomDocumentProperties().remove("TrackingID");
        document.getCustomDocumentProperties().remove("Checked by");

        //Save the resultant document
        document.saveToFile("RemoveCustomProperties.docx", FileFormat.Docx_2013);
    }
}
Thursday, 20 June 2019 05:54

Add Fillable Forms to Word in Java

This article demonstrates how to insert fillable forms such as text boxes, check boxes and drop-down lists to a Word document using Spire.Doc for Java.

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;
import com.spire.doc.documents.VerticalAlignment;
import com.spire.doc.fields.CheckBoxFormField;
import com.spire.doc.fields.DropDownFormField;
import com.spire.doc.fields.TextFormField;

public class CreateFormFields {

    public static void main(String[] args) {

        //create a Word document and add a section
        Document doc = new Document();
        Section section = doc.addSection();

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

        //add text to the cells of the first column
        Paragraph paragraph = table.getRows().get(0).getCells().get(0).addParagraph();
        paragraph.appendText("Text Form Field");
        paragraph = table.getRows().get(1).getCells().get(0).addParagraph();
        paragraph.appendText("Check Box Form Field");
        paragraph = table.getRows().get(2).getCells().get(0).addParagraph();
        paragraph.appendText("Drop Down Form Field");

        //add a text form to the specific cell
        paragraph = table.getRows().get(0).getCells().get(1).addParagraph();
        TextFormField textField = (TextFormField) paragraph.appendField("textbox", FieldType.Field_Form_Text_Input);
        textField.setTextFieldType(TextFormFieldType.Regular_Text);

        //add a checkbox form to the specific cell
        paragraph = table.getRows().get(1).getCells().get(1).addParagraph();
        CheckBoxFormField checkboxField = (CheckBoxFormField)paragraph.appendField("checkbox", FieldType.Field_Form_Check_Box);

        //add a dropdown-list form to the specific cell
        paragraph = table.getRows().get(2).getCells().get(1).addParagraph();
        DropDownFormField dropdownField = (DropDownFormField)paragraph.appendField("listbox",FieldType.Field_Form_Drop_Down);
        dropdownField.getDropDownItems().add("Canada");
        dropdownField.getDropDownItems().add("United States");
        dropdownField.getDropDownItems().add("Other");

        //create a ParagraphStyle object
        ParagraphStyle style = new ParagraphStyle(doc);
        style.setName("newFont");
        style.getCharacterFormat().setFontName("Calibri");
        style.getCharacterFormat().setFontSize(13);
        doc.getStyles().add(style);

        for (int i = 0; i < table.getRows().getCount(); i++) {

            //set row height
            table.getRows().get(i).setHeight(30f);
            for (Object cell:table.getRows().get(i).getCells()){
                if (cell instanceof TableCell)
                {
                    //set the vertical alignment of each cell to middle
                    ((TableCell) cell).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);

                    //apply paragraph style to each cell
                    ((TableCell) cell).getParagraphs().get(0).applyStyle(style.getName());
                }
            }
        }

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

Add Fillable Forms to Word in Java

Starts from version 7.6.5, Spire.Doc supports to add Latex math code to Word document in C#. This article will show you how to add Latex Math Symbols and equation to word document.

//create a word document
Document doc = new Document();

//add a section
Section section = doc.AddSection();

//add a paragraph to the section 
Paragraph paragraph = section.AddParagraph();

//add a LatexMathcode to the first paragraph
OfficeMath officeMath = new OfficeMath(doc);
paragraph.Items.Add(officeMath);
officeMath.FromLatexMathCode("x^{2}+\\sqrt{x^{2}+1}=2");

//add equation to the second paragraph
Paragraph paragraph2 = section.AddParagraph();
OfficeMath officeMath1 = new OfficeMath(doc);
paragraph2.Items.Add(officeMath1);
officeMath1.FromLatexMathCode("\\forall x \\in X, \\quad \\exists y \\leq \\epsilon");

//add symbols to the third paragraph
Paragraph paragraph3 = section.AddParagraph();
OfficeMath officeMath2 = new OfficeMath(doc);
paragraph3.Items.Add(officeMath2);
officeMath2.FromLatexMathCode(" \\alpha,\\beta, \\gamma, \\Gamma, \\pi, \\Pi, \\phi, \\varphi, \\mu, \\Phi");

//save the document to file       
doc.SaveToFile("Equation.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("Equation.docx");

Effective screenshot after adding latex math code and symbols to the word document:

C# insert math equation and symbol to Word document

Page 7 of 114