Aspose.Words - Create New Document

Document doc = new Document();

// DocumentBuilder provides members to easily add content to a document.
DocumentBuilder builder = new DocumentBuilder(doc);

// Write a new paragraph in the document with some text as "Sample Content..."
builder.writeln("Aspose Sample Content for Word file.");

// Save the document in DOCX format. The format to save as is inferred from the extension of the file name.
// Aspose.Words supports saving any document in many more formats."Aspose_NewDoc.docx",SaveFormat.DOCX);


WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
MainDocumentPart mdp = wordMLPackage.getMainDocumentPart();

// Example 1: add text in Title style
mdp.addStyledParagraphOfText("Title", "Example 1");

// Example 2: add normal paragraph (no explicit style)
mdp.addParagraphOfText("Example 2");

// Example 3a: bold text
// To get bold text, you must set the run's rPr@w:b,
// so you can't use the addParagraphOfText convenience method

org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();
org.docx4j.wml.P  p = factory.createP();

org.docx4j.wml.Text  t = factory.createText();
t.setValue("Example 3a (bold)");

org.docx4j.wml.R  run = factory.createR();


org.docx4j.wml.RPr rpr = factory.createRPr();		
org.docx4j.wml.BooleanDefaultTrue b = new org.docx4j.wml.BooleanDefaultTrue();


// Optionally, set pPr/rPr@w:b		
org.docx4j.wml.PPr ppr = factory.createPPr();	    
p.setPPr( ppr );
org.docx4j.wml.ParaRPr paraRpr = factory.createParaRPr();

// or just:
// mdp.getContent().add(p);
// but:
// mdp.addObject(p);
// is a better alternative if you are using a new style, since it 
// will ensure that the style is activated  

// Example 3b: bold text
// Well, actually you can use addParagraphOfText:
P p3b = mdp.addParagraphOfText("Example 3b (bold)");
R r3b = (R)p3b.getContent().get(0);
// .. now set rPr (I'll just reuse the above object)

// Example 4: Here is an easier way:
String str = "<w:p xmlns:w=\"\" ><w:r><w:rPr><w:b /></w:rPr><w:t>Example 4</w:t></w:r></w:p>";

			org.docx4j.XmlUtils.unmarshalString(str) );

// Example 5: Let's add a table
int writableWidthTwips = wordMLPackage.getDocumentModel().getSections().get(0).getPageDimensions().getWritableWidthTwips();
int cols = 3;
int cellWidthTwips = new Double( 
							Math.floor( (writableWidthTwips/cols ))

Tbl tbl = TblFactory.createTable(3, 3, cellWidthTwips);

// Pretty print the main document part
		XmlUtils.marshaltoString(mdp.getJaxbElement(), true, true) );

// Optionally save it
if (save) {
	String filename = "OUT_CreateWordprocessingMLDocument.docx"; );
	System.out.println("Saved " + filename);

Download Source Code

For More Examples, Please Visit Aspose Docs

Last edited Jan 12, 2015 at 2:30 PM by shoaibkhan, version 3