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();
        }
    }
}
相关推荐
学长毕设6 小时前
基于SpringBoot的实验室资产管理系统
java·spring boot·后端
C^h6 小时前
c++ string
开发语言·c++
raindayinrain6 小时前
c++高性能--原子操作,无锁编程,操作顺序
开发语言·c++·性能优化
学逆向的6 小时前
C++ 合并命名空间
开发语言·c++·网络安全
Zhao-Jichao6 小时前
VS2026 打包 C++ 程序生成 EXE,借助 Installer Project 扩展工具
开发语言·c++
zzu123zsw7 小时前
从臃肿的模板调用到声明式契约:深入 UniHttp 动态代理与多渠道生命周期扩展
java·spring boot·microsoft·unihttp
学逆向的7 小时前
C 局部静态变量
c语言·开发语言·网络安全
大都督会赢的7 小时前
C++第一节课
开发语言·c++
“AI国潮设计-小江”7 小时前
【AIGC实战】Python+Stable Diffusion打造“英歌舞财神”IP,解锁“马到成功”等爆款情绪营销文案设计
开发语言·人工智能·python·prompt·aigc
源码集结号8 小时前
云诊所门诊系统源码,基于SpringBoot+Vue.js架构,支持多租户设计与Docker容器化部署
java·spring boot·源码·医院信息系统·门诊系统·诊所系统