jasper 使用,關於list的連續模板讀取,讀取不同模板;pdf417+ireport

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;
    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章