gpt4 book ai didi

java - 如何设置PDFBox的字符编码

转载 作者:行者123 更新时间:2023-12-02 10:19:29 31 4
gpt4 key购买 nike

我正在使用 Apache PDFBox 构建一个 pdf 解析器,解析纯文本后,我运行一些算法,最后输出一个 json 文件。对于某些 pdf 文件,输出文件包含 utf-8 编码,对于其他 pdf 文件,它包含某种形式的似乎是 latin-1 编码(当在 python 中打开 json 文件时,空格显示为“\xa0”)。我认为这一定是 pdf 的字体或其他一些特征的结果?

我读取纯文本的代码如下

PDDocument document = PDDocument.load(file);

//Instantiate PDFTextStripper class
PDFTextStripper pdfStripper = new PDFTextStripper();

//Retrieving text from PDF document
String text = pdfStripper.getText(document);

//Closing the document
document.close();

我尝试只保存纯文本:

PrintWriter out = new PrintWriter(outPath + ".txt");
out.print(text);

如果文件被读入dictionary,即使在python中打开这个纯文本文件也会产生“\xa0”字符而不是空格。 ,产生以下结果:

dict_keys(['1.\xa0\lorem\xa0ipsum', '2.\xa0\lorem\xa0ipsum\xa0\lorem\xa0ipsum', '3.\xa0\lorem', '4.\xa0\lorem\xa0ipsum', '5.\xa0\lorem\xa0ipsum'])

我想确保文本始终编码为 utf-8。我该怎么做呢?

最佳答案

I'd like to make sure the text always gets encoded as utf-8. How do I go about doing this?

如果您想确保您的 PrintWriter 使用 UTF-8 编码,请在构造函数中这样说:

PrintWriter out = new PrintWriter(outPath + ".txt", "UTF-8");

关于java - 如何设置PDFBox的字符编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54447903/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com