使用iText导出word 可自由设置为横页和纵页

        最近做项目的时候要实现用iText 生成word时, word生成的个别页面需要横向显示, 其他的保持纵向,百度了半天都是生成PDF的,经实验iText生成PDF是可以实现这个效果, 但此方法不适用word,

附上根据生成PDF的思路 生成word的代码

public void CreateDocument() throws FileNotFoundException, DocumentException {
        FileOutputStream out = new FileOutputStream("d:\\demo.doc");
        //设置纸张大小
        Document document = new Document(PageSize.A4); 
        //建立一个书写器,与document对象关联
        RtfWriter2.getInstance(document, out); 

        document.open(); 
        Paragraph paragraph1 = new Paragraph("Hello World1");
        document.add(paragraph1);
        document.newPage();

        //想实现A4纸页面横向显示
        document.setPageSize(PageSize.A4.rotate()); 
        Paragraph paragraph2 = new Paragraph("Hello World2");
        document.add(paragraph2);
        document.newPage();

        document.setPageSize(PageSize.A4);
        Paragraph paragraph3 = new Paragraph("Hello World3");
        document.add(paragraph3);
        document.newPage();
        document.close();
}

运行的结果是:生成的word 三页全部是纵向的,故document.setPageSize(PageSize.A4.rotate());设置无效。

       经过反复的实验,终于找到问题的关键了,原来页面的横纵是根据章节来决定的, 一个页面变成横向显示,其所在的章节中全部页面也会变成横向显示。

解决方案: 将word内容 拆分章节

public void CreateDocument() throws FileNotFoundException, DocumentException {
        FileOutputStream out = new FileOutputStream("d:\\demo.doc");
        //设置纸张大小
        Document document = new Document(PageSize.A4); 
        //建立一个书写器,与document对象关联
        RtfWriter2.getInstance(document, out); 

        document.open();
        //章节一
        Chapter chapter1 = new Chapter(1);
        chapter1.add(new Paragraph("Hello World1"));
        //章节二
        Chapter chapter2 = new Chapter(2);
        chapter2.add(new Paragraph("Hello World2"));
        //章节三
        Chapter chapter3 = new Chapter(3);
        chapter3.add(new Paragraph("Hello World3"));
        //将章节加入document中
        document.add(chapter1);
        //将章节二纵向显示
        document.setPageSize(PageSize.A4.rotate());
        document.add(chapter2);
        //将章节三还原成横向
        document.setPageSize(PageSize.A4);
        document.add(chapter3);
        document.close();
}

运行结果: 第一页为纵向,第二页为横向,第三页为纵向。

 

 

转载于:https://my.oschina.net/yilin007/blog/898012

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值