itextpdf5.5.13给pdf添加图片水印、添加文字水印(平铺)、添加文字水印(单个)、添加页眉、页脚、页眉事件、添加图片

转载自简书用户:alex很累,感谢分享。原地址:https://www.jianshu.com/p/2b9c7a0300e4

一、相关工具类

1. Excel2Pdf.java (如代码不可用请查看原地址:https://www.jianshu.com/p/be82e26622a1)

import cn.hutool.core.util.StrUtil;
import com.itextpdf.text.Font;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import xyz.xunfan.xbs.constant.FontGenerater;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class Excel2Pdf {
    public static PdfPTable excelToPdf(Workbook workbook, String filename, float pagewidth, int sheetindex) throws Exception {
        Sheet sheet = workbook.getSheetAt(sheetindex);

        float[] widths = getColWidth(sheet);

        PdfPTable table = new PdfPTable(widths);
        table.setWidthPercentage(90);
        table.setLockedWidth(true);
        table.setTotalWidth(pagewidth);
        int colCount = widths.length;

        for (int r = 0; r < sheet.getPhysicalNumberOfRows(); r++) {
            Row row = sheet.getRow(r);
            if (row != null) {
                for (int c = 0; c < colCount; c++) {

                    Cell excelCell = row.getCell(c);
                    if (excelCell == null) {
                        excelCell = row.createCell(c);
                    }
                    String value = "";
                    if (excelCell != null) {
                        excelCell.setCellType(CellType.STRING);
                        value = excelCell.getStringCellValue() == null ? "" : excelCell.getStringCellValue();
                    }
                    org.apache.poi.ss.usermodel.Font excelFont = getExcelFont(workbook, excelCell, filename);

                    short fontsize = excelFont.getFontHeightInPoints();
                    if (!StrUtil.isEmpty(value) && value.length() > FontGenerater.FONT_SMALL_VALUELENGTH && value.split(FontGenerater.HG).length >= 3 && r <= 1) {
                        fontsize = FontGenerater.FONT_SMALL_SIZE;
                    }
                    Font pdFont = getFont(excelFont.getFontName(), fontsize, excelFont.getBold());

                    PdfPCell pCell = null;
                    if (value.indexOf(FontGenerater.REPORT_UNDERLINE) >= 0) {
                        pCell = new PdfPCell(new Phrase(FontGenerater.EMPTY, pdFont));
                        Paragraph para = new Paragraph();
                        String[] values = value.split(FontGenerater.REPORT_UNDERLINE_SUFFIX);
                        for (String v : values) {
                            if (v.indexOf(FontGenerater.REPORT_UNDERLINE) >= 0) {
                                v = v.replace(FontGenerater.REPORT_UNDERLINE, FontGenerater.EMPTY);
                                Chunk dateUnderline = new Chunk(v);
                                dateUnderline.setUnderline(0.1f, -2f);

                                para.add(dateUnderline);
                            } else {
                                para.add(new Chunk(v));
                            }
                        }
                        pCell.getPhrase().add(para);
                    } else {
                        pCell = new PdfPCell(new Phrase(value, pdFont));
                    }

                    List<PicturesInfo> infos = POIExtend.getAllPictureInfos(sheet, r, r, c, c, false);
                    if (!infos.isEmpty()) {
                        PicturesInfo info = infos.get(0);
                        Image img = Image.getInstance(infos.get(0).getPictureData());
                        img.scaleToFit(120, 120);
                        pCell = new PdfPCell(img);
                        pCell.setUseAscender(true);
                        pCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        pCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    }

                    pCell.setBorder(0);
                    pCell.setHorizontalAlignment(getHorAglin(excelCell.getCellStyle().getAlignment().getCode()));
                    pCell.setVerticalAlignment(getVerAglin(excelCell.getCellStyle().getVerticalAlignment().getCode()));

                    pCell.setMinimumHeight(row.getHeightInPoints());

                    if (isMergedRegion(sheet, r, c)) {

                        int[] line = getMerged(sheet, r, c);
                        if (r == line[0]) {
                            pCell.setBorderWidthLeft(excelCell.getCellStyle().getBorderLeft().getCode());
                            pCell.setBorderWidthTop(excelCell.getCellStyle().getBorderTop().getCode());
                        }
                        if (line[1] == sheet.getPhysicalNumberOfRows() - 1) {
                            pCell.setBorderWidthBottom(sheet.getRow(line[1]).getCell(line[2]).getCellStyle().getBorderBottom().getCode());
                        }

                        int[] span = getMergedSpan(sheet, r, c);
                        if (span[0] == 1 && span[1] == 1) {//忽略合并过的单元格
                            continue;
                        }
                        pCell.setRowspan(span[0]);
                        pCell.setColspan(span[1]);
                        c = c + span[1] - 1;//合并过的列直接跳过
                    } else {
                        pCell.setBorderWidthTop(excelCell.getCellStyle().getBorderTop().getCode());
                        pCell.setBorderWidthLeft(excelCell.getCellStyle().getBorderLeft().getCode());
                    }

                    if (r == sheet.getPhysicalNumberOfRows() - 1) {
                        pCell.setBorderWidthBottom(excelCell.getCellStyle().getBorderBottom().getCode());
                    }

                    if (c == row.getPhysicalNumberOfCells() - 1) {
                        pCell.setBorderWidthRight(excelCell.getCellStyle().getBorderRight().getCode());
                    }
                    table.addCell(pCell);
                }
            } else {
                PdfPCell pCell = new PdfPCell(new Phrase(FontGenerater.EMPTY));

                pCell.setBorder(0);
                pCell.setMinimumHeight(13);
                table.addCell(pCell);
            }
        }

        return table;
    }

    //获取字体
    private static org.apache.poi.ss.usermodel.Font getExcelFont(Workbook workbook, Cell cell, String excelName) {

        if (excelName.endsWith(".xls")) {
            return ((HSSFCell) cell).getCellStyle().getFont(workbook);
        }
        return ((XSSFCell) cell).getCellStyle().getFont();
    }

    /**
     * 判断excel单元格是否有边框
     *
     * @param excelCell
     * @return
     */
    private static boolean hasBorder(Cell excelCell) {
        short top = excelCell.getCellStyle().getBorderTop().getCode();
        short bottom = excelCell.getCellStyle().getBorderBottom().getCode();
        short left = excelCell.getCellStyle().getBorderLeft().getCode();
        short right = excelCell.getCellStyle().getBorderRight().getCode();
        return top + bottom + left + right > 2;
    }

    private static void setBorder(Cell excelCell, PdfPCell pCell) {
        pCell.setBorderWidthTop(excelCell.getCellStyle().getBorderTop().getCode());
        pCell.setBorderWidthBottom(excelCell.getCellStyle().getBorderBottom().getCode());
        pCell.setBorderWidthLeft(excelCell.getCellStyle().getBorderLeft().getCode());
        pCell.setBorderWidthRight(excelCell.getCellStyle().getBorderRight().getCode());
    }

    /**
     * 获取excel单元格数据显示格式
     *
     * @param dataFormat
     * @return
     * @throws Exception
     */
    private static String getNumStyle(String dataFormat) throws Exception {
        if (dataFormat == null || dataFormat.length() == 0) {
            throw new Exception("");
        }
        if (dataFormat.indexOf("%") > -1) {
            return dataFormat;
        } else {
            return dataFormat.substring(0, dataFormat.length() - 2);
        }
    }

    /**
     * 判断单元格是否是合并单元格
     *
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    private static boolean isMergedRegion(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    return true;
                }
            }
        }
        return false;
    }

    private static int[] getMerged(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        int[] span = {0, 0, 0, 0};
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    span[0] = firstRow;
                    span[1] = lastRow;
                    span[2] = firstColumn;
                    span[3] = lastColumn;
                    break;
                }
            }
        }
        return span;
    }

    /**
     * 计算合并单元格合并的跨行跨列数
     *
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    private static int[] getMergedSpan(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        int[] span = {1, 1};
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (firstColumn == column && firstRow == row) {
                span[0] = lastRow - firstRow + 1;
                span[1] = lastColumn - firstColumn + 1;
                break;
            }
        }

        return span;
    }

    /**
     * 获取excel中每列宽度的占比
     *
     * @param sheet
     * @return
     */
    private static float[] getColWidth(Sheet sheet) {
        int rowNum = getMaxColRowNum(sheet);
        Row row = sheet.getRow(rowNum);
        int cellCount = row.getPhysicalNumberOfCells();
        int[] colWidths = new int[cellCount];
        int sum = 0;

        for (int i = 0; i < cellCount; i++) {
            Cell cell = row.getCell(i);
            if (cell != null) {
                colWidths[i] = sheet.getColumnWidth(i);
                sum += sheet.getColumnWidth(i);
            }
        }

        float[] colWidthPer = new float[cellCount];
        for (int i = 0; i < cellCount; i++) {
            colWidthPer[i] = (float) colWidths[i] / sum * 100;
        }
        return colWidthPer;
    }

    /**
     * 获取excel中列数最多的行号
     *
     * @param sheet
     * @return
     */
    private static int getMaxColRowNum(Sheet sheet) {
        int rowNum = 0;
        int maxCol = 0;
        for (int r = 0; r < sheet.getPhysicalNumberOfRows(); r++) {
            Row row = sheet.getRow(r);
            if (row != null && maxCol < row.getPhysicalNumberOfCells()) {
                maxCol = row.getPhysicalNumberOfCells();
                rowNum = r;
            }
        }
        return rowNum;
    }

    /**
     * excel垂直对齐方式映射到pdf对齐方式
     *
     * @param aglin
     * @return
     */
    private static int getVerAglin(int aglin) {
        switch (aglin) {
            case 1:
                return Element.ALIGN_MIDDLE;
            case 2:
                return Element.ALIGN_BOTTOM;
            case 0:
                return Element.ALIGN_TOP;
            default:
                return Element.ALIGN_MIDDLE;
        }
    }

    /**
     * excel水平对齐方式映射到pdf水平对齐方式
     *
     * @param aglin
     * @return
     */
    private static int getHorAglin(int aglin) {
        switch (aglin) {
            case 2:
                return Element.ALIGN_CENTER;
            case 3:
                return Element.ALIGN_RIGHT;
            case 1:
                return Element.ALIGN_LEFT;
            default:
                return Element.ALIGN_CENTER;
        }
    }

    /**
     * 格式化数字
     *
     * @param pattern
     * @param num
     * @return
     */
    private static String numFormat(String pattern, double num) {
        DecimalFormat format = new DecimalFormat(pattern);
        return format.format(num);
    }

    private static int[] getImgPostion(String imgKey) {
        String[] arr = imgKey.split("_");
        int[] position = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            position[i] = Integer.parseInt(arr[i]);
        }
        return position;
    }

    public static Map<String, HSSFPictureData> getPictrues(HSSFWorkbook wb) {
        Map<String, HSSFPictureData> map = new HashMap<String, HSSFPictureData>();
        // getAllPictures方法只能获取不同的图片,如果Excel中存在相同的图片,只能得到一张图片
        List<HSSFPictureData> pics = wb.getAllPictures();
        if (pics.size() == 0) {
            return map;
        }
        for (Integer sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
            HSSFSheet sheet = wb.getSheetAt(sheetIndex);
            HSSFPatriarch patriarch = sheet.getDrawingPatriarch();
            if (patriarch == null) {
                continue;
            }
            for (HSSFShape shape : patriarch.getChildren()) {
                HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
                if (shape instanceof HSSFPicture) {
                    HSSFPicture pic = (HSSFPicture) shape;
                    int picIndex = pic.getPictureIndex() - 1;
                    HSSFPictureData picData = pics.get(picIndex);
                    // 键格式:sheet索引_行号_列号_单元格内的上边距_单元格内的左边距_uuid
                    String key = sheetIndex + "_" + anchor.getRow1() + "_" + anchor.getCol1() + "_" + anchor.getRow2() + "_" + anchor.getCol2();
                    key += "_" + anchor.getDx1() + "_" + anchor.getDy1() + "_" + anchor.getDx2() + "_" + anchor.getDy2();
                    key += "_" + UUID.randomUUID();
                    map.put(key, picData);
                }
            }
        }
        return map;
    }

    public static Map<String, PictureData> getPictrues(Workbook wb, int type) {
        Map<String, PictureData> map = new HashMap<String, PictureData>();
        // getAllPictures方法只能获取不同的图片,如果Excel中存在相同的图片,只能得到一张图片
        List<? extends PictureData> pics = wb.getAllPictures();
        if (pics.size() == 0) {
            return map;
        }
        for (Integer sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
            Sheet sheet = wb.getSheetAt(sheetIndex);
            Drawing<?> patriarch = sheet.getDrawingPatriarch();
            if (patriarch == null) {
                continue;
            }
            if (type == 2) {
                HSSFPatriarch hssfpatriarch = (HSSFPatriarch) patriarch;
                for (HSSFShape shape : hssfpatriarch.getChildren()) {
                    HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
                    if (shape instanceof HSSFPicture) {
                        HSSFPicture pic = (HSSFPicture) shape;
                        int picIndex = pic.getPictureIndex() - 1;
                        HSSFPictureData picData = (HSSFPictureData) pics.get(picIndex);
                        // 键格式:sheet索引_行号_列号_单元格内的上边距_单元格内的左边距_uuid
                        String key = sheetIndex + "_" + anchor.getRow1() + "_" + anchor.getCol1() + "_" + anchor.getRow2() + "_" + anchor.getCol2();
                        key += "_" + anchor.getDx1() + "_" + anchor.getDy1() + "_" + anchor.getDx2() + "_" + anchor.getDy2();
                        key += "_" + UUID.randomUUID();
                        map.put(key, picData);
                    }
                }
            } else if (type == 1) {
                XSSFSheet xssfsheet = (XSSFSheet) sheet;
                for (POIXMLDocumentPart dr : xssfsheet.getRelations()) {
                    if (dr instanceof XSSFDrawing) {
                        XSSFDrawing drawing = (XSSFDrawing) dr;
                        List<XSSFShape> shapes = drawing.getShapes();
                        for (XSSFShape shape : shapes) {
                            XSSFPicture pic = (XSSFPicture) shape;
                            XSSFPictureData data = pic.getPictureData();
                            XSSFClientAnchor aaa = pic.getClientAnchor();
                            CTMarker ccc = aaa.getFrom();
                            int ddd = ccc.getRow();
                            int eee = ccc.getCol();
//                            XSSFClientAnchor anchor = pic.getPreferredSize();
//                            CTMarker ctMarker = anchor.getFrom();
//                            String picIndex = String.valueOf(0) + "_" + ctMarker.getRow() + "_" + ctMarker.getCol();
                            String picIndex = String.valueOf(0) + "_" + ddd + "_" + eee;
                            map.put(picIndex, pic.getPictureData());
                        }
                    }
                }
            }
        }

        return map;
    }

    /**
     * 单元格是否是图片的起始位置
     *
     * @return 单元格是否是图片的起始位置
     */
    public static BaseColor parseBackgroundColor(Color hssfColor) {
        if (hssfColor == null) {
            // 白色
            return new BaseColor(255, 255, 255);
        }
        short[] rgb = new short[]{255, 255, 255};
        if (rgb[0] == 0 && rgb[1] == 0 && rgb[2] == 0) {
            rgb = new short[]{255, 255, 255};
        }
        return new BaseColor(rgb[0], rgb[1], rgb[2]);
    }

    public static PdfPCell parseImgPCell(Cell cell) {
        PdfPCell pdfpCell = new PdfPCell();
        CellStyle cellStyle = cell.getCellStyle();
        pdfpCell.setUseAscender(true);
        // 水平对齐方式
        int halign_itext = cellStyle.getAlignment().getCode();
        //int halign_itext = parseHorizontalAlignmen(halign);
        pdfpCell.setHorizontalAlignment(halign_itext);
        // 垂直对齐方式
        int valign_itext = cellStyle.getVerticalAlignment().getCode();
        // int valign_itext = parseVerticalAlignment(valign);
        pdfpCell.setVerticalAlignment(valign_itext);
        // 填充色(背景色)
        // HSSFColor backgroundColor = cellStyle.getFillBackgroundColorColor();
        Color backgroundColor = cellStyle.getFillForegroundColorColor();
        BaseColor backgroundColor_itext = parseBackgroundColor(backgroundColor);
        pdfpCell.setBackgroundColor(backgroundColor_itext);
        // 自动换行
        boolean noWrap = !cellStyle.getWrapText();
        pdfpCell.setNoWrap(noWrap);


        // 边框样式
        // 下边框
        float borderWidth = cellStyle.getBorderBottom().getCode() / 32.00f;
        //float borderWidth = borderStyle ;
        pdfpCell.setBorderWidthBottom(borderWidth);
        // 上框线
        // borderStyle = cellStyle.getBorderTop();
        pdfpCell.setBorderWidthTop(cellStyle.getBorderTop().getCode() / 32.00f);
        // 左框线
        //   borderStyle = cellStyle.getBorderLeft();
        pdfpCell.setBorderWidthLeft(cellStyle.getBorderLeft().getCode() / 32.00f);
        // 右框线
        //borderStyle = cellStyle.getBorderRight();
        pdfpCell.setBorderWidthRight(cellStyle.getBorderRight().getCode() / 32.00f);

        pdfpCell.normalize();
        // pdfpCell.disableBorderSide(9);
        return pdfpCell;
    }

    public static BaseColor parseColor(HSSFColor hssfColor) {
        if (hssfColor == null) {
            return new BaseColor(255, 255, 255);
        }
        short[] rgb = hssfColor.getTriplet();
        return new BaseColor(rgb[0], rgb[1], rgb[2]);
    }

    public static Font getFont(String fontname, int heigth, boolean bold) throws Exception {
        BaseFont font = FontGenerater.getFont(fontname);
        if (font == null) {
            font = (BaseFont) FontGenerater.FONTMAP.get(FontGenerater.FONT_SONTI_NAME);
        }

        return new Font(font, heigth, bold ? Font.BOLD : Font.NORMAL, BaseColor.BLACK);

    }
}

 


