当前位置: 首页 > news >正文

免费网站建站百度烟台建设信息网站

免费网站建站百度,烟台建设信息网站,网站开发文档撰写,WordPress附件下载插件通过文件路径获取文件,对不同类型的文件进行不同处理,将Word文件转成pdf文件预览,并早呢更加水印,暂不支持Excel文件,如果浏览器不支持PDF文件预览需要下载插件。文中currentUser.getUserid(),即为增加的水…

通过文件路径获取文件,对不同类型的文件进行不同处理,将Word文件转成pdf文件预览,并早呢更加水印,暂不支持Excel文件,如果浏览器不支持PDF文件预览需要下载插件。文中currentUser.getUserid(),即为增加的水印内容,需要替换掉,字符串类型的。

加水印用的包是pdfbox,不是itext7,这两个包有的方法名一致,但是穿的参数类型不一致,引用的包不对,会报错。BufferedImage引用的是java.awt.image.BufferedImage引用成pdfbox的也会报错,有报错的参数注意一下引用的包。

<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.24</version>
</dependency>
@RequestMapping("previewFile")public void download(String src,HttpServletRequest request,HttpServletResponse response) throws Exception {String filePath = src;System.out.println("filePath:" + filePath);File f = new File(filePath);if (!f.exists()) {response.sendError(404, "File not found!");return;}String fileName = f.getName();String extension = getFileExtension(f.getName());BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));byte[] bs = new byte[1024];int len = 0;response.reset(); // 非常重要URL u = new URL("file:///" + filePath);//String contentType = u.openConnection().getContentType();String contentType = "";if(extension.equals("pdf")){contentType = "application/pdf";br = addWatermarkToPdf(filePath, currentUser.getUserid());}else if (extension.equals("txt")){contentType = "text/plain";}else if (extension.equals("doc") || extension.equals("docx")){contentType = "application/pdf";try {br = convertToPdf(filePath,currentUser.getUserid());}catch (Exception e){}}else if (extension.equals("jpg") || extension.equals("jpeg")){contentType = "image/jpeg";br = createWatermarkedImage(filePath, currentUser.getUserid());}else if (extension.equals("png")){contentType = "image/png";br = createWatermarkedImage(filePath, currentUser.getUserid());}else if (extension.equals("gif")){contentType = "image/gif";br = createWatermarkedImage(filePath, currentUser.getUserid());}//Document docsss = new Document(filePath);response.setContentType(contentType+"; charset=UTF-8");response.setHeader("Content-Disposition", "inline;filename="+ fileName);// 文件名应该编码成utf-8,注意:使用时,我们可忽略这句OutputStream out = response.getOutputStream();while ((len = br.read(bs)) > 0) {out.write(bs, 0, len);}out.flush();out.close();br.close();}public static BufferedInputStream createWatermarkedImage(String imagePath, String watermarkText) throws IOException {// 读取原始图片File file = new File(imagePath);BufferedImage targetImg = ImageIO.read(new FileInputStream(file));int height = targetImg.getHeight();int width = targetImg.getWidth();//-------------------------文字水印 start----------------------------BufferedImage waterMarkImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 创建画笔Graphics2D graphics2D = waterMarkImage.createGraphics();// 绘制原始图片graphics2D.drawImage(targetImg, 0, 0, width, height, null);// 设置水印颜色graphics2D.setColor(new Color(255, 255, 255, 255));double scale = 1.0;if(width < height){scale = (double) width / height;}int fontSize = (int) Math.ceil((double) (height / 25) * scale);// 设置字体 画笔字体样式为微软雅黑,加粗,文字大小按比例给graphics2D.setFont(new Font("微软雅黑", Font.BOLD, fontSize));float alpha = 0.7f; // 设置透明度为50%AlphaComposite composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);graphics2D.setComposite(composite);// 水印旋转度graphics2D.rotate(Math.toRadians(-25), (double) width / 2, (double) height / 2);int x = -width * 3;int y;// 计算水印文字的宽度FontMetrics fontMetrics = graphics2D.getFontMetrics();int watermarkWidth = fontMetrics.stringWidth(watermarkText);// 水印横向间隔int positionWidth = (int)(width * 0.12);// 水印竖向间隔int positionHeight  = (int)(height * 0.12);while (x < width * 3) {y = -height * 3;while (y < height * 3) {graphics2D.drawString(watermarkText, x, y);y += fontSize + positionWidth;}x += watermarkWidth + positionHeight;}graphics2D.dispose();ByteArrayOutputStream outputStream = new ByteArrayOutputStream();ImageIO.write(waterMarkImage, "png", outputStream);byte[] imageBytes = outputStream.toByteArray();return new BufferedInputStream(new ByteArrayInputStream(imageBytes));}public static BufferedInputStream addWatermarkToPdf(String filePath,String userId) throws IOException {// 加载PDF文档PDDocument document = PDDocument.load(new File(filePath));try {// 遍历所有页面for (PDPage page : document.getPages()) {// 获取页面的媒体框(即页面的大小)PDRectangle mediaBox = page.getMediaBox();float pageWidth = mediaBox.getWidth();float pageHeight = mediaBox.getHeight();// 创建内容流,使用APPEND模式PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);// 设置水印字体和大小contentStream.setFont(PDType1Font.HELVETICA_BOLD, 36);// 设置水印颜色(RGB)contentStream.setNonStrokingColor(200, 200, 200);// 设置文本水印的参数String watermarkText = userId;PDType1Font font = PDType1Font.HELVETICA_BOLD;float fontSize = 20;float textWidth = font.getStringWidth(watermarkText) / 1000 * fontSize;float textHeight = fontSize;float xStep = pageWidth / 4; // 文本在x轴上的重复间隔float yStep = pageHeight / 12; // 文本在y轴上的重复间隔,可以根据需要调整// 绘制文本水印for (float y = 0; y < pageHeight; y += yStep) {for (float x = 0; x < pageWidth; x += xStep) {// 设置文本颜色(RGB),这里使用白色以确保在红色背景上可见contentStream.setStrokingColor(255, 255, 255);// 设置字体和大小contentStream.beginText();contentStream.setFont(font, fontSize);contentStream.newLineAtOffset(x, y);// 设置文本旋转//contentStream.newLineAtOffset(xx, yy);//contentStream.setTextMatrix(0, -0.5f, 0.5f, 0, 0, 0);contentStream.setTextMatrix(0.5f, 0.5f, -0.5f, 0.5f, x, y);contentStream.showText(watermarkText);contentStream.endText();}}// 关闭内容流contentStream.close();}ByteArrayOutputStream outputStream = new ByteArrayOutputStream();document.save(outputStream);document.close();return new BufferedInputStream(new ByteArrayInputStream(outputStream.toByteArray()));// 保存并关闭PDF文档//document.save(new File("watermarked.pdf"));//document.close();} finally {if (document != null) {document.close();}}}public static String getFileExtension(String fileName) {if (fileName == null || fileName.isEmpty()) {return "";}int dotIndex = fileName.lastIndexOf('.');if (dotIndex == -1 || dotIndex == fileName.length() - 1) {// No dot found or dot is at the end (e.g., "file.")return "";}return fileName.substring(dotIndex + 1);}public static BufferedInputStream convertToPdf(String wordFilePath,String userId) throws Exception {// 加载Word文档Document doc = new Document(wordFilePath);// 创建一个字节数组输出流来保存PDF内容ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();// 设置PDF保存选项(可选,这里使用默认设置)PdfSaveOptions saveOptions = new PdfSaveOptions();// 将文档保存为PDF格式到字节数组输出流中doc.save(byteArrayOutputStream, saveOptions);if (byteArrayOutputStream.size() == 0) {throw new IllegalArgumentException("ByteArrayOutputStream is empty");}// 将ByteArrayOutputStream的内容转换为ByteArrayInputStreamByteArrayInputStream bais = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());// 使用PDDocument.load方法将流转换为PDDocument对象PDDocument pdDocument = PDDocument.load(bais);// 关闭ByteArrayInputStreambais.close();// 将字节数组转换为字节输入流ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());// 返回BufferedInputStreamreturn addWatermarkToWord(pdDocument,userId);}public static BufferedInputStream addWatermarkToWord(PDDocument document,String userId) throws IOException {// 加载PDF文档//PDDocument document = PDDocument.load(new File(filePath));try {// 遍历所有页面for (PDPage page : document.getPages()) {// 获取页面的媒体框(即页面的大小)PDRectangle mediaBox = page.getMediaBox();float pageWidth = mediaBox.getWidth();float pageHeight = mediaBox.getHeight();// 创建内容流,使用APPEND模式PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);// 设置水印字体和大小contentStream.setFont(PDType1Font.HELVETICA_BOLD, 36);// 设置水印颜色(RGB)contentStream.setNonStrokingColor(200, 200, 200);// 设置文本水印的参数String watermarkText = userId;PDType1Font font = PDType1Font.HELVETICA_BOLD;float fontSize = 20;float textWidth = font.getStringWidth(watermarkText) / 1000 * fontSize;float textHeight = fontSize;float xStep = pageWidth / 4; // 文本在x轴上的重复间隔float yStep = pageHeight / 12; // 文本在y轴上的重复间隔,可以根据需要调整// 绘制文本水印for (float y = 0; y < pageHeight; y += yStep) {for (float x = 0; x < pageWidth; x += xStep) {// 设置文本颜色(RGB),这里使用白色以确保在红色背景上可见contentStream.setStrokingColor(255, 255, 255);// 设置字体和大小contentStream.beginText();contentStream.setFont(font, fontSize);contentStream.newLineAtOffset(x, y);// 设置文本旋转//contentStream.newLineAtOffset(xx, yy);//contentStream.setTextMatrix(0, -0.5f, 0.5f, 0, 0, 0);contentStream.setTextMatrix(0.5f, 0.5f, -0.5f, 0.5f, x, y);contentStream.showText(watermarkText);contentStream.endText();}}// 关闭内容流contentStream.close();}ByteArrayOutputStream outputStream = new ByteArrayOutputStream();document.save(outputStream);document.close();return new BufferedInputStream(new ByteArrayInputStream(outputStream.toByteArray()));// 保存并关闭PDF文档//document.save(new File("watermarked.pdf"));//document.close();} finally {if (document != null) {document.close();}}}

http://www.sczhlp.com/news/63922/

相关文章:

  • 七星彩的网站怎么做的大连网站建设佳熙科技公司
  • 建设部人力资源开发中心网站江苏省公路与水路建设网站
  • 站外推广网站经典的公司简介
  • 网站招牌模板小型企业网站建设项目
  • 如何创建网址免费注册北京厦门网站优化
  • 英文公司网站制作网页的过程
  • 龙华专业做网站昆明网站公司建设
  • 厦门网站设计制作济宁祥云网站建设
  • 深圳怎么做网站外贸网站如何引流
  • wordpress页脚内容居中seopc流量排名网站
  • 互动网络游戏公司网站建设添加到wordpress视频库中
  • 做网站需要买服务器吗网站开发产品需求说明
  • 做游戏网站用什么软件中小企业电商网站建设的重要性
  • 海誉网站定制特价旅游机票网站建设
  • 网站建设项目有哪些彬县网招聘
  • 自己制作小程序怎么做sem和seo是什么职位
  • 网站系统制作教程网站专题制作软件
  • 网站的域名怎么起学而思网校官网
  • 手机做网站空间泰安房产网签数据汇总
  • 3d地图网站模板html百度财报q3
  • 外贸高端网站开发昆明昌盛网络技术有限公司
  • 网站开发与部署题库汕头门户网站建设
  • 网站服务器租用价格怎么算wordpress 推酷
  • 为什么用html5做网站开发区人才市场官网
  • 网站验证码代码东莞手机微信网站
  • 怎么做可以支付的网站东莞住房和城乡建设厅网站
  • 吉林省网站建设网站建设费用预算模板
  • 织梦手机网站模板删除不了做手机网站和pc如何做
  • 网站服务器多少钱广州哪里能买到正品港版黄道益活络油
  • 企业建设网站的需求分析官方网站下载安装云支付