欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java純代碼實現(xiàn)導出pdf

 更新時間:2023年12月28日 14:03:52   作者:Xiao5xiao122  
在項目開發(fā)中,產品的需求越來越奇葩啦,開始文件下載都是下載為excel的,做著做著需求竟然變了,要求能導出pdf,所以本文就來用Java實現(xiàn)導出pdf功能吧

java導出pdf

在項目開發(fā)中,產品的需求越來越奇葩啦,開始文件下載都是下載為excel的,做著做著需求竟然變了,要求能導出pdf。導出pdf倒也不是特別大的問題關鍵就是麻煩。

導出pdf我知道的一共有3中方法:

方法一:利用模板導出,但是首先編輯模板的工具不好找,現(xiàn)有的國外的工具要收費,所以放棄了這個。

方法二:利用HTML頁面導出,奈何自己不會寫HTML,前端忙沒時間幫忙寫。本著求人不如靠己的想法就選擇了第三種比較麻煩的方法,自己用table畫。

方法三:自己用純代碼畫格式(可調字體大小,顏色,對復雜沒有規(guī)則的數(shù)據(jù)都可以)

首先必須導入的依賴有

<!--導出pdf所需包-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.10</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

然后就是一頓代碼輸出

先把效果貼上

然后是代碼部分

