springboot exporta pdf al navegador frontal para descargar una vista previa

  1. No diré mucho sobre pintura, lo subiré correctamente y luego exportaré el archivo pdf.

     2. dependencia maven

       <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. Método de clase de herramienta, tenga en cuenta que debido a las necesidades comerciales, cuando los datos exceden una página, la plantilla en el encabezado debe seguir siendo la misma al cambiar a la página siguiente, por lo que uso 27 líneas para cortar una página.

 /**
     *
     *  创建周检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. Se llama al método de la clase de servicios. Los datos en la lista de herramientas se consultan desde la base de datos. No publicaré el código.

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

      Cinco método del controlador

	/**
	 *  打印 本月计量器具周检
	 * @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, la URL es la ruta de este controlador. Después de activar el botón Imprimir, el navegador abrirá una nueva pestaña para mostrar el archivo pdf.

      window.open(url);

     El método no hace referencia a la plantilla, sino que genera archivos directamente. He visto muchos en Internet que primero hacen referencia a la plantilla y luego escriben datos en la plantilla. Considerando que no es fácil de mantener más adelante, escribo el código directamente.

Supongo que te gusta

Origin blog.csdn.net/qq_33278354/article/details/120157102
Recomendado
Clasificación