PDF添加水印,PdfBox

PDF添加水印,PdfBox

1. 输出PDF为图片
ByteArrayInputStream inputStream = new ByteArrayInputStream(outStream.toByteArray()); //获取输入流
PDDocument doc = PDDocument.load(inputStream);//new 一个文档对象
PDFRenderer renderer = new PDFRenderer(doc);
BufferedImage image = renderer.renderImageWithDPI(0, 100, ImageType.ARGB);//new一个image对象
OutputStream pngOutPut = fileManagerUtils.getOutputStream(outPath);// 获取输出流
ImageIO.write(image, "png", pngOutPut);//输出PDF内容为图片
2. 为PDF添加图片水印
 PDDocument doc = null; //new 一个文档对象
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //输出流
 try {
     ByteArrayInputStream inputStream = new ByteArrayInputStream(pdfFile);//获取pdf文件输入流
     doc = PDDocument.load(inputStream);
     ByteArrayInputStream imageInputStream = new ByteArrayInputStream(image);//获取图片输入流
     BufferedImage bufferedImage = ImageIO.read(imageInputStream);//读取图片
     int width = bufferedImage.getWidth();
     int height = bufferedImage.getHeight();
     BufferedImage bufferedImageWithAlpha = new BufferedImage(width ,height, BufferedImage.TYPE_INT_ARGB);//new一个image对象
     //操作图片,alpha 为透明度
     Graphics2D g2 = (Graphics2D) bufferedImageWithAlpha.getGraphics();
     g2.drawImage(bufferedImage, 0, 0, width, height, null);
     for (int j1 = bufferedImageWithAlpha.getMinY(); j1 < bufferedImageWithAlpha.getHeight(); j1++) {
         for (int j2 = bufferedImageWithAlpha.getMinX(); j2 < bufferedImageWithAlpha.getWidth(); j2++) {
             int rgb = bufferedImageWithAlpha.getRGB(j2, j1);
             rgb = ((alpha * 255 / 10) << 24) | (rgb & 0x00ffffff);//alpha 此处为整数,计算后透明度为应 0-1的浮点数
             bufferedImageWithAlpha.setRGB(j2, j1, rgb);
         }
     }
     g2.drawImage(bufferedImageWithAlpha,0,0,null);
     g2.dispose();
     ByteArrayOutputStream outImage = new ByteArrayOutputStream();
     ImageIO.write(bufferedImageWithAlpha, formatName, outImage);
     PDPage page = doc.getDocumentCatalog().getPages().get( 0 );//获取PDF第一页
     //图片画到PDF上
     PDImageXObject xObject = PDImageXObject.createFromByteArray(doc,outImage.toByteArray(),imageName);
     PDPageContentStream contentStream = new PDPageContentStream(doc, page,PDPageContentStream.AppendMode.APPEND,true);
     contentStream.drawImage(xObject,x,y);
     contentStream.close();
     doc.save(byteArrayOutputStream);
 } finally {
     if (doc != null) {
         doc.close();
         byteArrayOutputStream.close();
     }
 }
3. PDF生成图片时碰到的bug

生成jpg有时候会黑图
解决: ImageIO使用argb操作jpg的bug.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值