• java实现调用url来下载pdf并且加水印,追加excel转成pdf


    水印jar包:

    jar包获取百度云:链接: https://pan.baidu.com/s/1x0qS1pxCn1Pn1TDFx2MyWg 提取码: 7iky 

     excel转pdf的jar包+license破解认证:

    链接:https://pan.baidu.com/s/1fRQNUEoq2D9_W10XTRp5hQ
    提取码:xibs

    第一种:使用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>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
    </repositories>

    代码:

    package com.yiyezhiqiu.compdfwatermark.controller;


    import com.spire.pdf.PdfDocument;
    import com.spire.pdf.PdfPageBase;
    import com.spire.pdf.graphics.*;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.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 java.awt.geom.Dimension2D;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.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 = "http://ip:port/apiIn/00000.pdf";
    URL url = new URL(strUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    //得到输入流
    InputStream inputStream = conn.getInputStream();
    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:" + LocalDateTime.now() + ",localdate" + LocalDate.now());
    //来使得唯一
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    String str = formatter.format(LocalDateTime.now());

    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);

    FileUtils.copyInputStreamToFile(inputStream, file);

    //获取当前登陆用户
    // Map<String,Object> map = UserController.findCurrentUser(request,response);
    // String name = (String)map.get("name");
    waterMark(filePath, "hlh");


    }


    public void waterMark(String inputPdf, String waterMarkName) {

    //创建PdfDocument类的对象
    PdfDocument pdf = new PdfDocument();

    //加载测试文档
    pdf.loadFromFile(inputPdf);

    //获取文档第1页
    PdfPageBase page = pdf.getPages().get(0);
    pdf.getPages().getCount();//文档总页数,就可以对文档中所有页数加水印,但Spire.pdf.jar免费10页。故找了另外的pdf加水印方式。
    //调用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.setSize(page.getCanvas().getClientSize().getWidth() / 2, page.getCanvas().getClientSize().getHeight() / 2);

    PdfTilingBrush brush = new PdfTilingBrush(dimension2D);

    brush.getGraphics().setTransparency(0.4F);

    brush.getGraphics().save();

    brush.getGraphics().translateTransform((float) brush.getSize().getWidth() / 2, (float) brush.getSize().getHeight() / 2);

    brush.getGraphics().rotateTransform(-45);
    //这句话放在eclipse会有红线报错,但是无所谓,直接启动使用。
    brush.getGraphics().drawString(watermark, new PdfTrueTypeFont(new Font("宋体", 10, 50), true), PdfBrushes.getViolet(), 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
    brush.getGraphics().restore();

    brush.getGraphics().setTransparency(1);


    Rectangle2D loRect = new Rectangle2D.Float();

    loRect.setFrame(new Point2D.Float(0, 0), page.getCanvas().getClientSize());

    page.getCanvas().drawRectangle(brush, loRect);

    }

    }






    第二种方式: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 com.yiyezhiqiu.comwaterpdf.controller;

    import com.itextpdf.text.Element;
    import com.itextpdf.text.Rectangle;
    import com.itextpdf.text.pdf.*;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.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.net.HttpURLConnection;
    import java.net.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 = "http://ip:port/apiIn/00000.pdf";
    URL url = new URL(strUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    //得到输入流
    InputStream inputStream = conn.getInputStream();
    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:" + LocalDateTime.now() + ",localdate" + LocalDate.now());
    //来使得唯一
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    String str = formatter.format(LocalDateTime.now());

    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);

    FileUtils.copyInputStreamToFile(inputStream, file);

    //获取当前登陆用户
    // Map<String,Object> map = UserController.findCurrentUser(request,response);
    // String name = (String)map.get("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);
    if(f.exists()){
    f.delete();
    }
    // waterMark(inputPath, outPutPath, name);
    //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 = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

    Rectangle pageRect = null;
    PdfGState gs = new PdfGState();
    gs.setFillOpacity(0.3f);//改透明度
    gs.setStrokeOpacity(0.4f);
    int total = reader.getNumberOfPages() + 1;

    JLabel label = new JLabel();
    FontMetrics metrics;
    int textH = 0;
    int textW = 0;
    label.setText(waterMarkName);
    metrics = label.getFontMetrics(label.getFont());
    textH = metrics.getHeight();
    textW = metrics.stringWidth(label.getText());

    PdfContentByte under;
    // for (int i = 1; i < total; i++) {
    // pageRect = reader.getPageSizeWithRotation(i);
    // under = stamper.getOverContent(i);//在内容上方加水印
               under = stamper.getUnderContent(i);//在内容下方加水印
    // under.saveState();
    // under.setGState(gs);
    // under.beginText();
    // under.setFontAndSize(base, 20);

    // 水印文字成30度角倾斜
    // 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);
    // }
    // }


    // 添加水印文字
    // under.endText();
    // }


    for (int i = 1; i < total; i++) {
    under = stamper.getOverContent(i);// 在内容上方加水印
    //content = stamper.getUnderContent(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);


    under.endText();
    }
    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 = request.getServletContext().getRealPath("fileDir");//获取相对路径
    File licensefile = new File(relativePath+"\license.xml");

    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.format(LocalDateTime.now());

    //保存路径
    fileName = "D:\"+ str + ".pdf";
    File file = new File(fileName);// 输出路径
    for (int i = 0; i < wb.getWorksheets().getCount(); i++) {
    Worksheet worksheet = wb.getWorksheets().get(i);
    worksheet.getPageSetup().setCenterHorizontally(true);//水平居中
    worksheet.getPageSetup().setZoom(90);// 设置缩放比例
    }
    //CellsHelper.setFontDir(FONT); // 这里是字体路径
    fileOS = new FileOutputStream(file);
    wb.save(fileOS, com.aspose.cells.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 = PdfController.class.getResourceAsStream("license.xml"); // license.xml应放在..WebRootWEB-INFclasses路径下
    is = new FileInputStream(file);
    com.aspose.cells.License aposeLic = new com.aspose.cells.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.format(LocalDateTime.now());

    InputStream inputStream = null;
    try {
    URL url = new URL(excelFilePath);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    String code = conn.getResponseCode()+"";
    if("200".equals(code)){
    // 得到输入流
    inputStream = conn.getInputStream();
    }
    if("400".equals(code)){
    BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String lines;
    StringBuffer sb=new StringBuffer("");
    while((lines = reader.readLine())!=null){
    lines =new String(lines.getBytes(),"utf-8");
    sb.append(lines);
    }
    String jsonStr = new String(sb);
    JSONObject jsonObject = JSONObject.parseObject(jsonStr);
    String msg = jsonObject.getString("msg");
    map2.put("status", "false");
    map2.put("msg", msg);
    map2.put("path", "");
    return map2;
    }
    } catch (Exception e) {
    map2.put("path", "");
    map2.put("msg", "系统连接异常");
    map2.put("status", "false");
    return map2;
    }




  • 相关阅读:
    js高级-闭包
    js作用域
    js执行上下文与执行上下文栈
    js原型及原型链
    去除数组中重复的元素值
    树[省选联考2020]
    GDOI2020 游记
    Problem b[HAOI2011]
    分零食[JSOI2012]
    移动金币「SDOI2019」
  • 原文地址:https://www.cnblogs.com/yiyezhiqiuwuchen/p/12620581.html
Copyright © 2020-2023  润新知