JAVA PDF简单操作(输入、加密、伪水印)

在JAVA使用IText对PDF进行操作(网上例子很多)

http://www.ibm.com/developerworks/cn/opensource/os-javapdf/

 

当然这里要讲下中文问题,中文需要iTextAsian.jar

 

import com.lowagie.text.Font;

 

......

document.add(new Paragraph("这里是中文",FontChinese)); 

......

 

加密

Itext中我加密没成功过所以我选择PDFBox

 

public void PDFadmin(String filepath)
 {
  try
  {
      PDDocument pdf =
   PDDocument.load(filepath);
   //create the encryption options
   PDStandardEncryption encryptionOptions =
   new PDStandardEncryption();
   encryptionOptions.setCanPrint( false );
   pdf.setEncryptionDictionary(
   encryptionOptions );
   //encrypt the document
   pdf.encrypt( "master", "admin" );
   
   System.out.println("isEncrypted : " + pdf.isEncrypted());
   //save the encrypted document
   //to the file system
   pdf.save(filepath);
  }
  catch (Exception e) {
   // TODO: handle exception
  }
 }

 

   其中admin是密码,网上有很多例子写的是是null 然后都是只加密没密码(晕这算加密),你可以随便改成你想要的密码。

 

水印这个真的要请高人了,现在最多是加图片(而且会与密码冲突,导致图片变色,可能是图片的原因),你可以边输入边插入图片、也可以输入完再插入图片

 

   PdfReader reader = new PdfReader("h:\\ITextTest.pdf", "World".getBytes());
   PdfStamper stamp = new PdfStamper(reader, new FileOutputStream("h:\\ITextTest2.pdf"));
   Image img = Image.getInstance("d:\\watermark.gif");
   img.setAbsolutePosition(25, 0); //位置
   int total = reader.getNumberOfPages();
//      System.out.println(total);
   for(int i=1;i<=total;i++)
   {
    PdfContentByte under = stamp.getUnderContent(i);
    under.addImage(img);
   }
   stamp.close();

posted @ 2012-06-11 16:13  ajiaju  阅读(1115)  评论(0编辑  收藏  举报