itextpdf生成pdf文件并追加页码

阅读更多
/**
* 页眉页脚
* mark一下,原文地址:https://blog.csdn.net/ae6623/article/details/11734285/
*/

import java.io.IOException;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
 
public class PdfHeaderFooter extends PdfPageEventHelper {
 
    /**
     * 页眉

     */
    public String header = "";
 
    /**
     * 文档字体大小,页脚页眉最好和文本大小一致
     */
    public int presentFontSize = 12;
 
    /**
     * 文档页面大小,最好前面传入,否则默认为A4纸张
     */
    public Rectangle pageSize = PageSize.A4;
 
    // 模板
    public PdfTemplate total;
 
    // 基础字体对象
    public BaseFont bf = null;
 
    // 利用基础字体生成的字体对象,一般用于生成中文文字
    public Font fontDetail = null;
 
    /**
     *
     * Creates a new instance of PdfReportM1HeaderFooter 无参构造方法.
     *
     */
    public PdfHeaderFooter() {
 
    }
 
    /**
     *
     * Creates a new instance of PdfReportM1HeaderFooter 构造方法.
     *
     * @param yeMei
     *            页眉字符串
     * @param presentFontSize
     *            数据体字体大小
     * @param pageSize
     *            页面文档大小,A4,A5,A6横转翻转等Rectangle对象
     */
    public PdfHeaderFooter(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)
     */
    @Override
    public void onEndPage(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);// 数据体字体
            }
        } 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 + " 页 /共";
        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); // 调节模版显示的位置
 
    }
 
    /**
     *
     * 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) + " 页";
        total.showText(foot2);// 模版显示的内容
        total.endText();
        total.closePath();
    }
}




/**
* 生成pdf
*/

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.test.dorm.domain.vo.DmAgreemeetVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
* Created by xyh
*/
public class PdfTestServiceImpl {

    private static Logger logger = LoggerFactory.getLogger(PdfTestServiceImpl.class);

