下载文件同时添加水印文字

记录工作 记录生活

jfinal 添加附件 并上传水印文字(crm)

导入相关的pom文件

<dependency>
    <groupId>com.itextpdf.toolgroupId>
    <artifactId>xmlworkerartifactId>
    <version>5.5.10version>
dependency>
<dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>itextpdfartifactId>
    <version>5.5.10version>
dependency>

设置该工具类

  /**
     * @param inputFile 你的PDF文件地址
     * @param outputFile 添加水印后生成PDF存放的地址
     * @param waterMarkName 你的水印
     * @return
     */
    public static boolean waterMark(String inputFile,
                                    String outputFile, String waterMarkName) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
                    outputFile));
            //这里的字体设置比较关键,这个设置是支持中文的写法
            BaseFont base = BaseFont.createFont(PathKit.getWebRootPath() + "/upload/ttf/pf.ttf",
                    BaseFont.IDENTITY_H , BaseFont.EMBEDDED);// 使用系统字体
            int total = reader.getNumberOfPages() + 1;

            PdfContentByte under;
            Rectangle pageRect = null;
            for (int i = 1; i < total; i++) {
                pageRect = stamper.getReader().
                        getPageSizeWithRotation(i);
                // 计算水印X,Y坐标
                float x = pageRect.getWidth()/2;
                float y = pageRect.getHeight()/2-10;
                // 获得PDF最顶层
                under = stamper.getOverContent(i);
                under.saveState();
                // set Transparency
                PdfGState gs = new PdfGState();
                // 设置透明度为0.2
                gs.setFillOpacity(0.2f);
                under.setGState(gs);
                under.restoreState();
                under.beginText();
                under.setFontAndSize(base, 60);
                under.setColorFill(BaseColor.LIGHT_GRAY);

                // 水印文字成45度角倾斜
                under.showTextAligned(Element.ALIGN_CENTER
                        , waterMarkName, x,
                        y, 55);
                // 添加水印文字
                under.endText();
                under.setLineWidth(1f);
                under.stroke();
            }
            stamper.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

这里字体比较关键
下载文件同时添加水印文字_第1张图片

里面放这个代码,用来设置字体

苹方 常规

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab aspernatur consequatur distinctio eligendi eos esse harum illo iste libero magnam, natus quisquam quod repellat repudiandae rerum sapiente, similique. Amet beatae, consequuntur doloremque eaque eius eos, esse excepturi fuga harum numquam, placeat quae quas recusandae saepe sequi similique sunt vero voluptates.

代用工具类,编写相对应的接口,通过控制水印的开关 来进行是否添加水印

    /**
     * 获取附件地址
     */
    public void credit() {
        try {
            Map<String, Object> params = getParamsMap();
            Map<String, Object> paramss = new HashMap<>();
            Record record = Db.findFirst(
                    Db.getSqlPara("customer.customer_credit.queryCredit", params)
            );

            // 获取水印的开关
            Record status = Db.findFirst("select * from of_sys_param where param_name='mark_switch'");
            // 获取图片路径
			// Record Recordpath_status = Db.findFirst("select * from of_sys_param where param_name='mark_image'");
            if (status.getStr("param_value").equals("1")) {
				// ImageMarkUtile.waterMarkName(PathKit.getWebRootPath() + record.getStr("remark"), PathKit.getWebRootPath() + record.getStr("remark") + ".pdf", PathKit.getWebRootPath() + path_status.getStr("param_value"));
                Boolean b = PdfTextMarkUtil.waterMark(record.getStr("remark"), PathKit.getWebRootPath() + "/upload/image/" + record.getStr("name") + ".pdf", getUser().getLoginName());
                paramss.put("b", "T");
                paramss.put("name", record.getStr("name"));
                paramss.put("path", "/upload/image/" + record.getStr("name") + ".pdf");
                rendSuccessJson(paramss);
            } else {
                paramss.put("b", "F");
                paramss.put("name", record.getStr("name"));
                paramss.put("path", record.getStr("remark"));
                rendSuccessJson(paramss);
            }
        } catch (Exception e) {
            e.printStackTrace();
            rendFailedJson(ErrorCode.get("9999"));
        }
    }

页面上文件的下载

<input type="file" id="file" style="display: none">
<button
		class="layui-btn layui-btn-sm"
		type="button" onclick="download({{d.id}})"
>
	下载
button>

JS代码部分 这里主要关于文件下载的, 也是主要针对于pdf

<script>
    /**
     * 文件链接转文件流下载--主要针对pdf 解决谷歌浏览器a标签下载pdf直接打开的问题
     * @param url  :文件链接
     * @param fileName  :文件名;
     * @param type  :文件类型;
     */
    function fileLinkToStreamDownload(url, fileName, type) {
        console.log(url, fileName, type);
        var reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\/])+$/;
        // if (!reg.test(url)) {
        //     throw new Error("传入参数不合法,不是标准的文件链接");
        // } else {
            var xhr = new XMLHttpRequest();
            xhr.open('get', url, true);
            xhr.setRequestHeader('Content-Type', 'application/' + type);
            xhr.responseType = "blob";
            xhr.onload = function () {
                if (this.status == 200) {
                    //接受二进制文件流
                    var blob = this.response;
                    downloadExportFile(blob, fileName, type)
                }
            };
            xhr.send();
        // }
    }
    /**
     *下载导出文件
     * @param blob  :返回数据的blob对象或链接
     * @param tagFileName  :下载后文件名标记
     * @param fileType  :文件类 word(docx) excel(xlsx) ppt等
     */
    function downloadExportFile(blob, tagFileName, fileType) {
        var downloadElement = document.createElement('a');
        var href = blob;
        if (typeof blob === 'string') {
            downloadElement.target = '_blank';
        } else {
            href = window.URL.createObjectURL(blob); //创建下载的链接
        }
        downloadElement.href = href;
        downloadElement.download = tagFileName + '.' + fileType; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        if (typeof blob !== 'string') {
            window.URL.revokeObjectURL(href); //释放掉blob对象
        }

    }
</script>

连接口,传id 传入服务器的时候 要改成HTTPS 为了安全,一个是加水印 一个是不加水印的判断和控制

function download(id){
        $.post("${webroot}/admin/administrator/accessories.json",{id:id},function (res) {
            // window.open("${webroot}"+res.data.remark);
			var data = res.data;
			if(data.b == 'T'){
				fileLinkToStreamDownload("https://" + window.location.host + "${webroot}" + data.path, data.name, 'pdf')
			}else{
				fileLinkToStreamDownload(data.path, data.name, 'pdf')
			}
        })
    }
记录一下  。。 

你可能感兴趣的:(下载文件同时添加水印)