1
votes

I am trying to create a word document from a java application and am using Apache POI stable version 3.7 for the same. When i try to change the font for a paragraph, i am encountering a null pointer exception even if the font family exists. In fact if i call the function with any font family it gives a npe. Heres the code:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

/**
 *
 * @author william
 */
public class CreateDocumentFromScratch 
{

    public static void main(String[] args) 
    {
        XWPFDocument document = new XWPFDocument();

        XWPFParagraph paragraphOne = document.createParagraph();


        XWPFRun paragraphOneRunOne = paragraphOne.createRun();

        paragraphOneRunOne.setFontFamily("Arial");
        paragraphOneRunOne.setText("Hello");



        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream("c:/will/First.docx");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            document.write(outStream);
            outStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Here is the exception:

run:
Exception in thread "main" java.lang.NullPointerException
    at org.apache.poi.xwpf.usermodel.XWPFRun.setFontFamily(XWPFRun.java:413)
    at pdftest.CreateDocumentFromScratch.main(CreateDocumentFromScratch.java:30)

Any idea what wrong am I doing? Also, how reliable is Apache POI to create formatted word documents?

1

1 Answers