    /**
     * 追加协议内容
     *
     * @param document 原协议文档
     * @param agre     协议内容
     * @throws DocumentException
     * @throws IOException
     */
    private void addAgreement(Document document, DmAgreemeetVo agre) throws DocumentException, IOException {
        //设置字体
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font fontChinese18 = new Font(bfChinese, 18, Font.BOLD);
        Font fontChinese16 = new Font(bfChinese, 16, Font.BOLD);
        Font fontChinese11Bold = new Font(bfChinese, 11, Font.BOLD);
        Font fontChinese11Normal = new Font(bfChinese, 11, Font.NORMAL);

        // 标题【物品放行单】
        PdfPTable subject = new PdfPTable(1);
        //设置每列宽度比例
        int width21[] = {98};
        subject.setWidths(width21);
        subject.getDefaultCell().setBorder(0);
        PdfPCell cell21 = new PdfPCell(new Paragraph("物品放行单", fontChinese16));

        cell21.setBorder(0);
        cell21.setHorizontalAlignment(Element.ALIGN_CENTER);
        subject.addCell(cell21);
        document.add(subject);
        //加入空行
        Paragraph blankRow2 = new Paragraph(18f, " ", fontChinese18);
        document.add(blankRow2);

        // 申请单号
        PdfPTable applyCodeTbl = new PdfPTable(3);
        BaseColor applyCodeBorder = new BaseColor(0xCC, 0xCC, 0xCC);
        int applyCodeCellWidth[] = {160, 30, 50};
        applyCodeTbl.setWidths(applyCodeCellWidth);
        PdfPCell applyCodeCell1 = this.setPdfPCell("", 25, fontChinese11Normal, applyCodeBorder, true, PdfPCell.BOX);
        PdfPCell applyCodeCell2 = this.setPdfPCell("申请单号:", 25, fontChinese11Normal, applyCodeBorder, true, PdfPCell.BOX);
        PdfPCell applyCodeCell3 = this.setPdfPCell(agre.getTaskId(), 25, fontChinese11Normal, applyCodeBorder, true, PdfPCell.BOX);
        applyCodeCell1.setBorder(0);
        applyCodeCell2.setBorder(0);
        applyCodeCell3.setBorder(0);
        applyCodeCell3.setHorizontalAlignment(Element.ALIGN_LEFT);
        applyCodeTbl.addCell(applyCodeCell1);
        applyCodeTbl.addCell(applyCodeCell2);
        applyCodeTbl.addCell(applyCodeCell3);
        document.add(applyCodeTbl);

        // 放行日期
        PdfPTable releaseDateTbl = new PdfPTable(2);
        BaseColor releaseDateBorder = new BaseColor(0xCC, 0xCC, 0xCC);
        int releaseDateCellWidth[] = {30, 210};
        releaseDateTbl.setWidths(releaseDateCellWidth);
        PdfPCell releaseDateCell1 = this.setPdfPCell("放行日期", 25, fontChinese11Normal, releaseDateBorder, true, PdfPCell.BOX);
        PdfPCell releaseDateCell2 = this.setPdfPCell("", 25, fontChinese11Normal, releaseDateBorder, true, PdfPCell.BOX);
        releaseDateTbl.addCell(releaseDateCell1);
        releaseDateTbl.addCell(releaseDateCell2);
        document.add(releaseDateTbl);

        //申请人信息
        PdfPTable applyUserTbl = new PdfPTable(6);
        BaseColor applyUserBorder = new BaseColor(0xCC, 0xCC, 0xCC);
        int applyUserCellWidth[] = {30, 35, 35, 35, 20, 85};
        applyUserTbl.setWidths(applyUserCellWidth);
        PdfPCell applyUserCell1 = this.setPdfPCell("申请人", 25, fontChinese11Normal, applyUserBorder, true, PdfPCell.BOX);
        PdfPCell applyUserCell2 = this.setPdfPCell("", 25, fontChinese11Normal, applyUserBorder, true, PdfPCell.BOX);
        PdfPCell applyUserCell3 = this.setPdfPCell("电话", 25, fontChinese11Normal, applyUserBorder, true, PdfPCell.BOX);
        PdfPCell applyUserCell4 = this.setPdfPCell("", 25, fontChinese11Normal, applyUserBorder, true, PdfPCell.BOX);
        PdfPCell applyUserCell5 = this.setPdfPCell("部门", 25, fontChinese11Normal, applyUserBorder, true, PdfPCell.BOX);
        PdfPCell applyUserCell6 = this.setPdfPCell("", 25, fontChinese11Normal, applyUserBorder, true, PdfPCell.BOX);
        applyUserTbl.addCell(applyUserCell1);
        applyUserTbl.addCell(applyUserCell2);
        applyUserTbl.addCell(applyUserCell3);
        applyUserTbl.addCell(applyUserCell4);
        applyUserTbl.addCell(applyUserCell5);
        applyUserTbl.addCell(applyUserCell6);

        // 携物人信息
        PdfPCell carryGoodsUserCell1 = this.setPdfPCell("携物人", 25, fontChinese11Normal, applyUserBorder, true, PdfPCell.BOX);
        PdfPCell carryGoodsUserCell2 = this.setPdfPCell("", 25, fontChinese11Normal, applyUserBorder, true, PdfPCell.BOX);
        PdfPCell carryGoodsUserCell3 = this.setPdfPCell("电话", 25, fontChinese11Normal, applyUserBorder, true, PdfPCell.BOX);
        PdfPCell carryGoodsUserCell4 = this.setPdfPCell("", 25, fontChinese11Normal, applyUserBorder, true, PdfPCell.BOX);
        PdfPCell carryGoodsUserCell5 = this.setPdfPCell("单位", 25, fontChinese11Normal, applyUserBorder, true, PdfPCell.BOX);
        PdfPCell carryGoodsUserCell6 = this.setPdfPCell("", 25, fontChinese11Normal, applyUserBorder, true, PdfPCell.BOX);
        applyUserTbl.addCell(carryGoodsUserCell1);
        applyUserTbl.addCell(carryGoodsUserCell2);
        applyUserTbl.addCell(carryGoodsUserCell3);
        applyUserTbl.addCell(carryGoodsUserCell4);
        applyUserTbl.addCell(carryGoodsUserCell5);
        applyUserTbl.addCell(carryGoodsUserCell6);
        document.add(applyUserTbl);

        // 物品列表
        PdfPTable goodsListTbl = new PdfPTable(4);
        BaseColor goodsListBorder = new BaseColor(0xCC, 0xCC, 0xCC);
        int goodsListCellWidth[] = {75, 15, 75, 75};
        goodsListTbl.setWidths(goodsListCellWidth);
        PdfPCell goodsListCell1 = this.setPdfPCell("物品名称", 25, fontChinese11Normal, goodsListBorder, true, PdfPCell.BOX);
        PdfPCell goodsListCell2 = this.setPdfPCell("数量", 25, fontChinese11Normal, goodsListBorder, true, PdfPCell.BOX);
        PdfPCell goodsListCell3 = this.setPdfPCell("规格", 25, fontChinese11Normal, goodsListBorder, true, PdfPCell.BOX);
        PdfPCell goodsListCell4 = this.setPdfPCell("型号", 25, fontChinese11Normal, goodsListBorder, true, PdfPCell.BOX);
        goodsListTbl.addCell(goodsListCell1);
        goodsListTbl.addCell(goodsListCell2);
        goodsListTbl.addCell(goodsListCell3);
        goodsListTbl.addCell(goodsListCell4);
        int goodsRows = 10;
        for (int i = 0; i < goodsRows; i++) {
            PdfPCell goodsNameCell = this.setPdfPCell("物品名称", null, fontChinese11Normal, goodsListBorder, true, PdfPCell.BOX);
            PdfPCell goodsCountCell = this.setPdfPCell(i + "", null, fontChinese11Normal, goodsListBorder, true, PdfPCell.BOX);
            PdfPCell goodsSpecificationCell = this.setPdfPCell("啊大大逻辑发阿达啊爱就爱累加方式sfsfsfdsh哈哈faaaaaaaadfsfsfdsfds福建省发送到发送到", null, fontChinese11Normal, goodsListBorder, true, PdfPCell.BOX);
            PdfPCell goodsModelCell = this.setPdfPCell("adsadjaojdddddddddddsadsa2342424234s2aa" + i, null, fontChinese11Normal, goodsListBorder, true, PdfPCell.BOX);
            goodsListTbl.addCell(goodsNameCell);
            goodsListTbl.addCell(goodsCountCell);
            goodsListTbl.addCell(goodsSpecificationCell);
            goodsListTbl.addCell(goodsModelCell);
        }
        document.add(goodsListTbl);

        // 物品所属部门
        PdfPTable goodsBelongDeptTbl = new PdfPTable(2);
        BaseColor goodsBelongDeptBorder = new BaseColor(0xCC, 0xCC, 0xCC);
        int goodsBelongDeptCellWidth[] = {30, 210};
        goodsBelongDeptTbl.setWidths(goodsBelongDeptCellWidth);
        PdfPCell goodsBelongDeptCell1 = this.setPdfPCell("物品所属部门", 25, fontChinese11Normal, goodsBelongDeptBorder, true, PdfPCell.BOX);
        PdfPCell goodsBelongDeptCell2 = this.setPdfPCell("", 25, fontChinese11Normal, goodsBelongDeptBorder, true, PdfPCell.BOX);
        goodsBelongDeptTbl.addCell(goodsBelongDeptCell1);
        goodsBelongDeptTbl.addCell(goodsBelongDeptCell2);

        // 批准人
        PdfPCell approverUserCell1 = this.setPdfPCell("批准人", 25, fontChinese11Normal, goodsBelongDeptBorder, true, PdfPCell.BOX);
        PdfPCell approverUserCell2 = this.setPdfPCell("", 25, fontChinese11Normal, goodsBelongDeptBorder, true, PdfPCell.BOX);
        goodsBelongDeptTbl.addCell(approverUserCell1);
        goodsBelongDeptTbl.addCell(approverUserCell2);

        // 出门原因
        PdfPCell outReasonCell1 = this.setPdfPCell("出门原因", 25, fontChinese11Normal, goodsBelongDeptBorder, true, PdfPCell.BOX);
        PdfPCell outReasonCell2 = this.setPdfPCell("", 25, fontChinese11Normal, goodsBelongDeptBorder, true, PdfPCell.BOX);
        goodsBelongDeptTbl.addCell(outReasonCell1);
        goodsBelongDeptTbl.addCell(outReasonCell2);

        // 备注
        PdfPCell remarkCell1 = this.setPdfPCell("备注", 25, fontChinese11Normal, goodsBelongDeptBorder, true, PdfPCell.BOX);
        PdfPCell remarkCell2 = this.setPdfPCell("", 25, fontChinese11Normal, goodsBelongDeptBorder, true, PdfPCell.BOX);
        goodsBelongDeptTbl.addCell(remarkCell1);
        goodsBelongDeptTbl.addCell(remarkCell2);

        // 注
        PdfPCell noteCell1 = this.setPdfPCell("注:", 25, fontChinese11Normal, goodsBelongDeptBorder, true, PdfPCell.BOX);
        noteCell1.setRowspan(3);
        goodsBelongDeptTbl.addCell(noteCell1);
        PdfPCell noteCell2 = this.setPdfPCell("1、放行单当日有效,逾期作废", 25, fontChinese11Normal, goodsBelongDeptBorder, true, PdfPCell.BOX);
        noteCell2.setHorizontalAlignment(Element.ALIGN_LEFT);
        goodsBelongDeptTbl.addCell(noteCell2);
        PdfPCell noteCell3 = this.setPdfPCell("2、各项内容需填写完整、准确,不得涂改、损坏", 25, fontChinese11Normal, goodsBelongDeptBorder, true, PdfPCell.BOX);
        noteCell3.setHorizontalAlignment(Element.ALIGN_LEFT);
        goodsBelongDeptTbl.addCell(noteCell3);
        PdfPCell noteCell4 = this.setPdfPCell("3、须将此物品放行单交于当值安保员", 25, fontChinese11Normal, goodsBelongDeptBorder, true, PdfPCell.BOX);
        noteCell4.setHorizontalAlignment(Element.ALIGN_LEFT);
        goodsBelongDeptTbl.addCell(noteCell4);
        document.add(goodsBelongDeptTbl);

    }

