当前位置: 首页 > 后端技术 > Java

java使用pdfbox给pdf文件添加图片水印,支持多行多列

时间:2023-04-02 02:09:39 Java

有时您需要为pdf添加水印。市面上的工具都是收费会员的,还是自己做吧;试试spire.pdf.free,超过10页就不行了!最终还是选择了使用Apache的pdfbox,没有限制!导入依赖org.apache.pdfboxpdfbox2.0.27代码调整参数:图片宽高,旋转角度,几行几列等包;进口组织.pdfbox。util.Matrix;导入java.io.File;导入java.io.IOException;公共类PdfUtils{publicstaticvoidmain(String[]args)throwsIOException{Stringfile="D:\\workspaces\\demo\\sjp-work-utils\\src\\main\\resources\\pdf\\AladdinStatistics平台SDK接入指南.pdf";StringimgPath="D:\\workspaces\\demo\\sjp-work-utils\\src\\main\\resources\\imgs\\logo.png";addImgWatermark(file,imgPath);}publicstaticvoidaddImgWatermark(StringfilePath,StringimgPath)抛出IOException{Stringname=filePath.substring(filePath.lastIndexOf(File.separator),filePath.lastIndexOf(".pdf"));Stringfolder=filePath.substring(0,filePath.lastIndexOf(File.separator));Filefile=newFile(filePath);try(PDDocumentdoc=PDDocument.load(file)){PDImageXObjectpdImage=PDImageXObject.createFromFile(imgPath,doc);WatermarkOptionsoptions=newWatermarkOptions().size(120,60).padding(20).layout(4,3)//建议0-90度.rotate(30);for(PDPagepage:doc.getPages()){addImgWatermark(文档,页面,pd图片,选项);}doc.save(folder+File.separator+name+"_WaterMark.pdf");}}privatestaticvoidaddImgWatermark(PDDocumentdoc,PDPagepage,PDImageXObjectpdImage,WatermarkOptionsoptions)抛出IOException{.getMediaBox().getWidth();floatheight=page.getMediaBox().getHeight();//System.out.println("width="+width+",height="+height);//有一些pdf页面是有角度旋转的,修改一下introtation=page.getRotation();//System.out.println("page.getRotation()="+rotation);switch(rotation){case90:width=page.getMediaBox().getHeight();height=page.getMediaBox().getWidth();cs.transform(Matrix.getRotateInstance(Math.toRadians(90),height,0));休息;案例180:cs.transform(Matrix.getRotateInstance(Math.toRadians(180),width,height));休息;案例270:width=page.getMediaBox().getHeight();height=page.getMediaBox().getWidth();cs.transform(Matrix.getRotateInstance(Math.toRadians(270),0,width));休息;默认值:中断;}PDExtendedGraphicsStategs=newPDExtendedGraphicsState();gs.setNonStrokingAlphaConstant(0.2f);//设置透明度gs.setAlphaSourceFlag(true);gs.setBlendMode(BlendMode.NORMAL);cs.setGraphicsStateParameters(gs);introw=options.row;intcolumn=options.column;浮动imgWidth=options.width;浮动imgHeight=options.height;浮动填充=options.padding;intdegree=options.degree;//计算每个单元格的宽和高floatcellWidth=(width-padding*2)/column;floatcellHeight=(height-padding*2)/row;//System.out.println("cellWidth="+cellWidth+",cellHeight="+cellHeight);//偏移量,如果单元格的宽高大于图片的宽高,这样可以使图片居中floatxOffset=padding+(cellWidth-imgWidth)/2;floatyOffset=padding+(cellHeight-imgHeight)/2;浮动x;浮动y;for(inti=0;i