之前写了普通的文件上传,考虑到可能有些公司的文件会有版权问题,因此加上带水印的文件上传功能。
controller:
/**
* 文件上传带水印格式,支持PDF/图片
* @param file
* @param mark
* @param dto
* @param local 0中心水印,1四角水印,2循环全覆盖水印
* @return ResultDto
*/
@Autowired
PDFBoxUtils pDFBoxUtils;
@ApiOperation(value="文件上传带水印格式,支持PDF/图片", notes="null")
@PostMapping(value = "/dfsuploadmark")
public ItsSingleResultDto dfsUploadmark(
@ApiParam(value = "文件", required = true) @RequestParam( value="file", required = true) MultipartFile file,
@ApiParam(value = "水印文字", required = true) @RequestParam( value="mark", required = true) String mark,
@ApiParam(value = "文件信息", required = true) @ModelAttribute FileQueryDto dto,
@ApiParam(value = "位置", required = true) @RequestParam( value="local", required = true) String local
){
ItsSingleResultDto<FileDto> result = new ItsSingleResultDto<FileDto>();
FileDetailDto newdto = new FileDetailDto();
String name = file.getOriginalFilename();
String staffCode = this.getStaffCode();
String suffix = name.substring(name.lastIndexOf(".") + 1, name.length());
UploadDto uploadDto = new UploadDto();
java.io.File f = new java.io.File(name);
byte[] buffer = null;
try {
buffer = file.getBytes();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
uploadDto.setFile(buffer);
uploadDto.setFileName(name);
java.io.File filenew = new java.io.File("./" + uploadDto.getFileName());
Map<String, String> metaList = new HashMap<String, String>();
try {
FileOutputStream fstream = new FileOutputStream(filenew);
BufferedOutputStream stream = new BufferedOutputStream(fstream);
stream.write(uploadDto.getFile());
//----------------------------判断文件类型,并加水印-------------------------
try {
if (suffix.equals("pdf") || suffix.equals("PDF")) {
uploadDto.setFile(pDFBoxUtils.watermarkPDF(filenew, mark, local));
} else {
Image image = ImageIO.read(filenew);
if (image != null) {
uploadDto.setFile(pDFBoxUtils.addWaterMark(filenew, mark, local));
}
}
// filenew.delete();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//------------------进行文件上传-----------------------------------
String backpath = fastDFSClient.uploadFile(uploadDto.getFile(), uploadDto.getFileName(), metaList);
while (StringUtils.isEmpty(backpath)) {
backpath = fastDFSClient.uploadFile(uploadDto.getFile(), uploadDto.getFileName(), metaList);
System.out.println("00000+" + backpath);
}
System.out.println(backpath);
filenew.delete();
//----------------自己的业务逻辑-----------------------------------------------------
BeanUtils.copyProperties(dto, newdto);
// newdto.setPath(fileName);
newdto.setFilename(name);
newdto.setSize(file.getSize());
newdto.setType(suffix);
newdto.setFakepath(backpath);
newdto.setUploaderno(staffCode);
FileDto filedto = new FileDto();
BeanUtils.copyProperties(newdto, filedto);
// 插入主表
filedto.setDownloadcount(0);
// 当前系统时间
// Date day=new Date();
Date day = com.dhc.its.utils.GlobalHelper.getDateTime();
System.out.println("11111111111+" + day);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
filedto.setUploadtime(df.format(day));
if (StringUtils.isEmpty(dto.getIsAuth()) || dto.getIsAuth().equals("")) {
filedto.setIsauth(Constant.NOT_DELETE);
} else {
filedto.setIsauth(dto.getIsAuth());
}
// filedto.setUploadtime(day);
FileDto res = BeanMapper.map(fileAS.save(BeanMapper.map(filedto, File.class)), FileDto.class);
dto.setFileuid(res.getFileuid());
res.setFakepath(null);// 屏蔽fakepath
// 循环插入标签表
FileTagDto fileTagDto = new FileTagDto();
if (StringUtils.isEmpty(dto.getFileuid()) && StringUtils.isEmpty(dto.getTagid())) {
} else {
String tagarr[] = dto.getTagid().split(",");
for (int i = 0; i < tagarr.length; i++) {
dto.setTagid(tagarr[i]);
BeanUtils.copyProperties(dto, fileTagDto);
Boolean fileTag = fileTagAS.create(BeanMapper.map(fileTagDto, FileTag.class));
// FileTagDto result1 = BeanMapper.map(fileTag, FileTagDto.class);
}
}
result.setCode(ResultCodeEnum.SUCCESS.getCode());
result.setMessage(ResultCodeEnum.SUCCESS.getMessage());
result.setData(res);
return result;
}
完整的PDFBoxUtils的方法:
package com.***.***.file.utils;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JLabel;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;
import org.csource.common.MyException;
import org.csource.fastdfs.StorageClient1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
@Component
public class PDFBoxUtils {
@Autowired
private FastDFSClient storageClient1;
/**
* pdf/图片水印下载
*
* @param response
* @param filePath
* @param fileName
* void
* @return
*/
public byte[] dfsdownloadmark(HttpServletResponse response, String filePath,String mark, String fileName,String UserAgent,String suffix,String local) throws IOException {
java.io.File filenew = new java.io.File("./"+fileName);
String path=filePath.substring(filePath.indexOf("/")+1,filePath.length());
String group=filePath.substring(0,filePath.indexOf("/"));
BufferedInputStream bis = null;
BufferedOutputStream os = null; // 输出流
File targetFile = new File(path);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
response.setContentType("application/force-download");
try {
if (UserAgent.contains("MSIE") || UserAgent.contains("like Gecko") ) {
// win10 ie edge 浏览器 和其他系统的ie
fileName = URLEncoder.encode(fileName, "UTF-8");
}
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
mark = URLEncoder.encode(mark, "UTF-8");
mark = new String(mark.getBytes("utf-8"), "iso-8859-1");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] buffer2 = null;
FileOutputStream fstream = new FileOutputStream(filenew);
try {
byte[] content = null;
try {
content = storageClient1.storageClient1.download_file(group, path);
} catch (MyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream inputStream = new ByteArrayInputStream(content);
//fis = urlconn.getInputStream();
buffer2 = new byte[1024];
// OutputStream os = null; //输出流
//outs = response.getOutputStream();// 获取文件输出IO流
//os = new BufferedOutputStream(outs);
bis = new BufferedInputStream(inputStream);
os = new BufferedOutputStream(fstream);
int i;
while ((i = bis.read(content)) != -1) {
os.write(content, 0, i);
}
os.flush();
os.close();
bis.close();
//System.out.println("first");
if(suffix.equals("pdf")||suffix.equals("PDF")) {
buffer2 = this.watermarkPDF(filenew,mark,local);
//System.out.println("111");
}else {
Image image = ImageIO.read(filenew);
if(image != null) {
//mark = "jpgtest";
buffer2 = this.addWaterMark(filenew,mark,local);
//System.out.println("222");
}
}
filenew.delete();
//System.out.println("last");
// System.out.println("00000000+"+"输出end");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// System.out.println("00000000+"+"11111");
/*os.flush();
os.close();
bis.close();
urlconn.disconnect();*/
}
return buffer2;
}
public Image perreview(HttpServletResponse response, String filePath, String fileName,String UserAgent) throws IOException {
Image image = null;
java.io.File filenew = new java.io.File("./"+fileName);
String path=filePath.substring(filePath.indexOf("/")+1,filePath.length());
String group=filePath.substring(0,filePath.indexOf("/"));
BufferedInputStream bis = null;
BufferedOutputStream os = null; // 输出流
File targetFile = new File(path);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
response.setContentType("application/force-download");
try {
if (UserAgent.contains("MSIE") || UserAgent.contains("like Gecko") ) {
// win10 ie edge 浏览器 和其他系统的ie
fileName = URLEncoder.encode(fileName, "UTF-8");
}
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] buffer2 = null;
FileOutputStream fstream = new FileOutputStream(filenew);
try {
byte[] content = null;
try {
content = storageClient1.storageClient1.download_file(group, path);
} catch (MyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream inputStream = new ByteArrayInputStream(content);
//fis = urlconn.getInputStream();
buffer2 = new byte[1024];
// OutputStream os = null; //输出流
//outs = response.getOutputStream();// 获取文件输出IO流
//os = new BufferedOutputStream(outs);
bis = new BufferedInputStream(inputStream);
os = new BufferedOutputStream(fstream);
int i;
while ((i = bis.read(content)) != -1) {
os.write(content, 0, i);
}
os.flush();
os.close();
bis.close();
//System.out.println("first");
image = ImageIO.read(filenew);
//filenew.delete();
//System.out.println("last");
// System.out.println("00000000+"+"输出end");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// System.out.println("00000000+"+"11111");
/*os.flush();
os.close();
bis.close();
urlconn.disconnect();*/
}
return image;
}
/**
* 图片加水印
* @param srcImgPath
* @param tarImgPath
* @param waterMarkContent
* @param markContentColor
* @param font
*/
public byte[] addWaterMark (File fileStored,String mark,String local) throws Exception {
//File tmpPDF;
byte[] byt = null;
// 读取原图片信息
// File srcImgFile = new File(srcImgPath);//得到文件
Image srcImg = ImageIO.read(fileStored);//文件转化为图片
int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
int srcImgHeight = srcImg.getHeight(null);//获取图片的高
// 加水印
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufImg.createGraphics();
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
int fontSize = 50;
Font font = new Font("微软雅黑", Font.PLAIN, fontSize);
mark = URLDecoder.decode(mark, "UTF-8");
PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
// 透明度
float alpha = 0.3f; // 透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
g.setColor(Color.GRAY);//Red
g.setFont(font); //设置字体
//设置水印的坐标
//int x = srcImgWidth-srcImgWidth;//+ getWatermarkLength(mark, g);
//int y = srcImgHeight-srcImgHeight;//+getWatermarkLength(mark, g);
if(local.equals("0")) {
g.drawString(mark, (srcImgWidth-getWatermarkLength(mark, g))/2, (srcImgHeight-fontSize)/2+fontSize); //画出中间水印
}
if(local.equals("1")) {
g.drawString(mark, srcImgWidth-getWatermarkLength(mark, g), fontSize); //画出右上水印
g.drawString(mark, 0, fontSize/*getWatermarkLength(mark, g)*/); //画出左上水印
g.drawString(mark, srcImgWidth-getWatermarkLength(mark, g), srcImgHeight); //画出右下水印
g.drawString(mark, 0, srcImgHeight); //画出左下水印
}
if(local.equals("2")) {//全屏水印
g.rotate (Math.toRadians (-20), (double) bufImg.getWidth () / 2, (double) bufImg.getHeight () / 2);//角度偏移
final int XMOVE = 60;
// 水印之间的间隔
final int YMOVE = 60;
int x = 0;
int y = fontSize;
int markWidth = getWatermarkLength(mark, g);// 字体长度
int markHeight = fontSize;// 字体高度
// 循环添加水印
while (x < 1.5*(srcImgWidth-getWatermarkLength(mark, g))) {
y = fontSize;
while (y < srcImgHeight*2) {
g.drawString (mark, x, y);
y += markHeight + YMOVE;
}
x += markWidth + XMOVE;
}
}
//System.out.println((srcImgWidth-getWatermarkLength(mark, g))+"+"+(srcImgWidth-getWatermarkLength(mark, g))/2+"+0+"+(srcImgWidth-getWatermarkLength(mark, g))/2+"+"+(srcImgWidth-getWatermarkLength(mark, g)));
g.dispose();
// 输出图片
/* try {
FileInputStream stream = new FileInputStream(bufImg);
ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while((n = stream.read(b))!=-1) {
out.write(b,0,n);
}
stream.close();
out.close();
byt = out.toByteArray();
}catch(IOException e){
}*/
/* try {
FileInputStream stream = new FileInputStream(tmpPDF);
ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while((n = stream.read(b))!=-1) {
out.write(b,0,n);
}
stream.close();
out.close();
byt = out.toByteArray();
}catch(IOException e){
}
return byt;
*/
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bufImg, "jpg", bos);
bos.close();
byt = bos.toByteArray();
fileStored.delete();
return byt;
//return byt;
/*FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
ImageIO.write(bufImg, "jpg", outImgStream);
System.out.println("添加水印完成");
outImgStream.flush();
outImgStream.close(); */
}
/**
* 获取水印长度
* @param waterMarkContent
* @param g
* @return
*/
public int getWatermarkLength(String waterMarkContent, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
}
/**
* 暂未使用
* @param text
* @return
*/
private static int getTextLength (String text) {
int length = text.length ();
for (int i = 0; i < text.length (); i++) {
String s = String.valueOf (text.charAt (i));
if (s.getBytes ().length > 1) {
length++;
}
}
length = length % 2 == 0 ? length / 2 : length / 2 + 1;
return length;
}
/**
* PDF itext水印
*/
public byte[] watermarkPDF (File fileStored,String mark,String local) throws Exception {
//File tmpPDF;
Document doc;
byte[] byt = null;
//FileOutputStream outs = new FileOutputStream(fileStored.getParent()+ System.getProperty("file.separator")+"tem_"+fileStored.getName());
//tmpPDF = new File(fileStored.getParent() + System.getProperty("file.separator")+fileStored.getName());
PdfReader reader = new PdfReader(fileStored.getParent()+ System.getProperty("file.separator") +fileStored.getName());
PdfReader.unethicalreading = true;
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(fileStored.getParent()+ System.getProperty("file.separator")+"tem_"+fileStored.getName()));
String ts = mark;
ts = URLDecoder.decode(ts, "UTF-8");
PdfContentByte under = null;
//PdfWriter pdfWriter = PdfWriter.getInstance(doc, new FileOutputStream(fileStored.getParent() + System.getProperty("file.separator")+fileStored.getName()));
// 加入水印
//PdfContentByte waterMar = pdfWriter.getDirectContentUnder();
// 开始设置水印
// 设置水印透明度
PdfGState gs = new PdfGState();
// 设置填充字体不透明度为0.4f
gs.setFillOpacity(0.3f);
//gs.setStrokeOpacity(0.2f);
int total = reader.getNumberOfPages() + 1;
JLabel label = new JLabel();
FontMetrics metrics;
float textH = 0;
float textW = 0;
label.setText(ts);
metrics = label.getFontMetrics(label.getFont());
textH = metrics.getHeight();
textW = metrics.stringWidth(label.getText());
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
Rectangle pageRect = null;
for (int i = 1; i < total; i++) {
pageRect = reader.getPageSizeWithRotation(i);
under = stamper.getOverContent(i);
under.saveState();
under.setGState(gs);
under.beginText();
under.setFontAndSize(base, 50);
under.setColorFill(BaseColor.GRAY);
// 水印文字成30度角倾斜
//你可以随心所欲的改你自己想要的角度
//under.beginText();
BufferedImage bufImg = new BufferedImage((int)pageRect.getWidth(), (int) pageRect.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufImg.createGraphics();
Font fontnew = new Font("STSong-Light", Font.PLAIN,50);
g.setFont(fontnew);
float ax = getWatermarkLength(ts,g);
ax =(float) (1.5*ax);
if(local.equals("0")) {
//page.getMatrix().getScaleX();
under.setTextMatrix((pageRect.getWidth()-ax)/2,(pageRect.getHeight()-50)/2);
under.showText(ts);
//画出中间水印
/*for (int height = interval + textH; height < pageRect.getHeight();
height = height + textH*3) {
for (int width = interval + textW; width < pageRect.getWidth() + textW;
width = width + textW*2) {
under.showTextAligned(Element.ALIGN_LEFT
, waterMarkName, width - textW,
height - textH, 30);
}
} */
}
if(local.equals("1")) {
//doc.getPage(page.getRotation()).getMediaBox().getUpperRightX()
//System.out.println(pageRect.getWidth()+"+"+textW+"+"+ax+"+"+pageRect.getHeight()+"+");
under.setTextMatrix(pageRect.getWidth()-ax,0);//右下
under.showText(ts);
under.setTextMatrix(pageRect.getWidth()-ax,pageRect.getHeight()-50);//右上
under.showText(ts);
under.setTextMatrix(0,0);//左下
under.showText(ts);
under.setTextMatrix(0,pageRect.getHeight()-50);//左上
under.showText(ts);
/* g.drawString(mark, srcImgWidth-getWatermarkLength(mark, g), fontSize); //画出右上水印
g.drawString(mark, 0, fontSizegetWatermarkLength(mark, g)); //画出左上水印
g.drawString(mark, srcImgWidth-getWatermarkLength(mark, g), srcImgHeight); //画出右下水印
g.drawString(mark, 0, srcImgHeight); //画出左下水印
*/ }if(local.equals("2")) {
//cs.setTextMatrix(Matrix.getRotateInstance(20,350,400));
final int XMOVE = 150;
// 水印之间的间隔
final int YMOVE = 150;
int x = 15;
float y = 0;
float markWidth = textW;//getTextLength(ts);// 字体长度
float markHeight = textH;// 字体高度
// 循环添加水印
while (x < 2000) {
y = textH;
while (y < 2000) {
under.showTextAligned(Element.ALIGN_LEFT
,ts, x,
y, 20);
//under.showText(ts);
y += markHeight + YMOVE;
}
x += markWidth + XMOVE;
}
}
// 添加水印文字
under.endText();
//under.stroke();
}
//一定不要忘记关闭流
stamper.close();
reader.close();
try {
File tmpPDF = new File(fileStored.getParent() + System.getProperty("file.separator")+fileStored.getName());
File tmpPDF2 = new File(fileStored.getParent() + System.getProperty("file.separator")+"tem_"+fileStored.getName());
FileInputStream stream = new FileInputStream(tmpPDF2);
ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while((n = stream.read(b))!=-1) {
out.write(b,0,n);
}
stream.close();
out.close();
//doc.close();
tmpPDF.delete();
tmpPDF2.delete();
byt = out.toByteArray();
fileStored.delete();
}catch(IOException e){
}
return byt;
}
}
UpLoadDto:
package com.dhc.its.file.interfaces.dto;
import com.dhc.its.base.BaseDto;
import java.math.*;
import java.io.*;
import io.swagger.annotations.*;
import java.util.*;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
@ApiModel(description ="")
public class UploadDto extends BaseDto {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value="", required=false)
private byte[] file;
@ApiModelProperty(value="", required=false)
private String filePath;
@ApiModelProperty(value="", required=false)
private String fileName;
@ApiModelProperty(value="", required=false)
private File filed;
/**
* @return byte[]
*/
public byte[] getFile() {
return file;
}
/**
* @param byte[]
*/
public void setFile(byte[] file) {
this.file = file;
}
/**
* @return String
*/
public String getFilePath() {
return filePath;
}
/**
* @param String
*/
public void setFilePath(String filePath) {
this.filePath = filePath;
}
/**
* @return String
*/
public String getFileName() {
return fileName;
}
/**
* @param String
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* @return File
*/
public File getFiled() {
return filed;
}
/**
* @param File
*/
public void setFiled(File filed) {
this.filed = filed;
}
}