springboot exports pdf to front-end browser for preview download

  1. I won’t say much about painting. I’ll upload it successfully first and then export the pdf file.

     2.maven dependency

       <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.4</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

    3. Tool class method, please note that due to business needs, when the data exceeds one page, the template in the header should still be the same when changing to the next page, so I use 27 lines to cut one page.

 /**
     *
     *  创建周检pdf
     * @param products
     */
    public static void disposeWeekPDF (List<Tool> products, HttpServletResponse response) {
        Document document = new Document(PageSize.A4);
        try {
            //下面字体为windows自带的字体 在linux下可能会失效
            Font font = new Font(BaseFont.createFont("C://Windows//Fonts//simfang.ttf", BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED));
//            String filename = "d://erp//aaa.pdf";
//            PdfWriter.getInstance(document, new FileOutputStream(filename));//可为直接本地文件路径
            ByteArrayOutputStream ba = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, response.getOutputStream());
            document.open();

            createWeekPDFTitle(document);
            document.add(Chunk.NEWLINE);
            PdfPTable table = new PdfPTable(7);//生成一个 7列的表格
            createWeekTable(table,font);

            PdfPCell cell;
            int size = 20;
            int count = 1;
            int listSize = products.size();

            for(int i = 0; i< listSize;i++) {
                /**
                 *  一页只有26行数据
                 * 当为同一个部门,并且行数大于27时换一页,相当于每27行换一页
                 * 当为不同部门时,换一页
                 */
                int num = count /27;
                if (num ==1) {

                    //换下一页前必须把表格内容添加到文档中
                    document.add(table);
                    document.add(Chunk.NEWLINE);
                    document.add(new Paragraph("工具室、仪表负责人________                                          鉴定员_________",font));
                    Paragraph date =  new Paragraph("                                                                     年   月   日",font);
                    document.add(date);

                    //换下一页
                    document.newPage();

                    createWeekPDFTitle(document);
                    document.add(Chunk.NEWLINE);
                    table = new PdfPTable(7);//生成一个 7列的表格
                    createWeekTable(table,font);
                    count =1;
                }


                cell = new PdfPCell(new Phrase(Integer.valueOf(i+1).toString(),font));
                cell.setFixedHeight(size); //设置高度
                table.addCell(cell);

                cell = new PdfPCell(new Phrase(products.get(i).getCode(),font));
                cell.setFixedHeight(size);
                table.addCell(cell);

                cell = new PdfPCell(new Phrase(products.get(i).getName()+"",font));
                cell.setFixedHeight(size);
                table.addCell(cell);

                cell = new PdfPCell(new Phrase(products.get(i).getMeasureRange()+"",font));
                cell.setFixedHeight(size);
                table.addCell(cell);

                cell = new PdfPCell(new Phrase(products.get(i).getModel()+"",font));
                cell.setFixedHeight(size);
                table.addCell(cell);

                cell = new PdfPCell(new Phrase(products.get(i).getFactoryCode()+"",font));
                cell.setFixedHeight(size);
                table.addCell(cell);

                cell = new PdfPCell(new Phrase(products.get(i).getOriginalCode()+"",font));
                cell.setFixedHeight(size);
                table.addCell(cell);

                count ++;
            }

            //当最后一页,或者第一页数据不足26条时,创建空单元格,补齐
            //需要补齐的数量
            int fillNum = 0;
            if (listSize < 26) {
                fillNum = 26 - listSize-1;
            }else if (listSize > 26) {
                fillNum = listSize % 26 ;
                fillNum = 26 - fillNum - 3;
            }

            if (fillNum > 0) {
                for (int i = 0; i< fillNum;i++) {
                    cell = new PdfPCell(new Phrase("",font));//产品编号
                    cell.setFixedHeight(size); //设置高度
                    table.addCell(cell);

                    cell = new PdfPCell(new Phrase("",font));//产品编号
                    cell.setFixedHeight(size); //设置高度
                    table.addCell(cell);

                    cell = new PdfPCell(new Phrase("",font));//产品编号
                    cell.setFixedHeight(size); //设置高度
                    table.addCell(cell);

                    cell = new PdfPCell(new Phrase("",font));//产品编号
                    cell.setFixedHeight(size); //设置高度
                    table.addCell(cell);

                    cell = new PdfPCell(new Phrase("",font));//产品编号
                    cell.setFixedHeight(size); //设置高度
                    table.addCell(cell);


                    cell = new PdfPCell(new Phrase("",font));//产品编号
                    cell.setFixedHeight(size); //设置高度
                    table.addCell(cell);

                    cell = new PdfPCell(new Phrase("",font));//产品编号
                    cell.setFixedHeight(size); //设置高度
                    table.addCell(cell);

                    cell = new PdfPCell(new Phrase("",font));//产品编号
                    cell.setFixedHeight(size); //设置高度
                    table.addCell(cell);

                }
            }

            System.out.println(listSize);
            System.out.println(fillNum);

            document.add(table);
            document.add(Chunk.NEWLINE);
            document.add(new Paragraph("工具室、仪表负责人________                                          鉴定员_________",font));
            Paragraph date =  new Paragraph("                                                                     年   月   日",font);
            document.add(date);


        }catch (Exception e) {
            e.printStackTrace();
        }  finally {
            document.close();
        }

    }


    /**
     * 生成周检pdf头部内容
     */
    public static void createWeekPDFTitle(Document document ){
        //下面的结果没有生效 中文文字没出来
        try {
            BaseFont bf =  BaseFont.createFont("C://Windows//Fonts//simfang.ttf", BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);

            Font font = new Font(bf);

            //标题字体
            Font titleFont = new Font(bf, 25F, 0);
            document.add(new Paragraph("QR-4.16.1-01-02-211",font));

            Font FontProve = new Font(bf, 15F, 0);
            Paragraph p = new Paragraph("2021 年 9 月 量具仪表周期检定通知单",titleFont);
            p.setAlignment(Element.ALIGN_CENTER);
            document.add(p);

            //定义带下划线字体
            Font underline = new Font(bf, 15, Font.UNDERLINE);
            Chunk chunk = new Chunk("技术部 ");
            chunk.setFont(underline);

            Paragraph officeName = new Paragraph(" ",FontProve);
            officeName.add(chunk);
            officeName.add("你部受控之量具、仪表将到周期检定日期。请接到通知后_____天内将如下量具、仪表送往计量室进行检定为盼。");
            document.add(officeName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 生成周检pdf表格首行文字
     * @param table
     * @param font
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public static PdfPTable createWeekTable(PdfPTable table,Font font) throws IOException, DocumentException {

        int headerwidths[] = { 10, 10, 10, 10,10, 10, 10}; // percentage
        table.setWidths(headerwidths);
        table.setWidthPercentage(100);
        table.getDefaultCell().setPadding(3);
        table.getDefaultCell().setBorderWidth(3);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

        table.addCell(new PdfPCell(new Phrase("序号",font)));
        table.addCell(new PdfPCell(new Phrase("器具编码",font)));
        table.addCell(new PdfPCell(new Phrase("器具名称",font)));
        table.addCell(new PdfPCell(new Phrase("测量范围",font)));
        table.addCell(new PdfPCell(new Phrase("器具型号",font)));
        table.addCell(new PdfPCell(new Phrase("出厂编号",font)));
        table.addCell(new PdfPCell(new Phrase("原编码",font)));
        return table;
    }

        4. The services class method is called. The data in toolList is queried from the database. I will not put the code out.

		try{
			// 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
			String date = parseDateToStr(YYYY_MM_DD_HH_MM_SS_T,new Date());
			String fileName ="计量器具周检"+ date+".pdf";
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/pdf");
			//打开浏览器窗口预览文件
			response.setHeader("Content-Disposition","filename=" + new String(fileName.getBytes(), "iso8859-1"));
			//直接下载
			//response.setHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes(), "iso8859-1"));

            ToolPDFUtils.disposeWeekPDF(toolList,response);
		}catch (Exception e){
			e.printStackTrace();
		}

      5.controller method

	/**
	 *  打印 本月计量器具周检
	 * @param tool
	 * @param request
	 * @param response
	 * @param model
	 */
	@ResponseBody
	@RequestMapping(value = "weekTookPrintPDF")
	public void weekTookPrintPDF (Tool tool, HttpServletRequest request, HttpServletResponse response, Model model) {
		 toolService.weekTookPrintPDF(tool, response);

	}

       6. Front-end js, url is the path of this controller. After triggering the print button, the browser will open a new tab to display the pdf file.

      window.open(url);

     The method does not reference the template, but directly generates the file. I have seen many on the Internet that reference the template first and then write data into the template. Considering that it is not easy to maintain later, I write the code directly.

Guess you like

Origin blog.csdn.net/qq_33278354/article/details/120157102