给pdf加水印

来源:互联网 时间:1970-01-01

package com.form.test;import java.io.FileOutputStream;import java.io.IOException; import com.itextpdf.text.BaseColor;import com.itextpdf.text.Chunk;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.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; public class TestPriterWater { public static void main(String[] args) throws Exception { String pdfFilePath = "f:/itext-demo.pdf"; PdfReader pdfReader = new PdfReader("/home/xueqy/1.pdf"); // Get the PdfStamper object PdfStamper pdfStamper = new PdfStamper(pdfReader , new FileOutputStream( "/home/xueqy/2.pdf")); addWatermark(pdfStamper, "www.manualbirds.com"); pdfStamper.close(); } private static void addWatermark(PdfStamper pdfStamper , String waterMarkName) { PdfContentByte content = null; Rectangle pageRect = null; PdfGState gs = new PdfGState(); try { BaseFont base = BaseFont.createFont(); // 设置透明度为0.4 gs.setFillOpacity(0.4f); gs.setStrokeOpacity(0.4f); int toPage = pdfStamper.getReader().getNumberOfPages(); System.out.print(pdfStamper.getReader().getFileLength()+" :" +toPage); for (int i = 1; i <= toPage; i++) { pageRect = pdfStamper.getReader(). getPageSizeWithRotation(i); // 计算水印X,Y坐标 float x = pageRect.getWidth() / 2; float y = pageRect.getHeight() / 2; //获得PDF最顶层 content = pdfStamper.getOverContent(i); content.saveState(); // set Transparency content.setGState(gs); content.beginText(); content.setColorFill(BaseColor.GRAY); content.setFontAndSize(base, 24); // content.setFontAndSize( 20); content.showTextAligned(Element.ALIGN_CENTER , waterMarkName, 300, 350, 30); content.endText(); } } catch (Exception ex) { ex.printStackTrace(); } finally { content = null; pageRect = null; } } } 



相关阅读:
Top