美文网首页
使用iText 生成 包含横 纵页面的word文件

使用iText 生成 包含横 纵页面的word文件

作者: 淡定独行 | 来源:发表于2016-12-16 12:14 被阅读1200次
   最近做项目的时候要实现用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();
}

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

相关文章

网友评论

      本文标题:使用iText 生成 包含横 纵页面的word文件

      本文链接:https://www.haomeiwen.com/subject/dzdnmttx.html