簡體   English   中英

使用maven-shade-plugin構建的pdfbox的程序結果與普通的NetBeans Run不同

[英]Result of program using pdfbox built with maven-shade-plugin is different than normal NetBeans Run

我有使用PDFBox 1.7.1的java程序,它是用maven-shade-plugin 2.0構建的。

這是使用PDFBox api的代碼:

public class PdfFile {

    protected PDDocument document = null;

    public boolean load(byte[] bytes) throws IOException {
        InputStream is = new ByteArrayInputStream(bytes);
        PDFParser parser = new PDFParser(is);
        parser.parse();
        COSDocument cosDoc = parser.getDocument();
        this.document = new PDDocument(cosDoc);
        return true;
    }

    public byte[] extractText() throws IOException {
        PDFTextStripper pdfStripper = new PDFTextStripper();
        byte[] text = pdfStripper.getText(this.document).getBytes();

        return text;
    }

    public void close() throws IOException {
        if(this.document != null) {
            this.document.close();
        }
    }
}

所以基本上方法load()從字節數組加載pdf文檔,方法extractText()將從PDF中提取的文本作為字節數組返回。 當我從NetBeans Run按鈕運行程序時它可以工作,但是當我從使用maven-shade-plugin構建的單個jar運行它時,返回的文本是錯誤的字符編碼。 例如單詞:

odpowiadająca (normal polish characters)
odpowiadajšca (netbeans run)
odpowiadajÄca (single shade jar)

我知道它與兩個運行中作為to PdfFile.load()參數完全相同的文件(字節數組)。 所以問題是PDF框以兩種不同的格式返回文本...

我有3個問題:

  1. 為什么在使用shade插件編碼的jar中有所不同?
  2. 我如何控制/設置使用shade插件構建的jar使用的編碼?
  3. 我如何強制PDF框以正確的格式返回文本?

我知道在命令行PDFBox中有設置編碼的選項:

java -jar {$jar_path} ExtractText -encoding UTF-8

但我在PdfBox api中找不到它...


解決了:我不得不改變

pdfStripper.getText(this.document).getBytes();

pdfStripper.getText(this.document).getBytes("UTF8");

首先,這是2個事實(關於你的問題2):

對於問題1和3:

我認為你的問題與將extractText()返回的byte[]轉換為String的方式更相關。

new String(byte[])使用平台編碼。 因此,在netbeans或shell中執行此操作可能會產生不同的結果,因為我預計在Netbeans中運行時平台編碼可能會有所不同。

發布處理extractText()結果的代碼會很有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM