How to create headers in word with Apche POI?

2

I have this code:

XWPFParagraph title = document.createParagraph();    
XWPFRun run = title.createRun();
title.setAlignment(ParagraphAlignment.CENTER);
String imgFile = "C:\Users\Leath\Documents\NetBeansProjects\usuario_1\src\imagenes\encabezado.png";
FileInputStream is = new FileInputStream(imgFile);
run.addBreak();
run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(500), Units.toEMU(50));
run.addBreak();
is.close();

But as you can see, I am only creating a paragraph and I would like it to generate the word, generate the image in the header, or learn to write a template in Word

    
asked by Ángel Zaragoza 10.08.2017 в 18:41
source

1 answer

1

If we are always going to have the same heading. I suggest you use a template you can make a word document where you add the image in the header and all the text you need, so if in the future you change the header you do not need to break your head if you change your position trivial thing

So we can have this code that reads your template (note that it is .docx because there is a bug when using .dotx )

String path = "D:\templates\mitemplate.docx";
try {            
    //Carmagos el template
    XWPFDocument template = new XWPFDocument(new FileInputStream(new File(path)));

    //agregamos el nuevo contenido
    XWPFParagraph para = template.createParagraph();

    XWPFRun run = para.createRun();
    run.setText("Hola");

    FileOutputStream fos = new FileOutputStream(new File("nuevo.docx"));

    template.write(fos);

    fos.close();

}
catch(FileNotFoundException ex){
    ex.printStackTrace();
} catch (IOException ex) {
    ex.printStackTrace();
}

And if we require a change, we simply modify our word and deposit it in the route we have.

    
answered by 10.08.2017 в 19:37