2. PDFUtil.java

public class PDFUtil {
    /**
     * 给pdf添加图片水印
     * @param waterMar
     * @param imgpath 图片路径
     * @throws Exception
     */
    public static void addImgWaterMark(PdfContentByte waterMar, String imgpath) throws Exception {
        waterMar.beginText();

        PdfGState gs = new PdfGState();
        // 设置填充字体不透明度为0.4f
        gs.setFillOpacity(0.2f);
        waterMar.setFontAndSize(FontGenerater.getFont(FontGenerater.FONT_SONTI_NAME), 40);
        // 设置透明度
        waterMar.setGState(gs);
        // 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
        Image img = Image.getInstance(imgpath);
        img.setAbsolutePosition(200, 380);
        img.scaleAbsolute(200, 200);

        waterMar.addImage(img);
        // 设置水印颜色
        waterMar.setColorFill(BaseColor.GRAY);

        //结束设置
        waterMar.endText();
        waterMar.stroke();
    }

    /**
     * 给pdf添加文字水印(平铺)
     * @param waterMar
     * @param text 水印文本
     * @throws Exception
     */
    public static void addTextFullWaterMark(PdfContentByte waterMar, String text) throws Exception {
        waterMar.beginText();

        PdfGState gs = new PdfGState();
        // 设置填充字体不透明度为0.4f
        gs.setFillOpacity(0.2f);
        waterMar.setFontAndSize(FontGenerater.getFont(FontGenerater.FONT_SONTI_NAME), 40);
        // 设置透明度
        waterMar.setGState(gs);
        // 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
        for (int x = 0; x <= 700; x += 200) {
            for (int y = 0; y <= 800; y += 200) {
                waterMar.showTextAligned(Element.ALIGN_RIGHT, text, x, y, 35);
            }
        }

        // 设置水印颜色
        waterMar.setColorFill(BaseColor.GRAY);

        //结束设置
        waterMar.endText();
        waterMar.stroke();
    }

