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 小时前
GDScript 入门笔记(十一):Lambda 与匿名函数
开发语言·笔记·游戏引擎·godot
phltxy6 小时前
C语言操作符详解
java·c语言·算法
步行cgn7 小时前
@Configuration 详解:Spring 配置类的核心注解
java·后端·spring
sunshine22 girl7 小时前
Java学习一 环境配置2 安装和基本使用Idea
java·学习·intellij-idea
事圆则缓8 小时前
Kotlin 协程完全指南
开发语言·kotlin
我爱写代码i8 小时前
BeLink - 支持生成多种URL 缩短网址PHP源码
开发语言·php·短网址php源码
Java后端的Ai之路8 小时前
20、Python - 备忘录模式
开发语言·人工智能·python·外观模式·备忘录模式
嘿嘿-669 小时前
Windows 一键使用 GPT-6 Astra:Codex CLI 配置教程
java·人工智能·windows·gpt·chatgpt·web
统计学小王子9 小时前
数学建模国赛倒计时4天——《统计模型精讲(混合效应模型R语言实现)》
开发语言·数学建模·r语言
知无不研9 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while