| 27 | } |
| 28 | |
| 29 | public static void readPdfText(InputStream file, String textPath) throws IOException { |
| 30 | if (file == null) { |
| 31 | log.error("inputStream is null"); |
| 32 | return; |
| 33 | } |
| 34 | try (PDDocument document = PDDocument.load(file); |
| 35 | FileWriter fileWriter = new FileWriter(textPath, true) |
| 36 | ) { |
| 37 | AccessPermission ap = document.getCurrentAccessPermission(); |
| 38 | if (!ap.canExtractContent()) { |
| 39 | ap.setCanExtractContent(true); |
| 40 | } |
| 41 | |
| 42 | PDFTextStripper stripper = new PDFTextStripper(); |
| 43 | stripper.setSortByPosition(true); |
| 44 | |
| 45 | for (int p = 1; p <= document.getNumberOfPages(); ++p) { |
| 46 | stripper.setStartPage(p); |
| 47 | stripper.setEndPage(p); |
| 48 | String text = stripper.getText(document); |
| 49 | text = text.replaceAll(" ", ","); |
| 50 | text = text.replaceAll("\n", ""); |
| 51 | text = text.replaceAll(" ", ""); |
| 52 | fileWriter.write(text.trim()); |
| 53 | } |
| 54 | } catch (Exception e) { |
| 55 | log.error("解析pdf文本文件出错", e); |
| 56 | throw e; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * @Author luojiarui |