1. 程式人生 > >Pdf新增文字水印

Pdf新增文字水印

 

 

package com.zving.demo;

import java.awt.Color;  
import java.io.BufferedOutputStream;  
import java.io.File;  
import java.io.FileOutputStream;  
import com.lowagie.text.Element;   
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 class PdfWaterPrint { public static void main(String[] args) { try { // 目標pdf檔案 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("E:/BBB.pdf")));
// 源pdf檔案 setWatermark(bos, "E:/AAA.pdf",16); } catch (Exception e) { e.printStackTrace(); } } public static void setWatermark(BufferedOutputStream bos, String input, int permission){ try { PdfReader reader = new PdfReader(input); PdfStamper stamper
= new PdfStamper(reader, bos); int total = reader.getNumberOfPages() + 1; PdfContentByte content; BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); PdfGState gs = new PdfGState(); for (int i = 1; i < total; i++) { content = stamper.getOverContent(i);// 在內容上方加水印 gs.setFillOpacity(0.2f); content.beginText(); content.setColorFill(Color.LIGHT_GRAY); content.setFontAndSize(base, 50); content.setTextMatrix(70, 200); content.showTextAligned(Element.ALIGN_CENTER, "新聞記者證核發辦公室", 300,350, 55); content.setColorFill(Color.BLACK); content.setFontAndSize(base, 8); content.showTextAligned(Element.ALIGN_CENTER,"", 300, 10, 0); content.endText(); } stamper.close(); } catch (Exception e) { e.printStackTrace(); } } }

 

所需要得jar包