在word的表格中插入文档 行高和文本的行间距都变大了 同时不知道是否因为上面的原因 图片的位置也改变了,希望能够得到解答
add.docx (18.9 KB)
main.docx (28.8 KB)
mergedoc.docx (33.4 KB)
public static Document addDocument(String key,Document mainDoc,Document addDoc,Boolean isPortrait) {
try{
DocumentBuilder Builder = new DocumentBuilder(mainDoc);
Range range = mainDoc.getRange();
NodeCollection runs = mainDoc.getChildNodes(NodeType.PARAGRAPH, true); //获取所有节点
int dell = 0 ;
for (int i = 0; i < runs.getCount(); i++) {
Paragraph r = (Paragraph) runs.get(i);
String text = r.getRange().getText();//获取段落文本
if(text.length()>=key.length() && text.indexOf(key)>=0) {
//指定段落插入表格
Builder.moveTo(r);
Builder.getPageSetup().setPaperSize(PaperSize.A4);
if (isPortrait){
Builder.getPageSetup().setOrientation(Orientation.PORTRAIT);
}
else {
Builder.getPageSetup().setOrientation(Orientation.LANDSCAPE);
}
//range.replace(keyy, "" , true, false); //替换标记为空
Node insertAfterNode = Builder.getCurrentParagraph().getPreviousSibling();
insertDocumentAfterNode(insertAfterNode, mainDoc , addDoc);
r.remove();//删除标记所在行
break;
}
}
// mainDoc.updateFields();
return mainDoc;
}catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static void insertDocumentAfterNode(Node insertAfterNode, Document mainDoc, Document srcDoc) throws Exception {
if (insertAfterNode.getNodeType() != 8 && insertAfterNode.getNodeType() != 5) {
throw new Exception("The destination node should be either a paragraph or table.");
}else {
CompositeNode dstStory = insertAfterNode.getParentNode();
Body body = srcDoc.getLastSection().getBody();
DocumentBuilder Builder = new DocumentBuilder(mainDoc);
Builder.getParagraphFormat().setLineSpacingRule(LineSpacingRule.EXACTLY);
Builder.getParagraphFormat().setLineSpacing(0.5);
Builder.getParagraphFormat().setSpaceBefore(0.5);
Builder.getParagraphFormat().setSpaceAfter(0.5);
while (null != body.getLastParagraph() && !body.getLastParagraph().hasChildNodes()){
srcDoc.getLastSection().getBody().getLastParagraph().remove();
}
NodeImporter importer = new NodeImporter(srcDoc, mainDoc, ImportFormatMode.KEEP_DIFFERENT_STYLES);
int sectCount = srcDoc.getSections().getCount();
for (int sectIndex = 0; sectIndex < sectCount; ++sectIndex){
Section srcSection = srcDoc.getSections().get(sectIndex);
int nodeCount = srcSection.getBody().getChildNodes().getCount();
for (int nodeIndex = 0; nodeIndex < nodeCount; ++nodeIndex){
Node srcNode = srcSection.getBody().getChildNodes().get(nodeIndex);
Node newNode = importer.importNode(srcNode, true);
dstStory.insertAfter(newNode, insertAfterNode);
insertAfterNode = newNode;
}
}
}
}