docx4j处理word文档另起一页合并的解决方法,wps软件和office软件打开均有分页效果

合并文件方法:

/**
     * 合并docx输出文件流
     *
     * @param streams
     *            要合并的word文件的输入流
     * @return InputStream
     * @throws Docx4JException
     * @throws IOException
     */
    public static InputStream mergeDocx(final List<InputStream> streams) throws Docx4JException, IOException {
        WordprocessingMLPackage target = null;
        final File generated = File.createTempFile("tmp", ".docx");
        int chunkId = 0;
        Iterator<InputStream> it = streams.iterator();
        while (it.hasNext()) {
            InputStream is = it.next();
            if (is != null) {
                try {
                    if (target == null) {
                        //第一次插入创建
                        OutputStream os = new FileOutputStream(generated);
                        os.write(IOUtils.toByteArray(is));
                        os.close();
                        target = WordprocessingMLPackage.load(generated);
                    } else {
                        //其他文档在原有基础上追加
                        MainDocumentPart documentPart = target.getMainDocumentPart();
                        // 另起一页,换页
                        addPageBreak(documentPart);
                        // 插入文件内容
                        insertDocx(documentPart, IOUtils.toByteArray(is), chunkId++);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    is.close();
                }
            }
        }
        generated.deleteOnExit();
        if (target != null) {
            target.save(generated);
            return new FileInputStream(generated);
        } else {
            return null;
        }
    }

插入分页方法:

public static void addPageBreak(MainDocumentPart documentPart) {
        P paragraph = factory.createP();
        R run = factory.createR();
        Br br = factory.createBr();
        br.setType(STBrType.PAGE);
        run.getContent().add(br);
        paragraph.getContent().add(run);
        documentPart.getJaxbElement().getBody().getContent().add(paragraph);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值