    /**
     * 给pdf添加文字水印(单个)
     * @param waterMar
     * @param text 水印文本
     * @throws Exception
     */
    public static void addTextWaterMark(PdfContentByte waterMar, String text) throws Exception {
        waterMar.beginText();

        PdfGState gs = new PdfGState();
        // 设置填充字体不透明度为0.4f
        gs.setFillOpacity(0.2f);
        waterMar.setFontAndSize(FontGenerater.getFont(FontGenerater.FONT_SONTI_NAME), 80);
        // 设置透明度
        waterMar.setGState(gs);
        // 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
        waterMar.showTextAligned(Element.ALIGN_RIGHT, text, 475, 600, 45);

        // 设置水印颜色
        waterMar.setColorFill(BaseColor.GRAY);

        //结束设置
        waterMar.endText();
        waterMar.stroke();
    }

    /**
     * 添加页眉、页脚
     * @param writer
     * @param content
     * @param pagewidth
     * @param pageheight
     * @throws Exception
     */
    public static void addText(PdfWriter writer, String content, int pagewidth, int pageheight) throws Exception {
        PdfPTable table = new PdfPTable(1);
        table.setTotalWidth(530);
        PdfPCell cell = new PdfPCell(new Phrase(content, Excel2Pdf.getFont(FontGenerater.FONT_SONTI_NAME, 12, false)));
        cell.setBorder(0);
        // cell.setPaddingLeft(30f);
        cell.setPaddingTop(-15f);
        cell.setPaddingRight(20f);

        table.addCell(cell);
        Header event = new Header(table, pagewidth, pageheight);
        writer.setPageEvent(null);
        writer.setPageEvent(event);
    }

