文件流回写客户端及pdf加解密去除水印

 <!-- itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.4</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.49</version>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcpkix-jdk15on</artifactId>
            <version>1.49</version>
        </dependency>
        <!-- pdf转image -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.24</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
package com.nzc.quartz.util.testPdf;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import java.io.File;
import java.io.IOException;

/**
 * 测试pdf加解密
 */
public class PdfSecurySuccess {

    public static void main(String[] args) {
        PDDocument document = null;
        try {
            document = PDDocument.load(new File("D:\\data\\front\\html\\tesst.pdf"));
            AccessPermission ap = new AccessPermission();
            ap.setCanPrint(true);
            ap.setCanModify(true);
            ap.setCanExtractContent(true);
            ap.setCanExtractForAccessibility(true);
            ap.setCanFillInForm(true);
            ap.setCanModifyAnnotations(true);
            ap.setCanAssembleDocument(true);
            ap.setCanExtractForAccessibility(true);
            StandardProtectionPolicy spp = new StandardProtectionPolicy("12345", "123456", ap);
            document.protect(spp);
            document.save("D:\\data\\front\\html\\test_pwd.pdf");
            //PDFBOX破解
//            PDDocument doc = PDDocument.load(new FileInputStream(new File("test_pwd.pdf")), "12345");
//            doc.setAllSecurityToBeRemoved(true);
//            doc.save("test_decrypted.pdf");
            //iText加密
//            PdfReader reader = new PdfReader("test.pdf");
//            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("test_pwd.pdf"));
//            stamper.setEncryption("12345".getBytes(), "ownerpassword".getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
//            stamper.close();
            //iText破解
//            PdfReader reader = new PdfReader("test_pwd.pdf", "12345".getBytes());
//            reader.setUnethicalReading(true);
//            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("test_decrypted.pdf"));
//            stamper.close();
            //addImgWatermark("D:\\data\\front\\html\\tessst.pdf","D:\\data\\front\\html\\test.png");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                document.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

package com.nzc.quartz.util.testPdf;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfReader;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;import java.awt.*;
import java.io.*;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * pdf添加水印机移除水印
 */
public class PdfatermarkSuccess{

    public static void main(String[] args) throws Exception {
        addWatermark(new File("D:\\pdf\\pdfToImage\\测试word转pdf.pdf"), "tarzan");
        removeWatermark(new File("D:\\pdf\\pdfToImage\\测试word转pdf_waterMark.pdf"));
        combinPdf(Arrays.asList("D:\\pdf\\pdfToImage\\测试word转pdf.pdf","D:\\pdf\\pdfToImage\\测试word转pdf_waterMark.pdf"),"测试合并.pdf");
    }

    /**
     *
     * pdf添加文字水印
     */
    private static void addWatermark(File file, String text) {
         try {
             PDDocument document = PDDocument.load(file);
             document.setAllSecurityToBeRemoved(true);
             for (PDPage page : document.getPages()) {
                 PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
                 //pdf扩展图形对象
                 PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
                 // 透明度
                 graphicsState.setNonStrokingAlphaConstant(0.2f);
                 graphicsState.setAlphaSourceFlag(true);
                 cs.setGraphicsStateParameters(graphicsState);
                 cs.setNonStrokingColor(Color.red);
                 //Red
                 cs.beginText();
                 cs.setFont(PDType1Font.HELVETICA_OBLIQUE, 50.0f);
                 // 获取旋转实例
                 cs.setTextMatrix(Matrix.getRotateInstance(20, 350f, 490f));
                 cs.showText(text);
                 cs.endText();
                 cs.close();
             }
             String folderPath= file.getParent();
             String fileName=file.getName().substring(0,file.getName().lastIndexOf("."));
             document.save(folderPath+File.separator+fileName+"_waterMark"+".pdf");
             document.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }

     /**
      * pdf去除水印
      */
     public static boolean removeWatermark(File file) {
         try{
             //通过文件名加载文档
             PDDocument document = PDDocument.load(file);
             PDPageTree pages = document.getPages();
             Iterator<PDPage> iter = pages.iterator();
             while(iter.hasNext()){
                 PDPage page = iter.next();
                 PDResources resources  =page.getResources();
                 resources.getExtGStateNames().forEach(ext->{
                     PDExtendedGraphicsState gState=resources.getExtGState(ext);
                     gState.setNonStrokingAlphaConstant(0.0f);
                 });
             }
             String folderPath= file.getParent();
             String fileName=file.getName().substring(0,file.getName().lastIndexOf("."));
             document.save(folderPath+File.separator+fileName+"_noMark"+".pdf");
             document.close();
             return true;
         } catch(IOException ex){
             ex.printStackTrace();
             return false;
         }
     }

    /***
     * 合并pdf文件
     * @param pdfFilenames
     * @param filename
     * @return
     * @throws Exception
     */
    public static String combinPdf(List<String> pdfFilenames, String filename) throws Exception {
        String targetFilename = "D:\\pdf\\pdfToImage\\" + filename;
        PdfReader reader = null;
        Document doc = new Document();
        PdfCopy pdfCopy = new PdfCopy(doc, new FileOutputStream(targetFilename));
        int pageCount = 0;
        doc.open();
        if (pdfFilenames.size()>0) {
            for (int i = 0; i < pdfFilenames.size(); ++i) {
                reader = new PdfReader(pdfFilenames.get(i));
                pageCount = reader.getNumberOfPages();
                for (int j = 1; j <= pageCount; ++j) {
                    pdfCopy.addPage(pdfCopy.getImportedPage(reader, j));
                }
            }
        }
        doc.close();
        return targetFilename;
    }

}
package com.nzc.quartz.util;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 文件流回写客户端及下载
 */
@Slf4j
public class ResponseUtil {

    /**
     * 对象数据写入客户端
     * @param result
     * @param response
     */
    public static void responseWrite(Object result, HttpServletResponse response) {
        try (OutputStream out = response.getOutputStream()) {
            out.write(JSONObject.toJSONBytes(result, SerializerFeature.WriteMapNullValue,
                SerializerFeature.DisableCircularReferenceDetect));
            out.flush();
        } catch (IOException e) {
            log.error("文件流写失败", e);
        }
    }

    /**
     * byte数组写入客户端
     * @param bodyBytes
     * @param response
     */
    public static void responseWrite(byte[] bodyBytes, HttpServletResponse response) {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        try (ByteArrayInputStream in = new ByteArrayInputStream(bodyBytes); OutputStream out = response
            .getOutputStream()) {
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件流数据写入客户端
     * @param in
     * @param response
     */
    public static void responseWrite(InputStream in, HttpServletResponse response) {
        try (OutputStream out = response.getOutputStream()) {
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * httpclicent结果转byte数组
     * @param response
     * @return
     */
    private byte[] getBody(HttpResponse response) {
        try (InputStream in = response.getEntity()
                .getContent(); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            byte[] bytes = new byte[1024];
            int len;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }
            return out.toByteArray();
        } catch (IOException e) {
            log.error("外源调用异常", e);
            throw new RuntimeException("失败:"+e);
        }
    }

    /**
     * 下载resources下文档写入客户端
     */
    public static void downloadDocument(String classPath, OutputStream out) {
        ClassPathResource resource = new ClassPathResource(classPath);
        try (BufferedInputStream in = new BufferedInputStream(resource.getInputStream())) {
            byte[] bytes = new byte[1024];
            int len;
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("下载失败: {}", classPath);
        }
        log.info("下载成功: {}", classPath);
    }

    /**
     * 下载resources下文档写入客户端
     */
    public static void downloadExcel(String classPath, OutputStream out) {
        ClassPathResource resource = new ClassPathResource(classPath);
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(resource.getInputStream());
            workbook.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        FileInputStream inputStream = null;
        try {
            File file = new File("D:\\pdf\\pdfToImage\\测试合并.pdf");
            inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            inputStream.read(data);
            getFileByBytes(data,"D:\\pdf\\pdfToImage\\","tesdsss.pdf");
            byte[] bytesByFile = getBytesByFile("D:\\WORK\\picture\\codetest.png");
            getFileByBytes(bytesByFile,"D:\\WORK\\picture\\","codetests.jpg");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 文件转换成byte数组
     * @param pathStr
     * @return
     */
    public static byte[] getBytesByFile(String pathStr) {
        byte[] buffer = null;
        try {
            File file = new File(pathStr);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int numData;
            while ((numData = fis.read(bytes)) != -1) {
                bos.write(bytes, 0, numData);
            }
            fis.close();
            buffer = bos.toByteArray();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * byte数组转换成文件
     * @param bytes
     * @param filePath
     * @param fileName
     */
    public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + "\\" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 下载图片
     * @param iconPath
     * @param icon
     * @param response
     */
    public static void downloadIcon(String iconPath, String icon, HttpServletResponse response) {
        File file = new File(iconPath + File.separator + icon);
        if (!file.exists()) {
            log.error("图片logo不存在");
            return;
        }
        try{
            FileInputStream inputStream = new FileInputStream(file);
            OutputStream outputStream = response.getOutputStream();
            byte[] data = new byte[(int) file.length()];
            inputStream.read(data);
            if (icon.endsWith("svg")) {
                response.setContentType("image/svg+xml");
            } else {
                response.setContentType("image/png");
            }
            outputStream.write(data);
            outputStream.flush();
        } catch (IOException e) {
            log.error("图片logo读取失败");
            e.printStackTrace();
        }
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值