txt数据转为pdf格式并使用base64解密输出

使用该方法请注意:因为此方法使用了base64解密,需要保证txt中的数据首先用了base64加密,如果只是普通的二进制数据,该方法并不适用

第一步

XML 复制代码
 <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.24</version>
</dependency>

第二步

java 复制代码
package org.example.test.example.changefile;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ParsePDFFromString {
    public static void main(String[] args) {
        // 输入txt文件的路径
        String txtFilePath = "C:\\Users\\EDY\\Desktop\\input.txt";
        // 输出PDF文件的路径
        String outputPdfPath = "C:\\Users\\EDY\\Desktop\\output.pdf";

        try {
            // 读取txt文件内容
            String base64Data = new String(Files.readAllBytes(Paths.get(txtFilePath))).trim();

            // 检查Base64数据是否为空
            if (base64Data.isEmpty()) {
                System.out.println("Base64 data is empty.");
                return;
            }

            // Base64解码
            byte[] pdfBytes = java.util.Base64.getDecoder().decode(base64Data);

            // 检查解码后的数据是否为空
            if (pdfBytes.length == 0) {
                System.out.println("Decoded PDF data is empty.");
                return;
            }

            // 将解码后的数据转换为PDF文件
            try (PDDocument document = PDDocument.load(new ByteArrayInputStream(pdfBytes))) {
                // 创建PDFTextStripper对象
                PDFTextStripper stripper = new PDFTextStripper();

                // 从PDF文档中提取文本
                String text = stripper.getText(document);

                // 输出提取的文本
                System.out.println(text);

                // 保存PDF文档
                document.save(outputPdfPath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
相关推荐
Tony Bai5 小时前
高并发后端:坚守 Go,还是拥抱 Rust?
开发语言·后端·golang·rust
wjs20245 小时前
Swift 类型转换
开发语言
没有bug.的程序员5 小时前
服务安全:内部服务如何防止“裸奔”?
java·网络安全·云原生安全·服务安全·零信任架构·微服务安全·内部鉴权
一线大码6 小时前
SpringBoot 3 和 4 的版本新特性和升级要点
java·spring boot·后端
秃了也弱了。6 小时前
python实现定时任务:schedule库、APScheduler库
开发语言·python
weixin_440730506 小时前
java数组整理笔记
java·开发语言·笔记
weixin_425023006 小时前
Spring Boot 实用核心技巧汇总:日期格式化、线程管控、MCP服务、AOP进阶等
java·spring boot·后端
一线大码6 小时前
Java 8-25 各个版本新特性总结
java·后端
Thera7776 小时前
状态机(State Machine)详解:原理、优缺点与 C++ 实战示例
开发语言·c++
2501_906150566 小时前
私有部署问卷系统操作实战记录-DWSurvey
java·运维·服务器·spring·开源