【Java】批量生成条形码-itextpdf

批量生成条形码
Controller

@ApiOperation("商品一览批量生成商品条形码")
    @PostMapping("/batchGenerateProdBarCode")
    public void batchGenerateProdBarCode(@RequestBody ProductListCondition productListCondition,HttpServletResponse response){
        importExportService.batchGenerateProdBarCode(response, productListCondition);
    }

Service

 /**
     * 商品一览批量生成商品条形码
     * @param productListCondition
     * @return
     */
    public void batchGenerateProdBarCode(HttpServletResponse response,ProductListCondition productListCondition){
        List<MProductEx> productExList = mProductListDao.selectmproduct(
 		productListCondition.getProdCdDis(),productListCondition.getBrand());
        try {
            int dataCount = productExList.stream().filter(f -> StringUtils.isNotEmpty(f.getProdLabel())).collect(Collectors.toList()).size();
            if(dataCount == 0){
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "没有要生成的条码请调整查询条件后重新生成");
            }
            if(CollectionUtil.isNotEmpty(productExList)){
                String exportFileName = URLEncoder.encode("商品条码", "UTF-8") + DateUtil.format(new Date(), "yyyyMMddHHmmss");
                response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + exportFileName + ".pdf");
                response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
                response.setHeader("content-Type", "application/pdf");
                generateProdBarcodePDF(productExList, response.getOutputStream(),response);
            }else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "没有要生成的条码请调整查询条件后重新生成");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
