由于poi-tl横向和竖向页合并会出现问题,改用spire.doc解决
用到的依赖:
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.0</version>
</dependency>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
@SneakyThrows
@org.junit.jupiter.api.Test
public void test5(){
InputStream head = new FileInputStream("C:/Users/usher/Desktop/1.docx");
XWPFTemplate headTemplate = XWPFTemplate.compile(head).render(new HashMap<>());//根据关键词填写模板
NiceXWPFDocument headTemplateXWPFDocument = headTemplate.getXWPFDocument();
InputStream main = docToDocx(new FileInputStream("C:/Users/lishu/Desktop/11.doc"));
com.spire.doc.Document headDocument = NiceXWPFDocumentToDocument(headTemplateXWPFDocument);
com.spire.doc.Document mainDocument = new com.spire.doc.Document(main);
SectionCollection sectionCollection = mainDocument.getSections();
Section lastSection = headDocument.getLastSection();
for(int i=0;i<sectionCollection.getCount();i++){
Section section = sectionCollection.get(i);
if("Portrait".equals(sectionCollection.get(i).getPageSetup().getOrientation().toString())){
//竖版
section.cloneSectionPropertiesTo(lastSection);//这一行是为了保留合并文件的页码
sectionCollection.get(i).getBody().getChildObjects().forEach(o -> {
lastSection.getBody().getChildObjects().add(((DocumentObject) o).deepClone());
});
}else{
headDocument.getSections().add(sectionCollection.get(i).deepClone());
}
}
headDocument.saveToFile("C:/Users/usher/Desktop/2.docx");
}
public com.spire.doc.Document NiceXWPFDocumentToDocument(NiceXWPFDocument niceXWPFDocument) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
niceXWPFDocument.write(os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
com.spire.doc.Document document = new com.spire.doc.Document();
document.loadFromStream(is, FileFormat.Docx);
closeStream(is);
closeStream(os);
return document;
}
posted on 2022-03-30 10:33 Usher_baby 阅读(491) 评论(0) 编辑 收藏 举报