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.