/**
     * 批量生成商品条形码pdf文件导出适配条码打印机
     *
     * @param productExList 条码数据x信息
     * @param os    输出流
     * @throws IOException
     */
    public static void generateProdBarcodePDF(List<MProductEx> productExList, OutputStream os,HttpServletResponse response) throws IOException {
        Document document = null;
        try {
            document = new Document(new Rectangle(120F, 85F), 10, 2, 10, 2);
            PdfWriter writer = PdfWriter.getInstance(document, os);
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            BaseFont bfChinese = BaseFont.createFont("C:\\Windows\\Fonts\\simsun.ttc,1",  BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);
            Font fontChinese = new Font(bfChinese, 2, Font.NORMAL);
            Pattern pat = Pattern.compile("[\u4e00-\u9fa5]");
            Matcher m = null;
            for (MProductEx p : productExList) {
                m = pat.matcher(p.getProdLabel());
                if(StringUtils.isNullOrEmpty(p.getProdLabel()) || m.find()){
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "商品编号不能为中文且不能为空");
                }
                document.newPage();
                //创建一个一列的表格
                PdfPTable headerTable = new PdfPTable(1);
                headerTable.setWidthPercentage(70.0F);
                PdfPCell rightCell = new PdfPCell();
                Image codeImage = BarcodeUtil.generateBarcodePrefixSuffix(cb, p.getProdLabel(), 22f, 6f);
                Phrase imageP = new Phrase("", fontChinese);
                //自己调整偏移值 主要是负值往下
                imageP.add(new Chunk(codeImage, 5, -1));
                String textNmShow ="商品名称:" + (StringUtils.isNotEmpty(p.getProdNm()) ? p.getProdNm() : "");
                String textUnitShow ="计量单位:" + (StringUtils.isNotEmpty(p.getUnitNm()) ? p.getUnitNm() : "") ;
                String textSpecShow ="规格: " + (StringUtils.isNotEmpty(p.getSpec()) ? p.getSpec() : "");
                String textModelAndUnitShow ="型号:" + (StringUtils.isNotEmpty(p.getModel()) ? p.getModel() : "") +
                        "  " + textUnitShow;
                //Chunk chunkCd = new Chunk(textCdShow,fontChinese);
                Chunk chunkNm = new Chunk(textNmShow,fontChinese);
                //Chunk chunkUnit = new Chunk(textUnitShow,fontChinese);
                Chunk chunkSpec = new Chunk(textSpecShow,fontChinese);
                Chunk chunkModel = new Chunk(textModelAndUnitShow,fontChinese);
                rightCell = new PdfPCell();
                //imageP.setLeading(2f,1.5f);
                rightCell.addElement(imageP);
                //rightCell.addElement(chunkCd);
                rightCell.addElement(new Chunk("  ",fontChinese));
                rightCell.addElement(chunkNm);
                //rightCell.addElement(chunkUnit);
                rightCell.addElement(chunkSpec);
                rightCell.addElement(chunkModel);
                //false自动换行
                rightCell.setNoWrap(false);
                //行间距
                //rightCell.setLeading(40f,10.0f);
                rightCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                rightCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                rightCell.setFixedHeight(26.0f);

                //rightCell.setPadding(4.0f);//填充
                headerTable.addCell(rightCell);
//                headerTable.setSplitLate(false);
//                headerTable.setSplitRows(true);
                document.add(headerTable);
            }
            //document.add(headerTable);
            os.flush();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            if(Objects.nonNull(document)){
                document.close();
            }
            if (Objects.nonNull(os)) {
                os.close();
            }
        }
    }

 /**
     * 批量生成商品条形码pdf文件导出适配A4纸
     *
     * @param productExList 条码数据x信息
     * @param os    输出流
     * @throws IOException
     */
    public static void generateProdBarcodeA4PDF(List<MProductEx> productExList, OutputStream os,HttpServletResponse response) throws IOException {
        Document document = null;
        try {
            document = new Document(new Rectangle(283F, 425F), 10, 10, 10, 10);
            PdfWriter writer = PdfWriter.getInstance(document, os);
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            //判断列,一条数据只允许单列
            int dataCount = productExList.stream().filter(f -> StringUtils.isNotEmpty(f.getProdLabel())).collect(Collectors.toList()).size();
            int numColumns = 1;
            if (dataCount > 1) {
                numColumns = 2;
            }
            BaseFont bfChinese = BaseFont.createFont("C:\\Windows\\Fonts\\simsun.ttc,1",  BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);
            Font fontChinese = new Font(bfChinese, 5, Font.NORMAL);
            //创建一个两列的表格
            PdfPTable headerTable = new PdfPTable(numColumns);
            if(numColumns == 1){
                headerTable.setWidthPercentage(40.0f);
            }else {
                headerTable.setWidthPercentage(80.0f);
            }
            PdfPCell rightCell = null;
            Pattern pat = Pattern.compile("[\u4e00-\u9fa5]");
            Matcher m = null;
            for (MProductEx p : productExList) {
                m = pat.matcher(p.getProdLabel());
                if(StringUtils.isNullOrEmpty(p.getProdLabel()) || m.find()){
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "商品编号不能为中文且不能为空");
                }
                rightCell = new PdfPCell();
                Image codeImage = BarcodeUtil.generateBarcodePrefixSuffix(cb, p.getProdLabel(), 72, 24);
                Phrase imageP = new Phrase("", fontChinese);
                //自己调整偏移值 主要是负值往下
                imageP.add(new Chunk(codeImage, 15, -4));
                String textNmShow ="商品名称:" + (StringUtils.isNotEmpty(p.getProdNm()) ? p.getProdNm() : "");
                String textUnitShow ="计量单位:" + (StringUtils.isNotEmpty(p.getUnitNm()) ? p.getUnitNm() : "") ;
                String textSpecShow ="规格: " + (StringUtils.isNotEmpty(p.getSpec()) ? p.getSpec() : "");
                String textModelAndUnitShow ="型号:" + (StringUtils.isNotEmpty(p.getModel()) ? p.getModel() : "") +
                        "  " + textUnitShow;
                //Chunk chunkCd = new Chunk(textCdShow,fontChinese);
                Chunk chunkNm = new Chunk(textNmShow,fontChinese);
                //Chunk chunkUnit = new Chunk(textUnitShow,fontChinese);
                Chunk chunkSpec = new Chunk(textSpecShow,fontChinese);
                Chunk chunkModel = new Chunk(textModelAndUnitShow,fontChinese);
                rightCell = new PdfPCell();
                //imageP.setLeading(2f,1.5f);
                rightCell.addElement(imageP);
                //rightCell.addElement(chunkCd);
                rightCell.addElement(new Chunk("  ",fontChinese));
                rightCell.addElement(chunkNm);
                //rightCell.addElement(chunkUnit);
                rightCell.addElement(chunkSpec);
                rightCell.addElement(chunkModel);
                //false自动换行
                rightCell.setNoWrap(false);
                //行间距
                //rightCell.setLeading(40f,10.0f);
                rightCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                rightCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                rightCell.setFixedHeight(70.0f);
                //rightCell.setPadding(4.0f);//填充
                headerTable.addCell(rightCell);
            }
            if(productExList.size()%2 == 1){
                rightCell = new PdfPCell();
                new Chunk("END",fontChinese);
                headerTable.addCell(rightCell);
            }
            document.add(headerTable);
            os.flush();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            if(Objects.nonNull(document)){
                document.close();
            }
            if (Objects.nonNull(os)) {
                os.close();
            }
        }
    }






你可能感兴趣的:(java)