zoukankan      html  css  js  c++  java
  • java实现给pdf文件加水印!

    给pdf文档加水印!

    import java.awt.Color;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;

    import com.lowagie.text.DocumentException;
    import com.lowagie.text.Element;
    import com.lowagie.text.Image;
    import com.lowagie.text.pdf.BaseFont;
    import com.lowagie.text.pdf.PdfContentByte;
    import com.lowagie.text.pdf.PdfGState;
    import com.lowagie.text.pdf.PdfReader;
    import com.lowagie.text.pdf.PdfStamper;


    public static void waterMark(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.EMBEDDED); Rectangle pageRect = null; PdfGState gs = new PdfGState(); gs.setFillOpacity(0.3f); gs.setStrokeOpacity(0.4f); int total = reader.getNumberOfPages() + 1; JLabel label = new JLabel(); FontMetrics metrics; int textH = 0; int textW = 0; label.setText(waterMarkName); metrics = label.getFontMetrics(label.getFont()); textH = metrics.getHeight(); textW = metrics.stringWidth(label.getText()); PdfContentByte under; for (int i = 1; i < total; i++) { under = stamper.getOverContent(i);// 在内容上方加水印 //content = stamper.getUnderContent(i);//在内容下方加水印 gs.setFillOpacity(0.2f); // content.setGState(gs); under.beginText(); under.setFontAndSize(base, 50); under.setTextMatrix(70, 200); under.showTextAligned(Element.ALIGN_CENTER, "测试水印!", 300,350, 55); under.endText(); } //一定不要忘记关闭流 stamper.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } }
  • 相关阅读:
    【转载】MongoDB 数据库的备份与恢复
    【转载】Vim命令合集
    【转载】Mac 让 iTerm2 记住用户名密码
    CSS 实现单行、多行文本溢出显示省略号
    【转载】如何在Vue2中实现组件props双向绑定
    JavaScript 获取当日在今年第几周
    CentOS 7 安装配置FTP服务器(vsftpd)
    CentOS 7 防火墙(firewall)常用命令
    Vs Code 之 实现右键打开文件夹
    git 报错
  • 原文地址:https://www.cnblogs.com/sjzxs/p/11189913.html
Copyright © 2011-2022 走看看