jasper 使用,关于list的连续模板读取,读取不同模板;pdf417+ireport

本文介绍如何使用JasperReports进行报表设计,包括利用list字段简化复杂报表的创建,以及通过Java代码连续读取并填充不同模板。此外,还详细介绍了生成PDF417二维码的过程,解决ASCII码限制问题,确保数据正确显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.关于list的使用

定义一个dataset,定义list的字段

new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{mcLableDetailList})

 

这样就不用搞复杂的子父报表

2.连续读取不同的模板:

使用java代码实现:根据条件区分读取不同代码

// controller
    @GetMapping(value = { "printPalletLable" })
    public void printPalletLable(HttpServletResponse response) {
        try {
            List<LableVo> lableVoList;
            Map map = warpUsualParameters(super.getRequestParameters());

            lableVoList = relInvoiceService.printPalletLable(map);
            if (CollectionUtils.isEmpty(lableVoList)) {
                return;
            }
            List<LableVo> mcList = new ArrayList<>();
            List<LableVo> mxList = new ArrayList<>();
            List<JasperPrint> jasperPrintList = new ArrayList<>();
            Map<String, Object> params = new HashMap<>();
            String path = new ClassPathResource("reports/logs/anji.png").getPath();
            params.put("imageURL",path);
            lableVoList.stream().forEach(lableVo -> {
                if ("MC".equals(lableVo.getTarget())) {
                    mcList.add(lableVo);
                } else {
                    mxList.add(lableVo);
                }
            });
            if (CollectionUtils.isNotEmpty(mxList)) {
                InputStream inputStream = new ClassPathResource("reports/mxLable.jasper").getInputStream();
                JasperPrint print = JasperPrinter.fillReport(inputStream, params, mxList);
                jasperPrintList.add(print);
            }
            if (CollectionUtils.isNotEmpty(mcList)) {
                InputStream inputStream2 = new ClassPathResource("reports/mcLable.jasper").getInputStream();
                JasperPrint print2 = JasperPrinter.fillReport(inputStream2, params, mcList);
                jasperPrintList.add(print2);
            }
            JasperPrinter.exportPDFToWebList(jasperPrintList, null, response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
-----------------------------------------------------------------------------------------
//JasperPrinter 类
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @ClassName JasperPrinter
 * @Description: TODO
 * @Author dingkaiqiang
 * @Date 2019-11-28
 * @Version V1.0
 **/
public class JasperPrinter {
    public static void exportPDFToWeb(JasperPrint jasperPrint, String outputFileName, HttpServletResponse response)
            throws JRException, IOException {
        response.setContentType("application/pdf");
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    }

    public static JasperPrint fillReport(InputStream inputStream, Map<String, Object> params, Collection<?> detailList)
            throws JRException {
        JasperPrint jasperPrint = null;
        JRBeanCollectionDataSource datasource = null;
        if (detailList != null && !detailList.isEmpty()) {
            datasource = new JRBeanCollectionDataSource(detailList);
            jasperPrint = JasperFillManager.fillReport(inputStream, params, datasource);
        } else {
            jasperPrint = JasperFillManager.fillReport(inputStream, params, new JREmptyDataSource());
        }
        return jasperPrint;
    }
    /**
     * 连续读取多个模板
     * @param jasperPrintList
     * @param outputFileName
     * @param response
     * @throws JRException
     * @throws IOException
     */
    public static void exportPDFToWebList(List<JasperPrint> jasperPrintList, String outputFileName, HttpServletResponse response)
            throws JRException, IOException{
        ServletOutputStream outputStream = response.getOutputStream();
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            JRPdfExporter exporter = new JRPdfExporter();
            exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
            exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(baos));
            exporter.exportReport();
            byte[] bytes = baos.toByteArray();
            // 写出文件的类型
            response.setContentType("application/pdf;charset=UTF-8");
            baos.close();
            outputStream.write(bytes);
        } finally {
            outputStream.flush();
        }


    }
}

 

pdf417二维码

报表本身自带,这里限制于数据有ASCII码,导致数据不对,使用代码生成image形式

//            BarcodeFormat.PDF_417;
                String code=builder.toString();
                String path="D://pdf317code";
                Image barcode = null;
                BarcodePDF417 pdf417 = new BarcodePDF417();
                pdf417.setText(code);//设置文本
                System.out.println("codeValue:"+code);
                pdf417.setErrorLevel(8);//设置安全等级
                pdf417.setYHeight(2);//设置宽窄比例

                barcode = pdf417.createAwtImage(Color.black, Color.white);
                BufferedImage img = new BufferedImage((int)barcode.getWidth(null), (int)barcode.getHeight(null), BufferedImage.TYPE_INT_RGB);
                Graphics g = img.getGraphics();
                g.drawImage(barcode, 0, 0, Color.white, null);
                try {
                    ImageIO.write(img, "png",new File(path + ".png"));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                //----------------zing
                try {
                    String text = builder.toString(); // 二维码内容
                    int width = Integer.parseInt((String) map.get("width"));// 二维码图片宽度
                    int height = Integer.parseInt((String) map.get("height"));;; // 二维码图片高度
                    String format = "png";// 二维码的图片格式
                    String path2="D://pdf417code";

                    Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
                    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");	// 内容所使用字符集编码

                    BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.PDF_417, width, height, hints);
                    // 生成二维码
                    File outputFile = new File(path2 + ".png");

                    MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
                    BufferedImage bufferedImage = MatrixToImageWriter.getBufferedImage(bitMatrix);
                    printVO.setBufferedImage(img);

                }catch (Exception e){
                    e.printStackTrace();
                }
                labelList.add(printVO);

对应的vo:

package io.renren.modules.invoice.vo;

import lombok.Data;

import java.awt.image.BufferedImage;
import java.io.Serializable;

@Data
public class LabelPrintVO  {

    private BufferedImage bufferedImage;

}

工具类:

package io.renren.modules.invoice.util;


import com.google.zxing.common.BitMatrix;
import com.itextpdf.text.pdf.BarcodePDF417;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的,可以将该类直接拷贝到源码中使用
 */
public class MatrixToImageWriter {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    private MatrixToImageWriter() {
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }
    public static BufferedImage getBufferedImage(BitMatrix matrix) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        return image;
    }
    public static BufferedImage getBufferedImage(String code) throws IOException {
        Image barcode = null;
        BarcodePDF417 pdf417 = new BarcodePDF417();
        pdf417.setText(code);//设置文本
        System.out.println("codeValue:"+code);
        pdf417.setErrorLevel(8);//设置安全等级
        pdf417.setYHeight(2);//设置宽窄比例

        barcode = pdf417.createAwtImage(Color.black, Color.white);
        BufferedImage img = new BufferedImage((int)barcode.getWidth(null), (int)barcode.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        //必须要这行代码
        g.drawImage(barcode, 0, 0, Color.white, null);
        return img;
    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值