Springboot pdf转html返回url

很多业务要求pdf需要加水印

一般情况下后端对pdf加水印,存储到存储系统内

但是我们来搞点花的,将pdf转为html,前端通过html来加水印,哈哈,废话不多说,直接上代码。

首先pom.xml添加
<dependency>
    <groupId>net.sf.cssbox</groupId>
    <artifactId>pdf2dom</artifactId>
    <version>1.8</version>
</dependency>
controller层
 /**
 * 文件上传
 * @param request
 * @param file
 * @return UploadResultResponse 统一响应码,大家可以自己定义
 * @throws IOException
 */
@PostMapping("/upload")
public UploadResultResponse uploadFile(MultipartFile file) throws Exception {
    if (file == null){
        return null;
    }
    return assetPortalService.uploadFile(file);
}

Service层:
@Autowired
private SaveService saveService;

public static String pdfToHtml(InputStream is, PDFDomTreeConfig config)
        throws IOException, ParserConfigurationException {
    PDDocument pdf = PDDocument.load(is);
    PDFDomTree parser = new PDFDomTree(config);
    Writer output = new StringWriter();
    parser.writeText(pdf, output);
    pdf.close();
    String htmlOutput = output.toString();
    return htmlOutput;
}

public UploadResultResponse uploadFile(MultipartFile file) throws Exception {
    InputStream inputStream = file.getInputStream();
    String filename = file.getOriginalFilename();
    String htmlName = filename.split("\\.")[0] + ".html";
    String s = filename.split("\\.")[1];
    boolean flag = false;
    if ("pdf".equals(s)){
        PDFDomTreeConfig config = PDFDomTreeConfig.createDefaultConfig();
        String htmlOutput = pdfToHtml(inputStream, config);
        // 没有存储系统的可以用以下代码在本地测试 
        // FileUtils.write(new File("/Users/xxx/Downloads/pdf.html"), htmlOutput, "utf-8");
        // 如果没有存储系统,以上就可以测试通啦,saveService为存储API 这块只是逻辑哈,不能复用
        InputStream inputStreamHtml = IOUtils.toInputStream(htmlOutput, StandardCharsets.UTF_8);
        flag = saveService.save(inputStreamHtml, htmlName);
        filename = htmlName;
    }else {
        flag = saveService.save(inputStream, filename);
    }
    if (flag){
        String url = saveService.get(filename);
        // 前端可以根据你提供的url直接访问html
        Map<String, String> map = new HashMap<>();
        map.put("url", url);
        return UploadResultResponse.success(map);
    }
    logger.info("uploadFile fail");
    return null;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值