利用poi-tl生成word模板并实现行复制

第一步,引入相关依赖

        
            org.apache.poi
            poi
            4.1.2
        
        
            org.apache.poi
            poi-ooxml
            4.1.2
        
        
            org.apache.poi
            poi-ooxml-schemas
            4.1.2
        

        
      
        com.deepoove
           poi-tl
           1.10.0
       
        
        
            com.alibaba
            fastjson
            1.2.78
        

第二步 制作word模板

利用poi-tl生成word模板并实现行复制_第1张图片

图片的循环这里使用[@xxxx]占位,普通文本字段使用{{xxxx}}占位,因为存在行复制,所以使用{{xxx}}占位后,使用[xxxx]进行占位

第三步 直接上代码

a.因为涉及到对于图片的处理,图片也要进行行循环,所以要继承AbstractRenderPolicy,话不多数,直接上代码

  public class PictureRenderPolicy extends AbstractRenderPolicy>  {

        @Override
        public void doRender(RenderContext> renderContext) throws Exception {
            WhereDelegate where = renderContext.getWhereDelegate();
            List data = renderContext.getData();
            for (int i = 0; i < data.size(); i++) {
                // 目标宽度,等比例缩放图片,指定宽度
                int targetWidth = 200;
                ByteArrayInputStream in = new ByteArrayInputStream(data.get(i).getPictureSupplier().get());
                BufferedImage image = ImageIO.read(in);
                int originalWidth = image.getWidth();
                int originalHeight = image.getHeight();
                int targetHeight = (int) Math.round((double) targetWidth / originalWidth * originalHeight);
                //缩放图片
                BufferedImage scaledImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics2D = scaledImage.createGraphics();
                graphics2D.drawImage(image.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH), 0, 0, null);
                graphics2D.dispose();
                byte[] scaledImageData = getImageBytes(scaledImage);
                where.addPicture(new ByteArrayInputStream(scaledImageData),6,targetWidth,targetHeight);
            }
        }
        @Override
        protected void afterRender(RenderContext> context) {
            // 清空标签
            clearPlaceholder(context, true);
        }

    }
    
     private static byte[] getImageBytes(BufferedImage image) throws Exception {
        File tempFile = File.createTempFile("tempImage", "");
        ImageIO.write(image, "png", tempFile);
        FileInputStream inputStream = new FileInputStream(tempFile);
        byte[] imageData = IOUtils.toByteArray(inputStream);
        inputStream.close();
        tempFile.delete();
        return imageData;
    }

最后进行测试

 @Test
    public void test5(){
       //创建行循环策略
        LoopRowTableRenderPolicy rowTableRenderPolicy = new LoopRowTableRenderPolicy();
       //告诉模板引擎,要在p做行循环,绑定行循环策略
        Configure configure = Configure.builder().bind("p", rowTableRenderPolicy).bind("c",rowTableRenderPolicy).bind("img", new PictureRenderPolicy()).bind("img1", new PictureRenderPolicy()).build();
        //创建目标文件
        File sourceFile = new File("D:\\company\\develop\\pdfdemo\\src\\main\\resources\\templates\\temp.docx");
        //构建数据
        Map data = new HashMap();
        data.put("projectName", "jiefei");
        data.put("date", "18");
        data.put("person1", "福建福清");
        data.put("person2", "福建福清");

        List list = new ArrayList<>();
        PictureRenderData pictureRenderData = Pictures.ofUrl("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F7f0ae7b4-0a4c-418b-b0c9-1d666caa6b47%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1690452830&t=265cd68782f20caa66f175404c784ca5")
                .size(100, 100).create();
        list.add( Pictures.ofUrl("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F7f0ae7b4-0a4c-418b-b0c9-1d666caa6b47%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1690452830&t=265cd68782f20caa66f175404c784ca5")
                .size(200, 200).create());
        list.add( Pictures.ofUrl("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fss2.meipian.me%2Fusers%2F72978711%2Forigin6b96eb6e50aa18ec21756318da432bea.jpg%3Fmeipian-raw%2Fbucket%2Fivwen%2Fkey%2FdXNlcnMvNzI5Nzg3MTEvb3JpZ2luNmI5NmViNmU1MGFhMThlYzIxNzU2MzE4ZGE0MzJiZWEuanBn%2Fsign%2Fbeea6e21a810f6f90e231fe5f1aeb0df.jpg&refer=http%3A%2F%2Fss2.meipian.me&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1690453179&t=7849883700d28ef9905cd68b1703a846")
                .size(200, 200).create());

        List c = new ArrayList<>();
        c.add("11111111111111111");
        c.add("2222222222222222222");

        Demo demo = new Demo("1",list,c ,list,c);


        Demo demo1 = new Demo("2",list,c,list,c);

        List list3 = new ArrayList<>();
        TestDemo test =new TestDemo("ceshi","手动滑稽开始的");
        TestDemo test1 =new TestDemo("ceshi","手动滑稽开始的");
        list3.add(test);
        list3.add(test1);
        List list2 = new ArrayList<>();
        list2.add(demo);
        list2.add(demo1);
        data.put("p",list2);
        data.put("c",list3);
        data.put("process","aaaa \n bbbbb");



       //创建输出流
        OutputStream os = null;
        try {
            os = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\temps.docx");
            //最终编译渲染并输出
            XWPFTemplate.compile(sourceFile,configure).render(data).writeAndClose(os);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }



    }

最终结果

利用poi-tl生成word模板并实现行复制_第2张图片

你可能感兴趣的:(java,word,spring,boot)