1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| import org.apache.pdfbox.pdmodel.PDDocument;
@Slf4j @Service public class PdfWatermarkServiceImpl implements WatermarkService {
@Override public boolean support(String type) { return StringUtils.equalsIgnoreCase("PDF", type); }
@Override public OutputStream add(InputStream inputStream, OutputStream outputStream, String text) throws IOException { if (ignore(text)) return outputStream; try { PDDocument doc = PDDocument.load(inputStream); doc.setAllSecurityToBeRemoved(true); Double diagonal = getDiagonal(doc); ImageGeneratorUtil.ImageMessage image = getImage(text, diagonal); PdfWatermarkUtil.addSingleDiagonalWaterMarkToPdf(doc, image, outputStream); } catch (Exception e) { log.error("exception message ", e); } return outputStream; } public static ImageMessage getImage(String text, Double maxWidth) throws IOException { BufferedImage image = generateTransparentImage(text, maxWidth); ...... return new ImageMessage(image.getWidth(), image.getHeight(), pathname.toAbsolutePath().toString()); } public static BufferedImage generateTransparentImage(String text, double diagonalLength) { float fontSize = 8.0f; Font font; diagonalLength = 0.8f * diagonalLength;
BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = image.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
FontRenderContext frc = g2d.getFontRenderContext(); Rectangle2D bounds; double currentDiagonal; int width = 0, height = 0; font = FontLoaderUtil.getFont(fontSize); g2d.dispose();
image = new BufferedImage(width + 20, height, BufferedImage.TYPE_INT_ARGB); g2d = image.createGraphics(); setGraphicsHints(g2d); g2d.setFont(font); drawText(g2d, text, width, height, frc);
g2d.dispose(); return image; } public static void addSingleDiagonalWaterMarkToPdf(PDDocument doc, ImageGeneratorUtil.ImageMessage img, OutputStream outputStream) throws IOException { try { doc.setAllSecurityToBeRemoved(true);
PDImageXObject pdImage = PDImageXObject.createFromFile(img.getFilePath(), doc); WatermarkOptions options = new WatermarkOptions() .size(img.getWidth(), img.getHeight()) .padding(10) .layout(4, 3) .rotate(30);
for (PDPage page : doc.getPages()) { addSingleDiagonalWaterMarkToPdf(doc, page, pdImage, options); } doc.save(outputStream); } finally { boolean delete = new File(img.getFilePath()).delete(); }
}
}
|
This is copyright.