[Java] Generate barcodes in batches-itextpdf

Generate barcodes in batches
Controller

@ApiOperation("Product list generates product barcodes in batches")
    @PostMapping("/batchGenerateProdBarCode")
    public void batchGenerateProdBarCode(@RequestBody ProductListCondition productListCondition,HttpServletResponse response){<!-- -->
        importExportService.batchGenerateProdBarCode(response, productListCondition);
    }

service

 /**
     * Product list generates product barcodes in batches
     * @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, "There is no barcode to be generated, please adjust the query conditions and regenerate");
            }
            if(CollectionUtil.isNotEmpty(productExList)){<!-- -->
                String exportFileName = URLEncoder.encode("Product Barcode", "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, "There is no barcode to be generated, please adjust the query conditions and regenerate");
            }
        }catch (Exception e){<!-- -->
            e.printStackTrace();
        }
    }
/**
     * Batch generate product barcode pdf files and export them to barcode printers
     *
     * @param productExList barcode data x information
     * @param os output stream
     * @throwsIOException
     */
    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("[\\一-\\龥]");
            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, "The product number cannot be Chinese and cannot be empty");
                }
                document. newPage();
                //Create a table with one column
                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);
                //Adjust the offset value by yourself, mainly the negative value goes down
                imageP.add(new Chunk(codeImage, 5, -1));
                String textNmShow ="Product Name:" + (StringUtils.isNotEmpty(p.getProdNm()) ? p.getProdNm() : "");
                String textUnitShow ="Measurement unit:" + (StringUtils.isNotEmpty(p.getUnitNm()) ? p.getUnitNm() : "") ;
                String textSpecShow ="Specification: " + (StringUtils.isNotEmpty(p.getSpec()) ? p.getSpec() : "");
                String textModelAndUnitShow ="Model:" + (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 automatic line wrapping
                rightCell. setNoWrap(false);
                //Line spacing
                //rightCell.setLeading(40f,10.0f);
                rightCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                rightCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                rightCell.setFixedHeight(26.0f);

                //rightCell.setPadding(4.0f);//fill
                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();
            }
        }
    }

 /**
     * Batch generate product barcode pdf files and export them to A4 paper
     *
     * @param productExList barcode data x information
     * @param os output stream
     * @throwsIOException
     */
    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();
            //judgment column, a piece of data only allows a single column
            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);
            //Create a table with two columns
            PdfPTable headerTable = new PdfPTable(numColumns);
            if(numColumns == 1){<!-- -->
                headerTable.setWidthPercentage(40.0f);
            }else {<!-- -->
                headerTable.setWidthPercentage(80.0f);
            }
            PdfPCell rightCell = null;
            Pattern pat = Pattern.compile("[\\一-\\龥]");
            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, "The product number cannot be Chinese and cannot be empty");
                }
                rightCell = new PdfPCell();
                Image codeImage = BarcodeUtil.generateBarcodePrefixSuffix(cb, p.getProdLabel(), 72, 24);
                Phrase imageP = new Phrase("", fontChinese);
                //Adjust the offset value yourself, mainly negative values downwards
                imageP.add(new Chunk(codeImage, 15, -4));
                String textNmShow ="Product name:" + (StringUtils.isNotEmpty(p.getProdNm()) ? p.getProdNm() : "");
                String textUnitShow ="Unit of measurement:" + (StringUtils.isNotEmpty(p.getUnitNm()) ? p.getUnitNm() : "") ;
                String textSpecShow ="Specification: " + (StringUtils.isNotEmpty(p.getSpec()) ? p.getSpec() : "");
                String textModelAndUnitShow ="Model:" + (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 automatic line wrapping
                rightCell.setNoWrap(false);
                //Line spacing
                //rightCell.setLeading(40f,10.0f);
                rightCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                rightCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                rightCell.setFixedHeight(70.0f);
                //rightCell.setPadding(4.0f);//Padding
                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();
            }
        }
    }