Page 1 of 1

Basic Formatting

PostPosted: Fri Jul 19, 2013 11:39 am
by kan
I feel as though I am missing something very basic, but it took me a long time to figure out how to simply print text to a .docx file. I am trying to simply control the formatting of that text to be printed to the file. Is there any simple way to control the font, the size, the position (left, center, right, justified) of the text, and the spacing (double spacing for instance)? I just need a simple way to control where and how the text is finding its way onto the page without messing with the template styles.

I am probably being completely boneheaded here, but I feel like I'm going crazy and missing something obvious. Any help would be greatly appreciated. :)

This is the code I have so far:

Code: Select all

import java.io.File;

import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.exceptions.InvalidFormatException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.StyleDefinitionsPart;

import com.entrocorp.docizer.Docizer;

public class Word {
   
    public static void writeToFile(String internalPath, String content) {
        File docxFile = new File(Docizer.instance.getRootDirectory() + File.separator + internalPath + ".docx");
        try {
            WordprocessingMLPackage file = WordprocessingMLPackage.load(docxFile);
           
            file.getMainDocumentPart().getStyleDefinitionsPart().
           
            file.getMainDocumentPart().addStyledParagraphOfText("DefaultParagraphFont", content);
            file.save(docxFile);
        } catch (Docx4JException e) {
            e.printStackTrace();
        }
    }
   
    public static void createFile(String internalPath) {
       
        try {
            WordprocessingMLPackage file = WordprocessingMLPackage.createPackage();
            File docxFile = new File(Docizer.instance.getRootDirectory() + File.separator + internalPath + ".docx");
            file.save(docxFile);
           
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (Docx4JException e) {
            e.printStackTrace();
        }
       
    }

}

Re: Basic Formatting

PostPosted: Fri Jul 19, 2013 3:38 pm
by jason
Upload your sample docx to the demo webapp (link in menu above), and have it generate code for you.

If you don't like the generated code, maybe a fluent interface is more your thing. For that, see https://java.net/projects/gdocx/pages/GDocxAndDocx4j