@ApiOperation(value = "導出")
    @PostMapping("/download")
    @SneakyThrows(Exception.class)
    public void download(@RequestBody @Valid FumigationDTO fumigationDTO, HttpServletResponse response, HttpServletRequest request) {
        // 防止日志記錄獲取session異常
        request.getSession();
        // 設置編碼格式
        response.setContentType("application/pdf;charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("下載的PDF名稱", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".pdf");
        fumigationService.download(fumigationDTO, response);
    }

業(yè)務層

@Override
    public void download(FumigationDTO fumigationDTO, HttpServletResponse response) throws IOException {
    	//要下載的數(shù)據(jù)查詢數(shù)據(jù)部分我去掉了有需要自己根據(jù)業(yè)務取
        FumigationDowloadVO fumigationDowloadVO = new FumigationDowloadVO();
        

        // 定義全局的字體靜態(tài)變量
        Font titlefont;
        Font headfont;
        Font keyfont = null;
        Font textfont = null;
        Font content = null;
        // 最大寬度
        try {
            // 不同字體(這里定義為同一種字體:包含不同字號、不同style)
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titlefont = new Font(bfChinese, 16, Font.BOLD);
            headfont = new Font(bfChinese, 14, Font.BOLD);
            keyfont = new Font(bfChinese, 10, Font.BOLD);
            textfont = new Font(bfChinese, 15, Font.NORMAL);
            content = new Font(bfChinese, 10, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
        BaseFont bf;
        Font font = null;
        try {
            //創(chuàng)建字體
            bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
            //使用字體并給出顏色
            font = new Font(bf,20,Font.BOLD,BaseColor.BLACK);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Document document = new Document(new RectangleReadOnly(842F, 595F));
        //設置頁邊距  60:左邊距,60:右邊距,72:上邊距,72:下邊距
        document.setMargins(60, 60, 72, 72);
        try {
            PdfWriter.getInstance(document,response.getOutputStream());
            //添加頁碼
            writer.setPageEvent(new PdfPageUtil());
            //打開生成的pdf文件
            document.open();
            //設置內容
            Paragraph paragraph = new Paragraph("熏蒸備案回執(zhí)",font);
            paragraph.setAlignment(1);
            //引用字體
            document.add(paragraph);

            // 設置表格的列寬和列數(shù)
            float[] widths = {25f,25f,25f,25f,25f,25f};
            PdfPTable table = new PdfPTable(widths);
            table.setSpacingBefore(20f);
            // 設置表格寬度為100%
            table.setWidthPercentage(100.0F);
            table.setHeaderRows(1);
            table.getDefaultCell().setHorizontalAlignment(1);
            PdfPCell cell = null;
            //第一行
            cell = new PdfPCell(new Paragraph("熏蒸備案編碼",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(30);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(fumigationDowloadVO.getXzbm()));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("熏蒸備案時間",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(CheckVerifyUtil.dateToString4(fumigationDowloadVO.getSqxzrq())));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("申請備案單位",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(fumigationDowloadVO.getDwmc(),content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            //第二行
            cell = new PdfPCell(new Paragraph("熏蒸作業(yè)庫點",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(30);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(fumigationDowloadVO.getKdmc(),content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("負責人",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(fumigationDowloadVO.getFzr(),content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("聯(lián)系電話",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(fumigationDowloadVO.getFzrdh(),content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            //第三行
            cell = new PdfPCell(new Paragraph("單據(jù)狀態(tài)",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(30);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(shzt(fumigationDowloadVO.getShzt()),content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph("審核時間",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(CheckVerifyUtil.dateToString5(fumigationDowloadVO.getShsj()),content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(" ",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Paragraph(" ",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            // 設置表格的列寬和列數(shù)
            float[] widths2 = {25f,25f,25f,25f,25f,25f};
            PdfPTable table2 = new PdfPTable(widths2);
            table2.setSpacingBefore(20f);
            // 設置表格寬度為100%
            table2.setWidthPercentage(100.0F);
            table2.setHeaderRows(1);
            table2.getDefaultCell().setHorizontalAlignment(1);

            //人員列表-第四行
            cell = new PdfPCell(new Paragraph("姓名",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(20);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("職務",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("職業(yè)資格",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("身體狀況",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("熏蒸任務分工",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);

            cell = new PdfPCell(new Paragraph("是否外包",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);
            //人員列表數(shù)據(jù)-第五行
            if(fumigationDowloadVO.getProples().size() > 0){
                for (RecordFumigationPeople prople : fumigationDowloadVO.getProples()) {
                    PdfPCell cell1 = new PdfPCell(new Paragraph(prople.getXm(), content));
                    PdfPCell cell2 = new PdfPCell(new Paragraph(prople.getZw(), content));
                    PdfPCell cell3 = new PdfPCell(new Paragraph(prople.getZyzg(), content));
                    PdfPCell cell4 = new PdfPCell(new Paragraph(prople.getStzk(), content));
                    PdfPCell cell5 = new PdfPCell(new Paragraph(prople.getXzrwfg(), content));
                    PdfPCell cell6 = new PdfPCell(new Paragraph(prople.getSfwb(), content));

                    //單元格對齊方式
                    cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    cell1.setFixedHeight(20);
                    //單元格垂直對齊方式
                    cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    table2.addCell(cell1);
                    table2.addCell(cell2);
                    table2.addCell(cell3);
                    table2.addCell(cell4);
                    table2.addCell(cell5);
                    table2.addCell(cell6);
                }
            }

            // 設置表格的列寬和列數(shù)
            float[] widths3 = {25f,25f,25f,25f,25f};
            PdfPTable table3 = new PdfPTable(widths3);
            table3.setSpacingBefore(20f);
            // 設置表格寬度為100%
            table3.setWidthPercentage(100.0F);
            table3.setHeaderRows(1);
            table3.getDefaultCell().setHorizontalAlignment(1);

            //實施儲糧信息
            cell = new PdfPCell(new Paragraph("倉房",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setFixedHeight(20);
            table3.addCell(cell);

            cell = new PdfPCell(new Paragraph("貨位",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table3.addCell(cell);

            cell = new PdfPCell(new Paragraph("糧食品種",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table3.addCell(cell);

            cell = new PdfPCell(new Paragraph("計劃熏蒸開始時間",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table3.addCell(cell);

            cell = new PdfPCell(new Paragraph("計劃熏蒸結束時間",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table3.addCell(cell);

            if(fumigationDowloadVO.getDtls().size() > 0){
                for (RecordFumigationDtlVO dtl : fumigationDowloadVO.getDtls()) {
                    PdfPCell cell1 = new PdfPCell(new Paragraph(dtl.getCfmc(), content));
                    PdfPCell cell2 = new PdfPCell(new Paragraph(dtl.getHwmc(), content));
                    PdfPCell cell3 = new PdfPCell(new Paragraph(dtl.getLspzmc(), content));
                    PdfPCell cell4 = new PdfPCell(new Paragraph(CheckVerifyUtil.dateToString4(dtl.getJhxzksrq()), content));
                    PdfPCell cell5 = new PdfPCell(new Paragraph(CheckVerifyUtil.dateToString4(dtl.getJhxzjsrq()), content));
                    //設置居中
                    cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    cell1.setFixedHeight(20);

                    cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);

                    table3.addCell(cell1);
                    table3.addCell(cell2);
                    table3.addCell(cell3);
                    table3.addCell(cell4);
                    table3.addCell(cell5);

                }
            }

            document.add(new Paragraph("\n"));
            document.add(new Paragraph("▋ 基本信息",content));
            document.add(new Paragraph("\n"));

            document.add(table);

            document.add(new Paragraph("\n"));
            document.add(new Paragraph("▋ 基本信息",content));
            document.add(new Paragraph("\n"));

            document.add(table2);

            document.add(new Paragraph("\n"));
            document.add(new Paragraph("▋ 熏蒸作業(yè)儲糧糧情",content));
            document.add(new Paragraph("\n"));

            document.add(table3);
			//關閉文檔
            document.close();


        } catch (DocumentException e) {
            e.printStackTrace();
            log.error("導出pdf失敗:{}",e);
        }
    }

(二)2023-08-24 更新導出PDF無表格

效果:內容全部為代碼實現(xiàn)

貼上代碼:

@SneakyThrows
    @PostMapping("/rectification/notice/export")
    @ApiOperation("xxxx通知導出")
    public void registrationNoticeExport(@RequestBody InspectionPlanDtlListDTO reqParam, HttpServletRequest request, HttpServletResponse response) {
        request.getSession();
        if (StringUtils.isBlank(reqParam.getId())) {
            throw new CustomException("id不能為空");
        }
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        ExpertSignInExportVO vo = inspectionProblemService.registrationNoticeExport(reqParam.getId());
        if(NoticeCoeEnum.getIdList().contains(vo.getId())){
            vo.setDate("2023年08月18日");
        }else {
            vo.setDate(DateUtil.date().toString(DatePattern.CHINESE_DATE_PATTERN));
        }
        // 檢查單位
        List<InspectionPlanUnitVO> planUnitList = inspectionPlanUnitRelationMapper.selectByPlanId(vo.getPlanId());
        vo.setInspectionCompany(planUnitList.stream().map(InspectionPlanUnitVO::getUnitName).collect(Collectors.joining("、")));

        vo.setYear(year);

        Field[] fields = vo.getClass().getDeclaredFields();
        HashMap<String, String> dataMap = new HashMap<>(fields.length);
        for (Field field : fields) {
            field.setAccessible(true);
            dataMap.put("${" + field.getName() + "}", String.valueOf(field.get(vo)));
        }
        if (StringUtils.isNotBlank(vo.getInspectionTeamLeader()) || StringUtils.isNotBlank(vo.getInspectorPhone())) {
            dataMap.put("${inspectionTeamLeaderInfo}", String.format("(聯(lián)系人:%s;聯(lián)系電話:%s)",
                    vo.getInspectionTeamLeader(), StringUtils.isNotBlank(vo.getOfficePhone()) ? vo.getOfficePhone() : vo.getInspectorPhone()));
        }
        dataMap.put("${attachmentNameStr}", "    " + String.join("\n    ", vo.getAttachmentNameList()));

        //導出pdf
        PdfUtil.setResponseContentType(response, vo.getInspectedEnterprise() + vo.getPlanName() + "檢查整改通知" + year);
//        PdfUtil.fillWordTemplate("template/rectification_notice.pdf", dataMap, response);
        PdfUtil.downloadPdf(dataMap,response);

//            String fileName = vo.getInspectedEnterprise() + vo.getPlanName() + "檢查整改通知" + year;
//          //導出excel
//        WordUtil.setResponseContentType(response, fileName);
//        WordUtil.fillWordTemplate("template/rectification_notice.docx", dataMap, response.getOutputStream(),Boolean.TRUE);
    }

導出pdf工具


public static void setResponseContentType(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        response.setContentType("application/pdf");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".pdf");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    }


public static void downloadPdf(Map<String,String> dataMap, HttpServletResponse response){
        // 定義全局的字體靜態(tài)變量
        Font titlefont;
        Font headfont;
        Font keyfont = null;
        Font textfont = null;
        Font content = null;
        Font space = null;
        Font space1 = null;
        Font space2 = null;
        Font space3 = null;
        // 最大寬度
        try {
            // 不同字體(這里定義為同一種字體:包含不同字號、不同style)
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titlefont = new Font(bfChinese, 16, Font.BOLD);
            headfont = new Font(bfChinese, 14, Font.BOLD);
            keyfont = new Font(bfChinese, 22, Font.BOLD);
            textfont = new Font(bfChinese, 15, Font.NORMAL);
            content = new Font(bfChinese, 16, Font.NORMAL);
            space = new Font(bfChinese, 5, Font.NORMAL);
            space1 = new Font(bfChinese, 20, Font.NORMAL);
            space2 = new Font(bfChinese, 20, Font.NORMAL);
            space3 = new Font(bfChinese, 3, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
        BaseFont bf;
        Font font = null;
        try {
            //創(chuàng)建字體
            bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
            //使用字體并給出顏色
            font = new Font(bf,36,Font.BOLD, BaseColor.RED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Document document = new Document(new Rectangle(com.itextpdf.text.PageSize.A4));

        try {
            com.itextpdf.text.pdf.PdfWriter.getInstance(document, response.getOutputStream());
            //打開PDF文件
            document.open();
            //設置內容
            Paragraph paragraph = new Paragraph("深圳市糧食和物資儲備保障中心", font);
            //居中設置
            paragraph.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph);

            //頁眉橫線
            document.add(new Paragraph("\n", space2));
            LineSeparator line = new LineSeparator(3f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
            document.add(line);
            document.add(new Paragraph("\n", space3));
            LineSeparator lineStart = new LineSeparator(1f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
            document.add(lineStart);

            document.add(new Paragraph("\n", space));
            String text = "深儲整改〔 " + dataMap.get("${year}") + "〕" + dataMap.get("${sort}") + "號";
            Paragraph paragraph0 = new Paragraph(text, content);
            paragraph0.setAlignment(Element.ALIGN_RIGHT);
            document.add(paragraph0);

            document.add(new Paragraph("\n"));
            Paragraph paragraph1 = new Paragraph(dataMap.get("${inspectionCompany}") + "關于", keyfont);
            paragraph1.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph1);

            document.add(new Paragraph("\n", space));
            String concent = dataMap.get("${planName}") + "發(fā)現(xiàn)問題整改的通知";
            Paragraph paragraph2 = new Paragraph(concent, keyfont);
            paragraph2.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph2);

            document.add(new Paragraph("\n"));
            Paragraph paragraph3 = new Paragraph(dataMap.get("${qymc}") + ":", content);
            paragraph3.setAlignment(Element.ALIGN_LEFT);
            document.add(paragraph3);

            document.add(new Paragraph("\n", space));
            String concent1 = "             現(xiàn)將" + dataMap.get("${kdmc}") + dataMap.get("${planName}")
                    + "檢查發(fā)現(xiàn)問題及整改要求轉給你司,請嚴格按期限要求進行整改,并將整改落實情況(含佐證材料及附件)通過深圳市糧食和物資儲備信息管理平臺反饋我中心。";
            Paragraph paragraph4 = new Paragraph(concent1, content);
            //設置首行縮進
            paragraph4.setIndentationRight(2);
            document.add(paragraph4);

            document.add(new Paragraph("\n", space));
            Paragraph paragraph5 = new Paragraph("              特此通知。", content);
            paragraph5.setIndentationRight(2);//右縮進2格
            document.add(paragraph5);

            document.add(new Paragraph("\n", space1));
            document.add(new Paragraph("\n", space1));
            //附件
            Paragraph paragraph6 = new Paragraph("              附件:", content);
            paragraph6.setIndentationRight(2);//右縮進2格
            document.add(paragraph6);

            document.add(new Paragraph("\n", space));
            Paragraph paragraph7 = new Paragraph(dataMap.get("${attachmentNameStr}"), content);
            document.add(paragraph7);

            document.add(new Paragraph("\n", space1));
            document.add(new Paragraph("\n", space1));
            document.add(new Paragraph("\n", space1));

            //日期
            Paragraph paragraph8 = new Paragraph(dataMap.get("${date}"), content);
            //向右
            paragraph8.setAlignment(Element.ALIGN_RIGHT);
            document.add(paragraph8);

            document.add(new Paragraph("\n", space1));
            //落款
            Paragraph paragraph9 = new Paragraph(dataMap.get("${inspectionTeamLeaderInfo}"), content);
            paragraph9.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph9);

            //頁尾橫線
            document.add(new Paragraph("\n", space2));
            document.add(new Paragraph("\n", space2));
            LineSeparator lineEnd = new LineSeparator(3f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
            document.add(lineEnd);
            document.add(new Paragraph("\n", space3));
            LineSeparator lineEnd1 = new LineSeparator(1f, 100, BaseColor.RED, Element.ALIGN_CENTER, 0f);
            document.add(lineEnd1);


            //關閉文檔
            document.close();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("導出pdf失?。簕}", e);
        }


    }

更新于2023-12-15,更新內容:導出PDF增加頁碼和設置頁邊距

以下為效果圖:

package com.sydata.zt.common.pdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.IOException;

/**
 * @Author xx
 * @Date 2023/12/15 10:05
 * @Description: 導出pdf添加頁數(shù)
 * @Version 1.0
 */
public class PdfPageUtil extends PdfPageEventHelper {

    /**
     * 頁眉
     */
    //public String header = "itext測試頁眉";

    /**
     * 文檔字體大小,頁腳頁眉最好和文本大小一致
     */
    public int presentFontSize = 15;

    /**
     * 文檔頁面大小,最好前面?zhèn)魅?,否則默認為A4紙張
     */
    public Rectangle pageSize = PageSize.A4;

    // 模板
    public PdfTemplate total;

    // 基礎字體對象
    public BaseFont bf = null;

    // 利用基礎字體生成的字體對象,一般用于生成中文文字
    public Font fontDetail = null;

    /**
     *
     *  無參構造方法.
     *
     */
    public PdfPageUtil() {

    }

    /**
     *
     *  構造方法.
     *
     * @param
     *
     * @param presentFontSize
     *            數(shù)據(jù)體字體大小
     * @param pageSize
     *            頁面文檔大小,A4,A5,A6橫轉翻轉等Rectangle對象
     */
    public PdfPageUtil( int presentFontSize, Rectangle pageSize) {
        this.presentFontSize = presentFontSize;
        this.pageSize = pageSize;
    }

    public void setPresentFontSize(int presentFontSize) {
        this.presentFontSize = presentFontSize;
    }

    /**
     *
     * 文檔打開時創(chuàng)建模板
     */
    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {
    	// 共 頁 的矩形的長寬高
        total = writer.getDirectContent().createTemplate(50, 50);
    }

    /**
     *
     *關閉每頁的時候,寫入頁眉,寫入'第幾頁共'這幾個字。
     */
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        this.addPage(writer, document);
    }

    //加分頁
    public void addPage(PdfWriter writer, Document document){
        //設置分頁頁眉頁腳字體
        try {
            if (bf == null) {
                bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
            }
            if (fontDetail == null) {
                fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 數(shù)據(jù)體字體
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 1.寫入頁眉
//        ColumnText.showTextAligned(writer.getDirectContent(),
//                Element.ALIGN_LEFT, new Phrase(header, fontDetail),
//                document.left(), document.top() + 20, 0);
        // 2.寫入前半部分的 第 X頁/共
        int pageS = writer.getPageNumber();
        //String foot1 = "第 " + pageS + " 頁 /共";
        String foot1 = pageS  +"/";
        Phrase footer = new Phrase(foot1, fontDetail);

        // 3.計算前半部分的foot1的長度,后面好定位最后一部分的'Y頁'這倆字的x軸坐標,字體長度也要計算進去 = len
        float len = bf.getWidthPoint(foot1, presentFontSize);

        // 4.拿到當前的PdfContentByte
        PdfContentByte cb = writer.getDirectContent();

        // 5.寫入頁腳1,x軸就是(右margin+左margin + right() -left()- len)/2.0F
        ColumnText
                .showTextAligned(
                        cb,
                        Element.ALIGN_CENTER,
                        footer,
                        (document.rightMargin() + document.right()
                                + document.leftMargin() - document.left() - len) / 2.0F ,
                        document.bottom() - 10, 0);
        cb.addTemplate(total, (document.rightMargin() + document.right()
                        + document.leftMargin() - document.left()) / 2.0F ,
                document.bottom() - 10); // 調節(jié)模版顯示的位置

    }

//    //加水印
//    public void addWatermark(PdfWriter writer){
//        // 水印圖片
//        Image image;
//        try {
//            image = Image.getInstance("./web/images/001.jpg");
//            PdfContentByte content = writer.getDirectContentUnder();
//            content.beginText();
//            // 開始寫入水印
//            for(int k=0;k<5;k++){
//                for (int j = 0; j <4; j++) {
//                    image.setAbsolutePosition(150*j,170*k);
//                    content.addImage(image);
//                }
//            }
//            content.endText();
//        } catch (IOException | DocumentException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//    }

    /**
     *
     * 關閉文檔時,替換模板,完成整個頁眉頁腳組件
     */
    @Override
    public void onCloseDocument(PdfWriter writer, Document document) {
        // 關閉文檔的時候,將模板替換成實際的 Y 值
        total.beginText();
        // 生成的模版的字體、顏色
        total.setFontAndSize(bf, presentFontSize);
        //頁腳內容拼接  如  第1頁/共2頁
        //String foot2 = " " + (writer.getPageNumber()) + " 頁";
        //頁腳內容拼接  如  第1頁/共2頁
        String foot2 = String.valueOf(writer.getPageNumber());
        // 模版顯示的內容
        total.showText(foot2);
        total.endText();
        total.closePath();
    }
}

然后就可以了直接導出pdf。

以上就是Java純代碼實現(xiàn)導出pdf的詳細內容,更多關于Java導出pdf的資料請關注腳本之家其它相關文章!

相關文章

  • SpringBoot啟動時加載指定方法的方式小結

    SpringBoot啟動時加載指定方法的方式小結

    本文主要給大家介紹了Spring Boot項目啟動時加載指定方法都有哪些方式的,文中給大家介紹了五種常用的方式,有詳細的代碼示例,具有一定的參考價值,需要的朋友可以參考下
    2023-08-08
  • Java無需解壓直接讀取ZIP壓縮包里的文件及內容

    Java無需解壓直接讀取ZIP壓縮包里的文件及內容

    最近開發(fā)的時候遇到要獲取到zip壓縮包里面的文件內容,解決方案就是通過ZipInputStream來讀取,下面通過實例代碼介紹Java無需解壓直接讀取ZIP壓縮包里的文件及內容,感興趣的朋友跟隨小編一起看看吧
    2024-03-03
  • Java集合中的WeakHashMap、IdentityHashMap、EnumMap詳解

    Java集合中的WeakHashMap、IdentityHashMap、EnumMap詳解

    這篇文章主要介紹了Java集合中的WeakHashMap、IdentityHashMap、EnumMap詳解,HashMap的key保留了對實際對象的強引用,這意味著只要HashMap對象不被銷毀,還HashMap的所有key所引用的對象就不會被垃圾回收,需要的朋友可以參考下
    2023-09-09
  • Spring MessageSource獲取消息不符合預期的問題解決方案

    Spring MessageSource獲取消息不符合預期的問題解決方案

    最近我參與的產品要做國際化支持,選擇了用Spring MessageSource來實現(xiàn),這個Spring 框架提供的工具使用很簡單,網上有各種教程文章,這里不做贅述,只說一個實際遇到的問題及解決方案,需要的朋友可以參考下
    2024-01-01
  • Ubuntu快速安裝jdk的教程

    Ubuntu快速安裝jdk的教程

    這篇文章主要為大家詳細介紹了Ubuntu快速安裝jdk的教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • SpringCloud Finchley Gateway 緩存請求Body和Form表單的實現(xiàn)

    SpringCloud Finchley Gateway 緩存請求Body和Form表單的實現(xiàn)

    在接入Spring-Cloud-Gateway時,可能有需求進行緩存Json-Body數(shù)據(jù)或者Form-Urlencoded數(shù)據(jù)的情況。這篇文章主要介紹了SpringCloud Finchley Gateway 緩存請求Body和Form表單的實現(xiàn),感興趣的小伙伴們可以參考一下
    2019-01-01
  • SpringBoot項目打包部署到Tomcat的操作流程

    SpringBoot項目打包部署到Tomcat的操作流程

    在最近一個項目中,維護行里一個年代較為久遠的單體項目,需要將項目打包放到的tomcat服務器下運行,所以本文就給大家介紹一下SpringBoot項目打包部署到Tomcat的流程步驟,需要的朋友可以參考下
    2023-08-08
  • Java后臺判斷ajax請求及處理過程詳解

    Java后臺判斷ajax請求及處理過程詳解

    這篇文章主要介紹了Java后臺判斷ajax請求及處理過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-03-03
  • Lucene?索引刪除策略源碼解析

    Lucene?索引刪除策略源碼解析

    這篇文章主要為大家介紹了Lucene?索引刪除策略源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03
  • 23種設計模式(14)java迭代器模式

    23種設計模式(14)java迭代器模式

    這篇文章主要為大家詳細介紹了23種設計模式之java迭代器模式,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-12-12

最新評論