亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java純代碼實(shí)現(xiàn)導(dǎo)出pdf

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

java導(dǎo)出pdf

在項(xiàng)目開發(fā)中,產(chǎn)品的需求越來(lái)越奇葩啦,開始文件下載都是下載為excel的,做著做著需求竟然變了,要求能導(dǎo)出pdf。導(dǎo)出pdf倒也不是特別大的問(wèn)題關(guān)鍵就是麻煩。

導(dǎo)出pdf我知道的一共有3中方法:

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

方法二:利用HTML頁(yè)面導(dǎo)出,奈何自己不會(huì)寫HTML,前端忙沒(méi)時(shí)間幫忙寫。本著求人不如靠己的想法就選擇了第三種比較麻煩的方法,自己用table畫。

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

首先必須導(dǎo)入的依賴有

<!--導(dǎo)出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 = "導(dǎo)出")
    @PostMapping("/download")
    @SneakyThrows(Exception.class)
    public void download(@RequestBody @Valid FumigationDTO fumigationDTO, HttpServletResponse response, HttpServletRequest request) {
        // 防止日志記錄獲取session異常
        request.getSession();
        // 設(shè)置編碼格式
        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è)務(wù)層

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

        // 定義全局的字體靜態(tài)變量
        Font titlefont;
        Font headfont;
        Font keyfont = null;
        Font textfont = null;
        Font content = null;
        // 最大寬度
        try {
            // 不同字體(這里定義為同一種字體:包含不同字號(hào)、不同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));
        //設(shè)置頁(yè)邊距  60:左邊距,60:右邊距,72:上邊距,72:下邊距
        document.setMargins(60, 60, 72, 72);
        try {
            PdfWriter.getInstance(document,response.getOutputStream());
            //添加頁(yè)碼
            writer.setPageEvent(new PdfPageUtil());
            //打開生成的pdf文件
            document.open();
            //設(shè)置內(nèi)容
            Paragraph paragraph = new Paragraph("熏蒸備案回執(zhí)",font);
            paragraph.setAlignment(1);
            //引用字體
            document.add(paragraph);

            // 設(shè)置表格的列寬和列數(shù)
            float[] widths = {25f,25f,25f,25f,25f,25f};
            PdfPTable table = new PdfPTable(widths);
            table.setSpacingBefore(20f);
            // 設(shè)置表格寬度為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("熏蒸備案時(shí)間",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("申請(qǐng)備案單位",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è)庫(kù)點(diǎn)",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("負(fù)責(zé)人",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("審核時(shí)間",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è)置表格的列寬和列數(shù)
            float[] widths2 = {25f,25f,25f,25f,25f,25f};
            PdfPTable table2 = new PdfPTable(widths2);
            table2.setSpacingBefore(20f);
            // 設(shè)置表格寬度為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("職務(wù)",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("熏蒸任務(wù)分工",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));

                    //單元格對(duì)齊方式
                    cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    cell1.setFixedHeight(20);
                    //單元格垂直對(duì)齊方式
                    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è)置表格的列寬和列數(shù)
            float[] widths3 = {25f,25f,25f,25f,25f};
            PdfPTable table3 = new PdfPTable(widths3);
            table3.setSpacingBefore(20f);
            // 設(shè)置表格寬度為100%
            table3.setWidthPercentage(100.0F);
            table3.setHeaderRows(1);
            table3.getDefaultCell().setHorizontalAlignment(1);

            //實(shí)施儲(chǔ)糧信息
            cell = new PdfPCell(new Paragraph("倉(cāng)房",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("計(jì)劃熏蒸開始時(shí)間",content));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table3.addCell(cell);

            cell = new PdfPCell(new Paragraph("計(jì)劃熏蒸結(jié)束時(shí)間",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));
                    //設(shè)置居中
                    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è)儲(chǔ)糧糧情",content));
            document.add(new Paragraph("\n"));

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


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

(二)2023-08-24 更新導(dǎo)出PDF無(wú)表格

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

貼上代碼:

@SneakyThrows
    @PostMapping("/rectification/notice/export")
    @ApiOperation("xxxx通知導(dǎo)出")
    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()));

        //導(dǎo)出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;
//          //導(dǎo)出excel
//        WordUtil.setResponseContentType(response, fileName);
//        WordUtil.fillWordTemplate("template/rectification_notice.docx", dataMap, response.getOutputStream(),Boolean.TRUE);
    }

導(dǎo)出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 {
            // 不同字體(這里定義為同一種字體:包含不同字號(hào)、不同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();
            //設(shè)置內(nèi)容
            Paragraph paragraph = new Paragraph("深圳市糧食和物資儲(chǔ)備保障中心", font);
            //居中設(shè)置
            paragraph.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph);

            //頁(yè)眉橫線
            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 = "深儲(chǔ)整改〔 " + dataMap.get("${year}") + "〕" + dataMap.get("${sort}") + "號(hào)";
            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}") + "關(guān)于", keyfont);
            paragraph1.setAlignment(Element.ALIGN_CENTER);
            document.add(paragraph1);

            document.add(new Paragraph("\n", space));
            String concent = dataMap.get("${planName}") + "發(fā)現(xiàn)問(wè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)問(wèn)題及整改要求轉(zhuǎn)給你司,請(qǐng)嚴(yán)格按期限要求進(jìn)行整改,并將整改落實(shí)情況(含佐證材料及附件)通過(guò)深圳市糧食和物資儲(chǔ)備信息管理平臺(tái)反饋我中心。";
            Paragraph paragraph4 = new Paragraph(concent1, content);
            //設(shè)置首行縮進(jìn)
            paragraph4.setIndentationRight(2);
            document.add(paragraph4);

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

            document.add(new Paragraph("\n", space1));
            document.add(new Paragraph("\n", space1));
            //附件
            Paragraph paragraph6 = new Paragraph("              附件:", content);
            paragraph6.setIndentationRight(2);//右縮進(jìn)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);

            //頁(yè)尾橫線
            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);


            //關(guān)閉文檔
            document.close();

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


    }

更新于2023-12-15,更新內(nèi)容:導(dǎo)出PDF增加頁(yè)碼和設(shè)置頁(yè)邊距

以下為效果圖:

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: 導(dǎo)出pdf添加頁(yè)數(shù)
 * @Version 1.0
 */
public class PdfPageUtil extends PdfPageEventHelper {

    /**
     * 頁(yè)眉
     */
    //public String header = "itext測(cè)試頁(yè)眉";

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

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

    // 模板
    public PdfTemplate total;

    // 基礎(chǔ)字體對(duì)象
    public BaseFont bf = null;

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

    /**
     *
     *  無(wú)參構(gòu)造方法.
     *
     */
    public PdfPageUtil() {

    }

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

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

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

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

    //加分頁(yè)
    public void addPage(PdfWriter writer, Document document){
        //設(shè)置分頁(yè)頁(yè)眉頁(yè)腳字體
        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.寫入頁(yè)眉
//        ColumnText.showTextAligned(writer.getDirectContent(),
//                Element.ALIGN_LEFT, new Phrase(header, fontDetail),
//                document.left(), document.top() + 20, 0);
        // 2.寫入前半部分的 第 X頁(yè)/共
        int pageS = writer.getPageNumber();
        //String foot1 = "第 " + pageS + " 頁(yè) /共";
        String foot1 = pageS  +"/";
        Phrase footer = new Phrase(foot1, fontDetail);

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

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

        // 5.寫入頁(yè)腳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); // 調(diào)節(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();
//        }
//    }

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

然后就可以了直接導(dǎo)出pdf。

以上就是Java純代碼實(shí)現(xiàn)導(dǎo)出pdf的詳細(xì)內(nèi)容,更多關(guān)于Java導(dǎo)出pdf的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • SpringBoot啟動(dòng)時(shí)加載指定方法的方式小結(jié)

    SpringBoot啟動(dòng)時(shí)加載指定方法的方式小結(jié)

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

    Java無(wú)需解壓直接讀取ZIP壓縮包里的文件及內(nèi)容

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

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

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

    Spring MessageSource獲取消息不符合預(yù)期的問(wèn)題解決方案

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

    Ubuntu快速安裝jdk的教程

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

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

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

    SpringBoot項(xiàng)目打包部署到Tomcat的操作流程

    在最近一個(gè)項(xiàng)目中,維護(hù)行里一個(gè)年代較為久遠(yuǎn)的單體項(xiàng)目,需要將項(xiàng)目打包放到的tomcat服務(wù)器下運(yùn)行,所以本文就給大家介紹一下SpringBoot項(xiàng)目打包部署到Tomcat的流程步驟,需要的朋友可以參考下
    2023-08-08
  • Java后臺(tái)判斷ajax請(qǐng)求及處理過(guò)程詳解

    Java后臺(tái)判斷ajax請(qǐng)求及處理過(guò)程詳解

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

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

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

    23種設(shè)計(jì)模式(14)java迭代器模式

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

最新評(píng)論