    /**
     * 填充单元格
     *
     * @param cellVal    值
     * @param height     表格高度
     * @param font       字体
     * @param lightGrey  边框颜色
     * @param borderFlag 是否显示边框  true:显示;false:不显示
     * @param borderSide 显示或不显示那个边框
     * @return
     */
    private PdfPCell setPdfPCell(String cellVal, Integer height, Font font, BaseColor lightGrey, boolean borderFlag, int borderSide) {
        PdfPCell cell = new PdfPCell(new Paragraph(cellVal, font));
        //表格高度,null表示需要自动换行展示,所以设置padding
        if (height != null) {
            cell.setFixedHeight(25);
        } else {
            cell.setPadding(4);
        }
        //水平居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        //垂直居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        //边框颜色
        cell.setBorderColor(lightGrey);

        if (!borderFlag) {
            //去掉左右边框
            cell.disableBorderSide(borderSide);
        } else {
            //添加左右边框
            cell.enableBorderSide(borderSide);
        }
        return cell;
    }

    /**
     * 加文本水印
     * @param inputFile     你的PDF文件地址
     * @param outputFile    添加水印后生成PDF存放的地址
     * @param waterMarkName 你的水印
     * @return
     */
    public static boolean waterMarkWidthText(String inputFile,
                                    String outputFile, String waterMarkName) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
                    outputFile));
            //这里的字体设置比较关键,这个设置是支持中文的写法
            BaseFont base = BaseFont.createFont("STSong-Light",
                    "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
            int total = reader.getNumberOfPages() + 1;

            PdfContentByte under;
            Rectangle pageRect = null;
            for (int i = 1; i < total; i++) {
                pageRect = stamper.getReader().
                        getPageSizeWithRotation(i);
                // 计算水印X,Y坐标
//                float x = pageRect.getWidth()/10;
//                float y = pageRect.getHeight()/10-10;
                // 获得PDF最顶层
                under = stamper.getOverContent(i);
                under.saveState();
                // set Transparency
                PdfGState gs = new PdfGState();
                // 设置透明度为0.2
                gs.setFillOpacity(0.8f);
                under.setGState(gs);
                under.restoreState();
                under.beginText();
                under.setFontAndSize(base, 25);
                under.setTextMatrix(30, 30);
                under.setColorFill(BaseColor.RED);
                for (int y = 0; y < 10; y++) {
                    for (int x = 0; x < 8; x++) {
                        // 水印文字成45度角倾斜
                        under.showTextAligned(Element.ALIGN_LEFT
                                , waterMarkName, 100 + 300 * x, 300 * y, 45);
                    }
                }

                // 添加水印文字
                under.endText();
                under.setLineWidth(1f);
                under.stroke();
            }
            stamper.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置页码
     * @param writer
     * @throws DocumentException
     * @throws IOException
     */
    private void setFooter(PdfWriter writer) throws Exception {
        PdfHeaderFooter headerFooter = new PdfHeaderFooter();//就是上面那个类
        writer.setBoxSize("art", PageSize.A4);
        writer.setPageEvent(headerFooter);
    }

    /**
     * 生成pdf文件
     *
     * @param pdfFile 要生成的pdf文件
     * @param agre    pdf文件中的数据对象
     * @throws Exception
     */
    private void createPdfFile(File pdfFile, DmAgreemeetVo agre) throws Exception {
        FileOutputStream fo = new FileOutputStream(pdfFile);
        Document document1 = new Document(PageSize.A4.rotate());
        PdfWriter writer = null;
        // 初始化pdf文件写出流
        writer = PdfWriter.getInstance(document1, fo);
        this.setFooter(writer);
        document1.open();

        agre.setDepositStatus(1);
        // 追加协议内容
        this.addAgreement(document1, agre);
        document1.close();
        writer.close();
        fo.close();
    }

    /**
     * 加图片水印
     *
     * @param pdfFile          源pdf文件
     * @param pdfWatermarkFile 加水印后的pdf文件
     * @throws Exception
     */
    private void waterMarkWidthImage(File pdfFile, File pdfWatermarkFile) throws Exception {

        // 源pdf文件
        FileInputStream inputFile = new FileInputStream(pdfFile);

        PdfReader reader = new PdfReader(inputFile);
        int total = reader.getNumberOfPages() + 1;

        //实现A4纸页面 并且横向显示(不设置则为纵向)
        Document document = new Document(PageSize.A4.rotate());
        // 打开文档
        document.open();


        // 加入水印
        FileOutputStream resultOutFile = new FileOutputStream(pdfWatermarkFile);
        PdfStamper stamper = new PdfStamper(reader, resultOutFile);
        PdfContentByte waterMar = null;

        // 设置水印透明度
        PdfGState gs = new PdfGState();
        // 设置笔触字体不透明度为0.2f
        gs.setStrokeOpacity(0.8f);
        gs.setFillOpacity(0.8f);
        try {
            Image image = Image.getInstance("F:/京东logo.png");
            // 设置坐标 绝对位置 X Y
            image.setAbsolutePosition(200, 300);
            // 设置旋转弧度
            image.setRotation(30);// 旋转 弧度
            // 设置旋转角度
            image.setRotationDegrees(45);// 旋转 角度
            // 设置等比缩放
            image.scalePercent(20);// 依照比例缩放

            for (int i = 1; i < total; i++) {
                waterMar = stamper.getUnderContent(i);
                // 开始设置水印
                waterMar.beginText();
                // 设置透明度
                waterMar.setGState(gs);
                // 添加水印图片
                waterMar.addImage(image);
                //结束设置
                waterMar.endText();
                waterMar.stroke();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            waterMar = null;
            gs = null;
            // 关闭文档
            document.close();
            stamper.close();
            inputFile.close();
            resultOutFile.close();

        }


    }

    public static void main(String[] args) throws Exception {
        //创建文件夹目录
        String dirPath = "/export/home/releasePermitDownload";
        File baseDir = new File(dirPath);
        if (!baseDir.exists()) {
            boolean mkResult = baseDir.mkdirs();
            if (!mkResult) {
                logger.error("创建目录失败:{}", baseDir.getAbsolutePath());
                return;
            }
        }
        String baseDirPath = baseDir.getPath();
        String applyErp = "xiayanghui";
        File pdfFile = new File(baseDirPath + File.separator + applyErp + System.currentTimeMillis() + ".pdf");
        DmAgreemeetVo agre = new DmAgreemeetVo();
        agre.setTaskId("FXD00000000001");
        PdfTestServiceImpl pdfTestService = new PdfTestServiceImpl();
        // 生成pdf文件
        pdfTestService.createPdfFile(pdfFile, agre);

        // 加水印
        File pdfWatermarkFile = new File(baseDirPath + File.separator + applyErp + "Watermark" + System.currentTimeMillis() + ".pdf");
        pdfTestService.waterMarkWidthImage(pdfFile, pdfWatermarkFile);

        // 记得最后删除文件
        pdfFile.delete();
        //pdfWatermarkFile.delete();


    }

}



你可能感兴趣的:(itextpdf生成pdf文件并追加页码)