Java中如何使用itext生成pdf呢?

欣喜 Java每日一问 发布时间:2024-07-29 09:29:39 阅读数:15632 1
下文笔者讲述itext工具类生成pdf的方法分享,如下所示
itext工具类生成pdf文件,
  包含“生成页眉,页脚,首页背景”

itext生成pdf的实现思路

1.引入maven依赖包
2.编写相应的工具类
3.即可生成pdf文件
例:

1.引入依赖

  <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
        <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext-asian</artifactId>
        <version>5.2.0</version>
        </dependency>

2.controller层

 @GetMapping(value = "/exportInventoryResultPDF")
	 @ApiOperation("查数据pdf导出")
	 public void getInventoryProjectResultPDF(@RequestParam("infoId") String infoId,
												   HttpServletRequest request,
												   HttpServletResponse res
												   ){
		   cmpInventoryProjectCycleService.getInventoryProjectCycleResultPDF(infoId,res);
	 }

3.service层

void getInventoryProjectCycleResultPDF(String infoId, HttpServletResponse res);

4.serviceImpl层

 @Override
    public void getInventoryProjectCycleResultPDF(String infoId, HttpServletResponse res) {
          CmpInventoryProjectReportVo cmpInventoryProjectReportVo = this.getInventoryProjectCycleReport(infoId);
        try {
            //新建document对象
            Document document = new Document(PageSize.A4);
            BufferedOutputStream outputStream = new BufferedOutputStream(res.getOutputStream());
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
            writer.setPageEvent(new MyHeaderFooter());// 页眉/页脚

            //打开文件
            document.open();
            //生成pdf
            this.generatePDF(document, cmpInventoryProjectReportVo);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 
  // 生成PDF文件
    public void generatePDF(Document document, CmpInventoryProjectReportVo cmpInventoryProjectReportVo) throws Exception {
        CmpCarbonInventoryProject project = cmpInventoryProjectReportVo.getProject();
//        Image image = Image.getInstance("https://sungrow-dev.oss-cn-beijing.aliyuncs.com/temp/d85fc9f16e415f1550a377dbec48093.jpg");


        Image image = Image.getInstance("https://sungrow-dev.oss-cn-beijing.aliyuncs.com/temp/%E7%A2%B3%E6%8E%92%E6%9F%A5pdf%E6%8A%A5%E5%91%8A%E5%B0%81%E9%9D%A2");
        image.setAlignment(Image.UNDERLYING);
        image.setAbsolutePosition(0, 0);
        image.scaleAbsolute(595, 842);
//        image.setIndentationLeft(0);
//        image.setBorderWidthLeft(0);
        //依照比例缩放
        image.scalePercent(48);
        document.add(image);
        Paragraph title = new Paragraph(project.getOrgName() + "温室气体排放报告", PdfUtils.titleFont);
        //设置段落下空白
//        title.setSpacingAfter(230f);
//        title.setPaddingTop(250f);
 //        //设置段落上空白
        title.setSpacingBefore(210f);
        title.setAlignment(1);
        CmpInventoryProjectCycle projectCycle = cmpInventoryProjectReportVo.getProjectCycle();
        document.add(title);
//        Image image = Image.getInstance("https://sungrow-dev.oss-cn-beijing.aliyuncs.com/temp/%E7%A2%B3%E6%8E%92%E6%9F%A5%E6%8A%A5%E5%91%8A%E5%B0%81%E9%9D%A2.png");
//        image.setAlignment(Image.ALIGN_CENTER);
//        //依照比例缩放
//        image.scalePercent(40);
//        document.add(image);
        PdfUtils.getPDFDes("                                                                                 报告主体:" + project.getOrgName(),document,30f,10f);
        PdfUtils.getPDFDes("                                                                                 报告周期:" + projectCycle.getInventoryCycle(),document,0f,10f);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        PdfUtils.getPDFDes("                                                                                 编制日期:" + simpleDateFormat.format(projectCycle.getCreateTime()),document,0f,0f);
        document.newPage();

        PdfUtils.setParagraphTitle("根据国家发展和改革委员会发布的《工业其他行业企业温室气体排放核算方法与报告指南(试行)》,本报告主体核算了2021年温" +
                "室气体排放量,并填写了相关数据表格,现将有关情况报告如下:",document,PdfUtils.textfont,25);

        PdfUtils.setParagraphTitle("一、企业基本信息",document,PdfUtils.headFont,0);
        PdfUtils.setParagraphTitle(projectCycle.getReportDescription(),document,PdfUtils.textfont,25f);

        // 工具类编辑表格
        PdfUtils.setParagraphTitle("二、温室气体排放情况",document,PdfUtils.headFont,25f);
        PdfPTable tableGas=PdfUtils.getTable(new float[]{150, 80, 80, 80, 80},new String[]{"单位:吨CO2当量","范围一","范围二","范围三","总计"});
        list<GhgEmissionVo> ghgEmissionVoList = cmpInventoryProjectReportVo.getGhgEmissionVoList();
        for (GhgEmissionVo ghgEmissionVo : ghgEmissionVoList) {
            tableGas.addCell(PdfUtils.createSignCell(ghgEmissionVo.getEnergyActivity_dictText(), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
            tableGas.addCell(PdfUtils.createSignCell(String.valueOf(ghgEmissionVo.getDomain1().setScale(2,BigDecimal.ROUND_HALF_UP)), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
            tableGas.addCell(PdfUtils.createSignCell(String.valueOf(ghgEmissionVo.getDomain2().setScale(2,BigDecimal.ROUND_HALF_UP)), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
            tableGas.addCell(PdfUtils.createSignCell(String.valueOf(ghgEmissionVo.getDomain3().setScale(2,BigDecimal.ROUND_HALF_UP)), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
            tableGas.addCell(PdfUtils.createSignCell(String.valueOf(ghgEmissionVo.getTotal().setScale(2,BigDecimal.ROUND_HALF_UP)), PdfUtils.textfont,Element.ALIGN_CENTER,30f));

        }
        document.add(tableGas);
        // 三、活动水平及来源说明
        PdfUtils.setParagraphTitle("三、活动水平及来源说明",document,PdfUtils.headFont,25f);
        PdfPTable tableAct=PdfUtils.getTable(new float[]{80, 80, 80, 80},new String[]{"活动类型","排放源","排放源规格","活动数据"});
        List<CmpInventoryProjectCycleInfo> cycleInfoList = cmpInventoryProjectReportVo.getCycleInfoList();
        for (CmpInventoryProjectCycleInfo cmpInventoryProjectCycleInfo : cycleInfoList) {
            tableAct.addCell(PdfUtils.createSignCell(cmpInventoryProjectCycleInfo.getEnergyActivity_dictText(), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
            tableAct.addCell(PdfUtils.createSignCell(cmpInventoryProjectCycleInfo.getEmissionName_dictText(), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
            tableAct.addCell(PdfUtils.createSignCell(cmpInventoryProjectCycleInfo.getSpecCategory_dictText(), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
            tableAct.addCell(PdfUtils.createSignCell(cmpInventoryProjectCycleInfo.getEmissionData()+" "+cmpInventoryProjectCycleInfo.getUnit(), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
        }

        document.add(tableAct);

        // 三、活动水平及来源说明
        PdfUtils.setParagraphTitle("四、排放因子数据及来源",document,PdfUtils.headFont,25f);

        // 四、排放因子数据及来源
        List<CmpFactorInfoVo> cmpFactorInfoVoList = cmpInventoryProjectReportVo.getCmpFactorInfoVoList();
        for (CmpFactorInfoVo cmpFactorInfoVo : cmpFactorInfoVoList) {
            PdfPTable tableFactor = PdfUtils.createTableFixHeight(new float[]{80, 80, 80, 80, 80, 80, 80},25f);
            tableFactor.addCell(PdfUtils.createCell(cmpFactorInfoVo.getFactorName(), PdfUtils.factorTableTitleFont, Element.ALIGN_LEFT, 7, false));
            String[] tableFactors= new String[]{"排放源","气体","地图/条件","值类型","值","单位","来源"};
            for(String factor:tableFactors) {
                tableFactor.addCell(PdfUtils.createSignCell(factor, PdfUtils.textfont, Element.ALIGN_CENTER,30f));
            }
            for (CmpFactorItem cmpFactorItem : cmpFactorInfoVo.getFactorItemList()) {
                tableFactor.addCell(PdfUtils.createSignCell(cmpFactorItem.getEmissionSource(), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
                tableFactor.addCell(PdfUtils.createSignCell(cmpFactorItem.getGasCategory(), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
                tableFactor.addCell(PdfUtils.createSignCell(cmpFactorItem.getAreaAndCondition(), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
                tableFactor.addCell(PdfUtils.createSignCell(cmpFactorItem.getValueType(), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
                tableFactor.addCell(PdfUtils.createSignCell(cmpFactorItem.getValue().stripTrailingZeros().toPlainString(), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
                tableFactor.addCell(PdfUtils.createSignCell(cmpFactorItem.getUnit(), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
                tableFactor.addCell(PdfUtils.createSignCell(cmpFactorItem.getOrigin(), PdfUtils.textfont,Element.ALIGN_CENTER,30f));
            }
            tableFactor.setSpacingAfter(25f);
            document.add(tableFactor);
        }


        // 其他未报告类型及排除原因
        PdfUtils.setParagraphTitle("五、其他未报告类型及排除原因",document,PdfUtils.headFont,25f);
        PdfUtils.setParagraphTitle("暂无",document,PdfUtils.textfont,25f);

       // 其他未报告类型及排除原因
        PdfUtils.setParagraphTitle("六、核算与报告依据",document,PdfUtils.headFont,25f);
        Set<String> factorItemOriginSet = cmpInventoryProjectReportVo.getFactorItemOriginSet();
        for (String string : factorItemOriginSet) {
            document.add(new Paragraph(string,PdfUtils.textfont));
        }
        PdfPTable tableSign=PdfUtils.getTable(new float[]{80, 80, 80},new String[]{"角色","签名","日期"});
        String[] stringTableSign = {"盘查组长","技术复核人", "批准人"};
        for (int i = 0; i < stringTableSign.length; i++) {
            tableSign.addCell(PdfUtils.createSignCell(stringTableSign[i], PdfUtils.textfont,Element.ALIGN_CENTER,30f));
            tableSign.addCell(PdfUtils.createSignCell("", PdfUtils.textfont,Element.ALIGN_CENTER,30f));
            tableSign.addCell(PdfUtils.createSignCell("", PdfUtils.textfont,Element.ALIGN_CENTER,30f));
        }
        tableSign.setSpacingBefore(25f);
        document.add(tableSign);
    }

PDFUtils工具类

package org.jeecg.modules.cm.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.cm.service.impl.CmpInventoryProjectCycleServiceImpl;
import org.jeecg.modules.cm.vo.CmpInventoryProjectReportVo;


public class PdfUtils {
    // 定义全局的字体静态变量
    public static Font titleFont;
    public static Font headFont;
    public static Font keyfont;
    public static Font textfont;
    public static Font factorTableTitleFont;
    public static Font desfont;
    // 最大宽度
    public static int maxWidth = 520;

    // 静态代码块
    static {
        try {
            // 不同字体(这里定义为同一种字体:包含不同字号、不同style)
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titleFont = new Font(bfChinese, 28, Font.BOLD);
            headFont = new Font(bfChinese, 14, Font.BOLD);
            keyfont = new Font(bfChinese, 6, Font.BOLD);
            textfont = new Font(bfChinese, 10, Font.NORMAL);
            desfont = new Font(bfChinese, 12, Font.NORMAL);
            factorTableTitleFont = new Font(bfChinese, 12, Font.BOLD);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void setParagraphTitle(String paragraphTitle,Document document,Font font,float spacing) throws DocumentException {
        //生成段落
        Paragraph paragraph = new Paragraph(paragraphTitle, font);
        //下留空格25f
        paragraph.setSpacingAfter(spacing);
        document.add(paragraph);
        //设置文字居中 0靠左   1,居中     2,靠右
        //  paragraph.setAlignment(0);
    }



/**------------------------创建表格单元格的方法start----------------------------*/
    /**
     * 创建单元格(指定字体)
     *
     * @param value
     * @param font
     * @return
     */
    public static PdfPCell createCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 创建单元格(指定字体、水平..)
     *
     * @param value
     * @param font
     * @param align
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 创建单元格(指定字体、水平..)
     *
     * @param value
     * @param font
     * @param align
     * @return
     */
    public static PdfPCell createSignCell(String value, Font font, int align,float height) {
        PdfPCell cell = new PdfPCell();
        cell.setMinimumHeight(height);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 创建单元格(指定字体、水平居..、单元格跨x列合并)
     *
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, int colspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 创建单元格(指定字体、水平居..、单元格跨x列合并、设置单元格内边距)
     *
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @param boderFlag
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        if (!boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(15.0f);
            cell.setPaddingBottom(8.0f);
        } else if (boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(0.0f);
            cell.setPaddingBottom(15.0f);
        }
        return cell;
    }

    /**
     * 创建单元格(指定字体、水平..、边框宽度:0表示无边框、内边距)
     *
     * @param value
     * @param font
     * @param align
     * @param borderWidth
     * @param paddingSize
     * @param flag
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorderWidthLeft(borderWidth[0]);
        cell.setBorderWidthRight(borderWidth[1]);
        cell.setBorderWidthTop(borderWidth[2]);
        cell.setBorderWidthBottom(borderWidth[3]);
        cell.setPaddingTop(paddingSize[0]);
        cell.setPaddingBottom(paddingSize[1]);
        if (flag) {
            cell.setColspan(2);
        }
        return cell;
    }
/**------------------------创建表格单元格的方法end----------------------------*/


/**--------------------------创建表格的方法start------------------- ---------*/
    /**
     * 创建默认列宽,指定列数、水平(居中、右、左)的表格
     *
     * @param colNumber
     * @param align
     * @return
     */
    public static PdfPTable createTable(int colNumber, int align) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(align);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 创建指定列宽、列数的表格
     *
     * @param widths
     * @return
     */
    public static PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 创建指定列宽、列数的表格
     *
     * @param widths
     * @return
     */
    public static PdfPTable createTableFixHeight(float[] widths,float height) {
        PdfPTable table = new PdfPTable(widths);
        try {
            table.setTotalWidth(maxWidth);
            table.getDefaultCell().setMinimumHeight(height);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }
    /**
     * 创建空白的表格
     *
     * @return
     */
    public static PdfPTable createBlankTable() {
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorder(0);
        table.addCell(createCell("", keyfont));
        table.setSpacingAfter(20.0f);
        table.setSpacingBefore(20.0f);
        return table;
    }

    public static PdfPTable getTable(float[] floats, String[] gasList) throws DocumentException {
        PdfPTable tableGas = PdfUtils.createTableFixHeight(floats,25f);
        for(String gas:gasList) {
            tableGas.addCell(PdfUtils.createSignCell(gas, PdfUtils.textfont, Element.ALIGN_CENTER,30f));
        }
        tableGas.setSpacingAfter(25);
        return tableGas;
    }

    public static void getPDFDes(String des,Document document,float before,float after) throws DocumentException {
        Paragraph paragraph = new Paragraph(des, PdfUtils.desfont);
        paragraph.setAlignment(0);
        paragraph.setSpacingBefore(before);
        paragraph.setSpacingAfter(after);
        document.add(paragraph);
    }

/**--------------------------创建表格的方法end------------------- ---------*/


}

 
页眉页脚

package org.jeecg.modules.cm.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.LineSeparator;
import lombok.SneakyThrows;

import java.io.IOException;

 
public class MyHeaderFooter extends PdfPageEventHelper {
    /**
     * 页眉
     */
    public String header = "————————————————————————————————————————————————————————————————————————————————————————";

    /**
     * 文档字体大小,页脚页眉最好和文本大小一致
     */
    public int presentFontSize = 12;

    /**
     * 文档页面大小,最好前面传入,否则默认为A4纸张
     */
    public Rectangle pageSize = PageSize.A4;


    /**
     * logo  页眉
     */
    public Image image;

    // 模板
    public PdfTemplate total;

    // 基础字体对象
    public BaseFont bf = null;

    // 利用基础字体生成的字体对象,一般用于生成中文文字
    public Font fontDetail = null;

//    /**
//     *
//     * Creates a new instance of PdfReportM1HeaderFooter 无参构造方法.
//     *
//     */
//    public PDFBuilder() {
//
//    }
//
//    /**
//     *
//     * Creates a new instance of PdfReportM1HeaderFooter 构造方法.
//     *
//     * @param yeMei
//     *            页眉字符串
//     * @param presentFontSize
//     *            数据体字体大小
//     * @param pageSize
//     *            页面文档大小,A4,A5,A6横转翻转等Rectangle对象
//     */
//
//    public PDFBuilder(String yeMei, int presentFontSize, Rectangle pageSize) {
//        this.header = yeMei;
//        this.presentFontSize = presentFontSize;
//        this.pageSize = pageSize;
//    }
//
//    public void setHeader(String header) {
//        this.header = header;
//    }
//
//    public void setPresentFontSize(int presentFontSize) {
//        this.presentFontSize = presentFontSize;
//    }

    /**
     *
     * TODO 文档打开时创建模板
     *
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter,
     *      com.itextpdf.text.Document)
     */
    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {
        total = writer.getDirectContent().createTemplate(50, 50);// 共 页 的矩形的长宽高
    }

    /**
     *
     * TODO 关闭每页的时候,写入页眉,写入'第几页共'这几个字。
     *
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
     *      com.itextpdf.text.Document)
     */
    @SneakyThrows
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        this.addPage(writer, document);
        //this.addWatermark(writer);
    }

    //加分页
    public void addPage(PdfWriter writer, Document document) throws BadElementException, IOException {
        //设置分页页眉页脚字体
        try {
            if (bf == null) {
                bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
            }
            if (fontDetail == null) {
                fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 数据体字体
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        int pageS = writer.getPageNumber();
        if (pageS != 1) {

            // 页眉logo图片实例
             image = Image.getInstance("\n" +
                     "******");
             image.scalePercent(40);
            //  !!!! 最重要的是这个, 如果页眉需要设置图片的话,需要在Phrase对象中添加一个Chunk对象,在Chunk对象中添加图片信息即可
            Phrase p1 = new Phrase("", fontDetail);
            p1.add(new Chunk(image, 0, -30));
            // 1、写入左侧页眉logo
            ColumnText.showTextAligned(writer.getDirectContent(),
                    Element.ALIGN_LEFT, p1,
                    document.left()-17, document.top(-35), 0);
//             //1.写入页眉文字
//            ColumnText.showTextAligned(writer.getDirectContent(),
//                    Element.ALIGN_LEFT, new Phrase(header, fontDetail),
//                    document.left()-10, document.top() + 40, 0);
            // 1.写入页眉
//            // 直线
            Paragraph p2 = new Paragraph();
            LineSeparator lineSeparator = new LineSeparator();
            lineSeparator.setLineColor(new BaseColor(180,180,180));
            lineSeparator.setLineWidth(0.3f);
            p2.add(new Chunk(lineSeparator));
            ColumnText.showTextAligned(writer.getDirectContent(),
                    Element.ALIGN_LEFT, p2,
                    document.left()-38, document.top() + 3, 0);

            // 2.写入前半部分的 第 X页/共
            String foot1 = "第 " + (pageS-1) + " 页 /共";
            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
            // 再给偏移20F适合人类视觉感受,否则肉眼看上去就太偏左了
            // ,y轴就是底边界-20,否则就贴边重叠到数据体里了就不是页脚了;注意Y轴是从下往上累加的,最上方的Top值是大于Bottom好几百开外的。
            ColumnText
                    .showTextAligned(
                            cb,
                            Element.ALIGN_CENTER,
                            footer,
                            (document.rightMargin() + document.right()
                                    + document.leftMargin() - document.left() - len) / 2.0F + 20F,
                            document.bottom() - 20, 0);

            // 6.写入页脚2的模板(就是页脚的Y页这俩字)添加到文档中,计算模板的和Y轴,X=(右边界-左边界 - 前半部分的len值)/2.0F +
            // len , y 轴和之前的保持一致,底边界-20 // 调节模版显示的位置
            cb.addTemplate(total, (document.rightMargin() + document.right()
                            + document.leftMargin() - document.left()) / 2.0F + 20F,
                    document.bottom() - 20);
        }


    }

    //加水印
    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();
        }
    }

    /**
     *
     * TODO 关闭文档时,替换模板,完成整个页眉页脚组件
     *
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter,
     *      com.itextpdf.text.Document)
     */
    @Override
    public void onCloseDocument(PdfWriter writer, Document document) {
        // 7.最后一步了,就是关闭文档的时候,将模板替换成实际的 Y 值,至此,page x of y 制作完毕,完美兼容各种文档size。
        total.beginText();
        total.setFontAndSize(bf, presentFontSize);// 生成的模版的字体、颜色
        String foot2 = " " + (writer.getPageNumber()-1) + " 页"; //页脚内容拼接  如  第1页/共2页
        total.showText(foot2);// 模版显示的内容
        total.endText();
        total.closePath();
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaProblem/202407/8160.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者