itext生成pdf并添加水印

发布时间 2023-05-04 17:01:19作者: 愚蠢的程序员

  <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>

/**
* 生成PDF * @throws Exception */ public static void createPDF() throws Exception { // 第一步,实例化一个document对象 Document document = new Document(); // 第二步,设置要到出的路径 FileOutputStream out = new FileOutputStream("C:\\tmp\\workbook111.pdf"); // 第三步,将pdf文件输出到磁盘 PdfWriter.getInstance(document, out); // 第四步,打开生成的pdf文件 document.open(); // 第五步,设置内容 // 创建table,注意这里的4是两列的意思,下面通过table.addCell添加的时候必须添加整行内容的所有列 PdfPTable table = new PdfPTable(4); //设置表格宽度比例为%90 table.setWidthPercentage(90.0F); table.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER); PdfPCell title = getCell4("山西省农村信用社维护客户信息电子凭证"); table.addCell(title); table.addCell(getCell1("交易类型")); table.addCell(getCell3("维护客户信息")); Image image1 = Image.getInstance("C:\\tmp\\idCardIs_1.jpg"); PdfPCell cell1 = new PdfPCell(image1, true); // 设置占用列数 cell1.setColspan(2); table.addCell(cell1); Image image2 = Image.getInstance("C:\\tmp\\idCardThe_2.jpg"); PdfPCell cell2 = new PdfPCell(image2, true); cell2.setColspan(2); table.addCell(cell2); document.add(table); document.newPage();//开始新的一页 PdfPTable table2 = new PdfPTable(4); table2.setWidthPercentage(90.0F); table2.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER); PdfPCell title2 = getCell4("山西省农村信用社维护客户信息电子凭证"); title2.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); title2.setHorizontalAlignment(Element.ALIGN_CENTER); table2.addCell(title2); table2.addCell(getCell1("交易类型")); document.add(table2); // 第七步,关闭document document.close(); System.out.println("导出pdf成功~"); } private static Font getFont() throws DocumentException, IOException { BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false); return new Font(bfChinese, 8.0F, 0); } /** * 占用一列 * @return */ public static PdfPCell getCell1(String msg) throws DocumentException, IOException { PdfPCell cell = new PdfPCell(); cell.setColspan(1); cell.addElement(new Paragraph(msg , getFont())); return cell; } /** * 占用二列 * @return */ public static PdfPCell getCell2(String msg) throws DocumentException, IOException { PdfPCell cell = new PdfPCell(); cell.setColspan(2); cell.addElement(new Paragraph(msg , getFont())); return cell; } /** * 占用三列 * @return */ public static PdfPCell getCell3(String msg) throws DocumentException, IOException { PdfPCell cell = new PdfPCell(); cell.setColspan(3); cell.addElement(new Paragraph(msg , getFont())); return cell; } /** * 占用四列 * @return */ public static PdfPCell getCell4(String msg) throws DocumentException, IOException { //cell01.setVerticalAlignment(PdfPCell.ALIGN_CENTER);//设置单元格的垂直对齐方式 //cell01.setHorizontalAlignment(Element.ALIGN_RIGHT);//设置单元格的水平对齐方式 //这两行代码是不起作用的。 //解决方法: //1、按照itextpdf的代码书写方式 //直接在new pdfPCell的时候添加Phrase、Paragraph、chunk PdfPCell cell = new PdfPCell(new Paragraph(msg , getFont())); cell.setColspan(4); return cell; }
/**
     * Description: 给pdf文件添加水印 <br>
     * @param InPdfFile
     *            要加水印的原pdf文件路径
     * @param outPdfFile
     *            加了水印后要输出的路径
     * @param markImagePath
     *            水印图片路径
     * @param imgWidth
     *            图片横坐标
     * @param imgHeight
     *            图片纵坐标
     * @throws Exception
     * @see
     */
    public static void addPdfImgMark(String InPdfFile, String outPdfFile, String markImagePath, int imgWidth,
            int imgHeight) throws Exception {
        PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));
 
        PdfContentByte under;
 
        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0.3f);// 透明度设置
 
        Image img = Image.getInstance(markImagePath);// 插入图片水印
 
        img.setAbsolutePosition(imgWidth, imgHeight); // 坐标
        img.setRotation(-20);// 旋转 弧度
        img.setRotationDegrees(45);// 旋转 角度
        img.scaleAbsolute(700, 80);// 自定义大小
        // img.scalePercent(50);//依照比例缩放
 
        int pageSize = reader.getNumberOfPages();// 原pdf文件的总页数
        for (int i = 1; i <= pageSize; i++) {
            under = stamp.getUnderContent(i);// 水印在之前文本下
            // under = stamp.getOverContent(i);//水印在之前文本上
            under.setGState(gs1);// 图片水印 透明度
            under.addImage(img);// 图片水印
        }
 
        stamp.close();// 关闭
    }
 
    /**
     * Description: 给pdf文件添加水印<br>
     * @param InPdfFile
     *            要加水印的原pdf文件路径
     * @param outPdfFile
     *            加了水印后要输出的路径
     * @param textMark
     *            水印文字
     * @param textWidth
     *            文字横坐标
     * @param textHeight
     *            文字纵坐标
     * @throws Exception
     * @see
     */
    public static void addPdfTextMark(String InPdfFile, String outPdfFile, String textMark, int textWidth,
            int textHeight) throws Exception {
        PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));
 
        PdfContentByte under;
 
        BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);// 使用系统字体
 
        int pageSize = reader.getNumberOfPages();// 原pdf文件的总页数
        for (int i = 1; i <= pageSize; i++) {
            //under = stamp.getUnderContent(i);// 水印在之前文本下
            under = stamp.getOverContent(i);//水印在之前文本上
            under.beginText();
            under.setColorFill(new BaseColor(245,245,245));// 文字水印 颜色
            under.setFontAndSize(font, 20);// 文字水印 字体及字号
            under.setTextMatrix(textWidth, textHeight);// 文字水印 起始位置
            under.showTextAligned(Element.ALIGN_CENTER, textMark, textWidth, textHeight, 0);
            under.endText();
        }
        stamp.close();// 关闭
        reader.close();
    }
 
    public static void main(String[] args) {
        // createPDF();
        try {
            //addPdfImgMark("d:\\first.pdf", "d:\\first-photo.pdf", "d:\\first.jpg", 0, 100);
            addPdfTextMark("C:\\tmp\\workbook111.pdf","C:\\tmp\\workbook1112.pdf","翻印无效",300,600);
            File file = new File("C:\\tmp\\workbook111.pdf");
            if(file.exists()){
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }