java实现调⽤url来下载pdf并且加⽔印,追加excel转成pdf ⽔印jar包:
excel转pdf的jar包+license破解认证:
第⼀种:使⽤spire.pdf.jar包或者导⼊依赖。
<!--filtutil依赖-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<!--pdf依赖-->
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>2.2.2</version>
</dependency>
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>repo.e-iceblue/nexus/content/groups/public/</url>
</repository>
</repositories>
代码:
package ller;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.aphics.*;
slf4j.Slf4j;
import org.apachemons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import Dimension2D;
import Point2D;
import Rectangle2D;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.HttpURLConnection;
import java.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping(value = "/pdf")
public class PdfWaterMark {
@ResponseBody
@RequestMapping(value = "/loadPdf")
public void loadPdf(HttpServletRequest request, HttpServletResponse response) throws IOException {
String strUrl = "ip:port/apiIn/00000.pdf";
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//得到输⼊流
InputStream inputStream = InputStream();
String[] urlSplit = strUrl.split("/");
int i = urlSplit.length;
String[] nextSplit = urlSplit[urlSplit.length - 1].split("\\.");
//解析出名字
String fileName = nextSplit[0];
log.info("fileName:" + nextSplit[0]);
log.info("localdateTime:" + w() + ",localdate" + w());
/
/来使得唯⼀
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
String str = formatter.w());
for (int m = 1; m < 3; m++) {
int rd = (int) (Math.random() * 10);
str = str + rd;
}
//保存路径
String filePath = "D://" + nextSplit[0] + "-" + str + ".pdf";
java.io.File file = new java.io.File(filePath);
/
/获取当前登陆⽤户
//        Map<String,Object> map = UserController.findCurrentUser(request,response);
//        String name = (("name");
waterMark(filePath, "hlh");
}
public void waterMark(String inputPdf, String waterMarkName) {
//创建PdfDocument类的对象
PdfDocument pdf = new PdfDocument();
//加载测试⽂档
pdf.loadFromFile(inputPdf);
//获取⽂档第1页
PdfPageBase page = Pages().get(0);
//调⽤insertWatermark()⽅法插⼊⽂本⽔印
insertWatermark(page, waterMarkName);
//保存⽂档到指定⽂件夹
pdf.saveToFile(inputPdf);
//        pdf.saveToFile(inputPdf, FileFormat.PDF);
pdf.close();
}
static void insertWatermark(PdfPageBase page, String watermark) {
Dimension2D dimension2D = new Dimension();
dimension2D.Canvas().getClientSize().getWidth() / 2, Canvas().getClientSize().getHeight() / 2);
PdfTilingBrush brush = new PdfTilingBrush(dimension2D);
//这句话放在eclipse会有红线报错,但是⽆所谓,直接启动使⽤。
Rectangle2D loRect = new Rectangle2D.Float();
loRect.setFrame(new Point2D.Float(0, 0), Canvas().getClientSize());
}
}
第⼆种⽅式:jar包获取在最前⾯  itex的两个
依赖如下:
<!--itextpdf-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
代码:
package ller;
import Element;
import Rectangle;
import pdf.*;
slf4j.Slf4j;
import org.apachemons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.HttpURLConnection;
import java.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Slf4j
@RestController
@RequestMapping("/pdf2")
public class WaterMarkPdf {
@ResponseBody
@RequestMapping(value = "/loadPdf")
public void loadPdf(HttpServletRequest request, HttpServletResponse response) throws IOException {
String strUrl = "ip:port/apiIn/00000.pdf";
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//得到输⼊流
InputStream inputStream = InputStream();
String[] urlSplit = strUrl.split("/");
int i = urlSplit.length;
String[] nextSplit = urlSplit[urlSplit.length - 1].split("\\.");
//解析出名字
String fileName = nextSplit[0];
log.info("fileName:" + nextSplit[0]);
log.info("localdateTime:" + w() + ",localdate" + w());
//来使得唯⼀
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
String str = formatter.w());
for (int m = 1; m < 3; m++) {
int rd = (int) (Math.random() * 10);
str = str + rd;
}
//保存路径
String filePath = "D:\\" + nextSplit[0] + "-" + str + ".pdf";
java.io.File file = new java.io.File(filePath);
//获取当前登陆⽤户
//        Map<String,Object> map = UserController.findCurrentUser(request,response);
//        String name = (("name");
//        waterMark02(filePath, filePath,"hlh");
}
//    public void waterMark02(String inputPath,String outPutPath,String name){
@RequestMapping("/water")
public void waterMark02(){
String inputFile = "D:\\00000-2020040122333118.pdf";
String outputFile = "D:\\b.pdf";
String content = "hlh";
waterMark(inputFile, outputFile, content);
File f=new File(inputFile);
ists()){
f.delete();
}
// waterMark(inputPath, outPutPath, name);
/springframework jar包下载
/String base64String = getPDFBinary(outputFile);
//System.out.println(base64String);
//getText(outputFile);
}
//给PDF添加⽔印
//inputFile ⽂件路径+名称
//outputFile 添加⽔印后输出⽂件保存的路径+名称
//waterMarkName 添加⽔印的内容
public static void waterMark(String inputFile,String outputFile, String waterMarkName) {
int interval = -5;
try {
PdfReader reader = new PdfReader(inputFile);  //切记这⾥的参数是⽂件的路径,路径必须是双斜杠的如F:\\123.pdf,不能是F:/123.pdf 或者F:\123.pdf            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
outputFile));
BaseFont base = ateFont("STSong-Light", "UniGB-UCS2-H",  BaseFont.EMBEDDED);            Rectangle pageRect = null;
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.3f);//改透明度
gs.setStrokeOpacity(0.4f);
int total = NumberOfPages() + 1;
JLabel label = new JLabel();
FontMetrics metrics;
int textH = 0;
int textW = 0;
label.setText(waterMarkName);
metrics = Font());
textH = Height();
textW = metrics.Text());
PdfContentByte under;
//            for (int i = 1; i < total; i++) {
//                pageRect = PageSizeWithRotation(i);
//                under = OverContent(i);//在内容上⽅加⽔印
          under = UnderContent(i);//在内容下⽅加⽔印
/
/                under.saveState();
//                under.setGState(gs);
//                under.beginText();
//                under.setFontAndSize(base, 20);
// ⽔印⽂字成30度⾓倾斜
//                for (int height = interval + textH; height < Height();
//                    height = height + textH*3) {
//                    for (int width = interval + textW; width < Width() + textW;
//                        width = width + textW*2) {
//                        under.showTextAligned(Element.ALIGN_LEFT
//                                , waterMarkName, width - textW,
/
/                                height - textH, 30);
//                    }
//                }
// 添加⽔印⽂字
//                dText();
//            }
for (int i = 1; i < total; i++) {
under = OverContent(i);// 在内容上⽅加⽔印
//content = UnderContent(i);//在内容下⽅加⽔印
gs.setFillOpacity(0.2f);
// content.setGState(gs);
under.beginText();
under.setColorFill(BaseColor.RED);//改变颜⾊
under.setFontAndSize(base, 50);//改⽔印⽂字⼤⼩
under.setTextMatrix(70, 200);
          //后3个参数,x坐标,y坐标,⾓度
under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 350, 55);
}
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
后⾯追加功能。
execl⽂件转成pdf。
aspose的jar包,在maven中没,只能引⼊,看我其他某⼀篇随笔有说引⼊。
代码如下:
@RequestMapping(value="/excelCvPdfAddWaterMark")
public String excelCvPdfAddWaterMark(HttpServletRequest request) throws IOException{ String relativePath = ServletContext().getRealPath("fileDir");//获取相对路径File licensefile = new File(relativePath+"\\l");
String fileName = relativePath + "\\0B1002-01-13_A.1.xlsx";
if (!getExcelLicense(licensefile)) { // 验证License 若不验证则转化出的pdf⽂档会有⽔印产⽣return null;
}
FileOutputStream fileOS = null;
try {
long old = System.currentTimeMillis();
Workbook wb = new Workbook(fileName);// 原始excel路径
//fileName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + "pdf";
//来使得唯⼀
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
String str = formatter.w());
/
/保存路径
fileName = "D:\\"+ str + ".pdf";
File file = new File(fileName);// 输出路径
for (int i = 0; i < wb.getWorksheets().getCount(); i++) {
Worksheet worksheet = wb.getWorksheets().get(i);
}
//CellsHelper.setFontDir(FONT); // 这⾥是字体路径
fileOS = new FileOutputStream(file);
wb.save(fileOS, lls.SaveFormat.PDF);
fileOS.close();
long now = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOS != null) {
fileOS.close();
}
}
waterMark02(fileName);//调⽤⽅法去加⽔印,上⾯有代码
return "success";
}
/**
* Excel签名验证
*
* @return
* @throws IOException
* @throws Exception
*/
public static boolean getExcelLicense(File file) throws IOException {
boolean result = false;
InputStream is = null;
try {
//is = ResourceAsStream("l"); // l应放在..\WebRoot\WEB-INF\classes路径下
is = new FileInputStream(file);
lls.License aposeLic = new lls.License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
is.close();
}
}
return result;
}
/*
  追加,通过调⽤别⼈接⼝把excel下到本地服务器,通过返回状态码来判断成功失败(总结,也就是连接都可以通过⽤连接对象.getResponseCode()来获得http状态码,进⽽获取状态码相对应的信息)*/
public Map<String,Object> loadExcel(String excelFilePath,String userNum) throws IOException{
Map<String, Object> map2 = new HashMap<String, Object>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
String str = formatter.w());
InputStream inputStream = null;
try {
URL url = new URL(excelFilePath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String code = ResponseCode()+"";
if("200".equals(code)){
// 得到输⼊流

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。