我希望将所有格式的一个docx的内容复制到另一个docx(图像,项目符号和编号等)

时间:2016-10-06 12:04:57

标签: apache docx

这是代码的当前情况。我需要以正确的格式和位置导入所有图像。并且还需要子弹和编号完好无损。 主要动机是将文档从英语翻译成法语,但所有格式都保持不变。

        FileInputStream is = new FileInputStream("d:\\Profiles\\nishgupta\\Desktop\\Test1.docx"); 
        @SuppressWarnings("resource")
        XWPFDocument doc = new XWPFDocument(is);

        List<XWPFParagraph> paras = doc.getParagraphs();             

        @SuppressWarnings("resource")
        XWPFDocument newdoc = new XWPFDocument();                                     
        for (XWPFParagraph para : paras) {  

            if (!para.getParagraphText().isEmpty()) {       
                XWPFParagraph newpara = newdoc.createParagraph();
                copyAllRunsToAnotherParagraph(para, newpara);
            }
            else
            { 
                XWPFParagraph blankpara = newdoc.createParagraph();
                @SuppressWarnings("unused")
                XWPFRun blank = blankpara.createRun();                  
            }
        }

        FileOutputStream fos = new FileOutputStream(new File("d:\\Profiles\\nishgupta\\Desktop\\Test2.docx"));
        newdoc.write(fos);
        fos.flush();
        fos.close();
    } 

// Copy all runs from one paragraph to another, keeping the style unchanged
private static void copyAllRunsToAnotherParagraph(XWPFParagraph oldPar, XWPFParagraph newPar) {
    final int DEFAULT_FONT_SIZE = 10;

    for (XWPFRun run : oldPar.getRuns()) {  
        String textInRun = run.getText(0);
      if (textInRun == null || textInRun.isEmpty()) {
         continue;
     }    

        int fontSize = run.getFontSize();

        newPar.setAlignment(oldPar.getAlignment());
        XWPFRun newRun = newPar.createRun();

        // Copy text
        newRun.setText(textInRun);

        // Apply the same style
        newRun.setFontSize( ( fontSize == -1) ? DEFAULT_FONT_SIZE : run.getFontSize() );    
        newRun.setFontFamily( run.getFontFamily() );
        newRun.setBold( run.isBold() );
        newRun.setItalic( run.isItalic() );
        newRun.setColor( run.getColor() );
        newRun.setBold(run.isBold());
        newRun.setColor(run.getColor());
        newRun.setCapitalized(run.isCapitalized());
        newRun.setDoubleStrikethrough(run.isDoubleStrikeThrough());
        newRun.setEmbossed(run.isEmbossed());
        newRun.setItalic(run.isItalic());
        newRun.setImprinted(run.isImprinted());
        newRun.setKerning(run.getKerning());
        newRun.setShadow(run.isShadowed());
        newRun.setSmallCaps(run.isSmallCaps());
        newRun.setUnderline(run.getUnderline());
        newRun.setStrikeThrough(run.isStrikeThrough());         
    }        
}
}

0 个答案:

没有答案