    //页眉事件
    private static class Header extends PdfPageEventHelper {
        public static PdfPTable header;
        public int pagewidth;
        public int pageheight;

        public Header(PdfPTable header, int pagewidth, int pageheight) {
            Header.header = header;
            this.pagewidth = pagewidth;
            this.pageheight = pageheight;
        }

        @Override
        public void onEndPage(PdfWriter writer, Document document) {
            //把页眉表格定位
            header.writeSelectedRows(0, -1, this.pagewidth, this.pageheight, writer.getDirectContent());
        }
    }

    /**
     * 添加图片
     * @param document
     * @param imgPath
     * @param newWidth
     * @param newHeight
     * @param absoluteX
     * @param absoluteY
     * @throws IOException
     * @throws DocumentException
     */
    public static void addImg(Document document, String imgPath, float newWidth, float newHeight,
                              float absoluteX, float absoluteY) throws IOException, DocumentException {
        Image img1 = Image.getInstance(imgPath);
        img1.setAbsolutePosition(absoluteX, absoluteY);
        img1.scaleAbsolute(newWidth, newHeight);
        document.add(img1);
    }
}

二、示例

1、添加图片水印

// A4大小
RectangleReadOnly shuban = new RectangleReadOnly(PageSize.A4);
Document document = new Document(shuban);
// 获取一个pdfwriter实例
FileOutputStream stream = new FileOutputStream("D:\\website\\demo.pdf");
PdfWriter writer = PdfWriter.getInstance(document, stream);
// 打开document
document.open();
// 新增页
document.newPage();
// **************添加水印**************
PdfContentByte waterMar = writer.getDirectContentUnder();
PDFUtil.addImgWaterMark(waterMar, "D:\\website\\java.png");
// **************完成图片水印添加***********
// 关闭
document.close();
writer.close();
stream.close();

 

2、添加平铺的文字水印

// **************添加平铺的文字水印**************
PdfContentByte waterMar = writer.getDirectContentUnder();
String text = "这是一个示例";
PDFUtil.addTextFullWaterMark(waterMar, text);
// **************完成水印***********************

 

3、添加单个文字水印

// **************添加单个的文字水印**************
PdfContentByte waterMar = writer.getDirectContentUnder();
String text = "这是一个示例";
PDFUtil.addTextWaterMark(waterMar, text);
// **************完成水印***********************

 

4、插入文字、图片

// 插入文字,最后两个参数是文字的位置
PDFUtil.addText(writer, "这是一段文字", 480, 802);
// 插入图片,第二、三个参数表示图片宽高,第四、五个参数表示位置
PDFUtil.addImg(document, "D:\\website\\start.png", 100, 100, 70, 700);

 

posted on 2023-05-23 14:52  宇宙小子  阅读(2059)  评论(0编辑  收藏  举报