gpt4 book ai didi

java - 无法使用 PDFBox 在 Java 中正确打印 pdf 文件中的非英语(拉脱维亚语)字符?

转载 作者:行者123 更新时间:2023-11-30 06:08:56 26 4
gpt4 key购买 nike

import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.text.PDFTextStripper;
public class sample {
public static void main(String[] args) throws InvalidPasswordException, IOException {
File file = new File("C:\\sample.pdf");
PDDocument document = PDDocument.load(file);
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
//java.io.PrintStream p = new java.io.PrintStream(System.out,false,"Cp921");
//p.println(text.toString());
System.out.println(text);
}
}

文本是从 pdf 中读取的,但在使用 System.out.println 显示时显示不同的输出。然后我在网上阅读了不同的帖子,发现它与编码有关,我在这个问题上找到了解决方案:Text extracted by PDFBox does not contain international (non-English) characters但我必须对拉脱维亚字符使用 Cp921 编码,但问题仍然没有解决,输出在此图像中给出

然后我经历了调试过程,发现从PDF读取的文本以精确的编码存储,没有任何更改,所以我不知道如何以正确的编码显示文本。任何帮助将非常感谢。

PDF 内容示例:[Maksātājs、Informācija、Vārdu krājums、Ēģipte、Plašs、Vājš、Brieži、Pērtiķi、Grāmatiņa、šķīvis]

使用 System.out.println 在 Eclipse 中输出控制台:

Console output in Eclipse using System.out.println

使用 PrintStream 在 Eclipse 中进行控制台输出:

Console output in eclipse using PrintStream

附注我是初学者程序员,没有太多编码经验

最佳答案

您可以通过修改系统属性file.encoding或设置out来更改系统。以下任何一项都应该有效:

  1. -Dfile.encoding=utf-8 (或任何你需要的)作为 jvm 参数
  2. System.setProperty("file.encoding", "utf-8") -- 与 (1) 相同,但在运行时
  3. System.setOut(new PrintStream(System.out, true, "utf-8")) -- 将 System.out 设置为您需要的任何打印流。

编辑

您的评论提到您正在写入文件。要写入文件并指定编码,请考虑类似

try (OutputStreamWriter writer =
new OutputStreamWriter(new FileOutputStream(new File("path/to/file")), StandardCharsets.UTF_8))
writer.write(text, 0, text.length());
}

请参阅文档 here .

关于java - 无法使用 PDFBox 在 Java 中正确打印 pdf 文件中的非英语(拉脱维亚语)字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50657884/

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