java在线预览doc

今天遇到了一个很坑的问题,MinIo下载下来的doc文档使用java无法打开,尝试了Apache POI,Aspose.Words等工具,转换html或者转换pdf文件,一直报错文档已损坏,但是office打开之后随便修改一点再保存就没有问题。

最后实在没有办法,取了个巧,把下载下来的文档存到一个临时txt文档中,然后读取文档内容,去除多余字符,再进行截取,保留一段HTML代码传到页面显示。

try {
    // 创建一个HTTP客户端
    HttpClient client = HttpClientBuilder.create().build();
    // 发送GET请求
    HttpGet request = new HttpGet(downloadUrl);
    HttpResponse response = client.execute(request);
    // 从响应中获取实体内容
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        // 将实体内容转换为字节数组
        byte[] fileData = EntityUtils.toByteArray(entity);
        // 创建临时文件
        File tempFile = File.createTempFile("temp-", ".txt");
        // 将字节数组写入临时文件
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            fos.write(fileData);
        }

        // 加载TXT文本内容
        String txtContent = loadTextFromFile(tempFile.getAbsolutePath());
        // 删除不符合DOC内容规范的部分
        String cleanedContent = removeInvalidContent(txtContent);
        // 删除临时文件
        tempFile.delete();
        model.addAttribute("content", cleanedContent);
    }
} catch (IOException e) {
    e.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
}
private static String loadTextFromFile(String filePath) throws IOException {
    FileInputStream fis = new FileInputStream(filePath);
    //这里的编码看情况
    InputStreamReader isr = new InputStreamReader(fis, "GBK");
    BufferedReader reader = new BufferedReader(isr);
    StringBuilder content = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        // 处理每一行的文本内容
        content.append(line);
    }
    reader.close();
    isr.close();
    fis.close();
    return content.toString();
}
private static String removeInvalidContent(String text) {
    // 去除特殊字符
    text = text.replaceAll("^[^\\w\\s.,!?【】“”‘’'\"\\-*/+\\\\^()\\[\\]{}|$%<>@#&=:;~`\\u4e00-\\u9fa5]+$", "");

    int startIndex = text.indexOf("<BODY>") + "<BODY>".length();
    int endIndex = text.indexOf("</BODY>");
    if (startIndex != -1 && endIndex != -1) {
        return text.substring(startIndex, endIndex);
    }

    return text;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值