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(); } }
  • 相关阅读:
    excel读取表,并将结果保存为键值对的字典列表;
    [置顶] MQ选型对比RabbitMQ RocketMQ ActiveMQ Kafka
    ActiveMQ持久化消息的三种方式
    getConstructor、getDeclaredConstructor区别
    JavaEE 保存文件获取绝对路径getResource("")和servletContext.getRealPath("/")
    Java中getResourceAsStream的用法
    Java 输出流中的flush方法
    Java之关闭流
    Java中的字节流、缓冲流
    java原生序列化和Kryo序列化性能比较
  • 原文地址:https://www.cnblogs.com/sjzxs/p/11189913.html
Copyright © 2011-2022 走看看