SpringBoot+OCR實現(xiàn)PDF內(nèi)容識別的示例代碼
一、SpringBoot+OCR對pdf文件內(nèi)容識別提取
1、在 Spring Boot 中,您可以結(jié)合 OCR(Optical Character Recognition)庫來實現(xiàn)對 PDF 文件內(nèi)容的識別和提取。
一種常用的 OCR 庫是 Tesseract,而 pdf2image 是一個用于將 PDF 轉(zhuǎn)換為圖像的工具,可以與 Tesseract 配合使用。
以下是一個簡單的 Spring Boot 示例,演示如何使用 Tesseract 和 pdf2image 對 PDF 文件進(jìn)行 OCR 識別和提?。?/p>
- 添加 Maven 依賴:
在您的 Spring Boot 項目中,添加以下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.30</version> <!-- 使用最新版本 -->
</dependency>
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.5.5</version> <!-- 使用最新版本 -->
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.30</version> <!-- 使用最新版本 -->
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-debugger</artifactId>
<version>2.0.30</version> <!-- 使用最新版本 -->
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-app2</artifactId>
<version>2.0.30</version> <!-- 使用最新版本 -->
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.68</version> <!-- 使用最新版本 -->
</dependency>
- 編寫代碼:
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.tools.PDFToImage;
import org.springframework.stereotype.Service;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
@Service
public class OCRService {
public String extractTextFromPDF(String pdfFilePath) {
try {
// Convert PDF to images
List<BufferedImage> images = convertPDFToImages(pdfFilePath);
// Use OCR to extract text from images
StringBuilder extractedText = new StringBuilder();
for (BufferedImage image : images) {
extractedText.append(performOCR(image)).append("\n");
}
return extractedText.toString();
} catch (Exception e) {
e.printStackTrace();
return "Error extracting text from PDF.";
}
}
private List<BufferedImage> convertPDFToImages(String pdfFilePath) throws Exception {
List<BufferedImage> images = new ArrayList<>();
try (PDDocument document = PDDocument.load(new File(pdfFilePath))) {
PDFToImage pdfToImage = new PDFToImage();
pdfToImage.setStartPage(1);
pdfToImage.setEndPage(document.getNumberOfPages());
pdfToImage.setOutputPrefix("outputImage");
pdfToImage.processPages(document);
for (int i = 1; i <= document.getNumberOfPages(); i++) {
BufferedImage image = pdfToImage.getImage(i - 1);
images.add(image);
}
}
return images;
}
private String performOCR(BufferedImage image) throws Exception {
ITesseract tesseract = new Tesseract();
return tesseract.doOCR(image);
}
}
在這個例子中,OCRService 類包含了兩個方法。convertPDFToImages 方法將 PDF 文件轉(zhuǎn)換為圖像,而 performOCR 方法使用 Tesseract 對圖像執(zhí)行 OCR。最后,extractTextFromPDF 方法將這兩個步驟結(jié)合在一起,對 PDF 中的每個頁面執(zhí)行 OCR,并返回提取的文本。
請注意,為了使這個示例運(yùn)行,您需要在系統(tǒng)上安裝 Tesseract OCR,并配置其環(huán)境變量,以便 Java 可以找到 Tesseract 的執(zhí)行文件。此外,也需要配置 pdf2image 的相關(guān)依賴。
以上代碼示例僅供參考,實際項目中可能需要根據(jù)具體情況進(jìn)行適當(dāng)?shù)恼{(diào)整和優(yōu)化。
2、Tesseract OCR
Tesseract OCR 是一個開源的光學(xué)字符識別引擎,由 Google 開發(fā)和維護(hù)。它能夠識別圖像中的文本并將其轉(zhuǎn)換為可編輯的文本格式。以下是一些關(guān)于 Tesseract OCR 的關(guān)鍵信息:
主要特點(diǎn):
- 多語言支持: Tesseract 支持多種語言的文本識別,包括但不限于英語、中文、西班牙語、法語等。
- 開源: Tesseract 是開源的,可以在 GitHub 上找到其源代碼。這使得開發(fā)人員可以自由使用、修改和分發(fā)它。
- 靈活性: Tesseract 可以處理不同字體和樣式的文本,并在一定程度上適應(yīng)圖像質(zhì)量的變化。
- 訓(xùn)練自定義字體: 如果您有特定的字體需要識別,Tesseract 允許您使用訓(xùn)練數(shù)據(jù)來訓(xùn)練模型,以提高對這些字體的識別能力。
如何使用 Tesseract OCR:
- 安裝 Tesseract OCR: 在您的系統(tǒng)上安裝 Tesseract。它支持多個操作系統(tǒng),包括 Windows、Linux 和 macOS。您可以從 Tesseract GitHub Releases 頁面下載預(yù)編譯的二進(jìn)制文件。
- 配置環(huán)境變量: 將 Tesseract 可執(zhí)行文件所在的目錄添加到系統(tǒng)的 PATH 環(huán)境變量中,以便在命令行中直接調(diào)用 Tesseract。
- 使用 Tesseract: 您可以通過命令行或通過編程語言的接口使用 Tesseract。對于 Java,您可以使用 Tesseract 的 Java API(Tess4J)。
Tess4J(Java API for Tesseract):
Tess4J 是 Tesseract 的 Java 封裝庫,它允許您在 Java 應(yīng)用程序中使用 Tesseract OCR。以下是一個簡單的 Java 示例:
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import java.io.File;
public class TesseractExample {
public static void main(String[] args) {
ITesseract tesseract = new Tesseract();
try {
File imageFile = new File("path/to/your/image.png");
String result = tesseract.doOCR(imageFile);
System.out.println("OCR Result:\n" + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
確保您在項目中添加了 Tess4J 的依賴:
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.5.5</version> <!-- 使用最新版本 -->
</dependency>
此示例演示了如何使用 Tess4J 從圖像文件中提取文本。請根據(jù)您的實際需求進(jìn)行適當(dāng)?shù)呐渲煤蛿U(kuò)展。
3、SpringBoot+pdf2image
在Spring Boot中使用pdf2image庫進(jìn)行PDF到圖像的轉(zhuǎn)換通常涉及以下幾個步驟:
添加 Maven 依賴:
在您的 Spring Boot 項目的
pom.xml文件中添加以下依賴:<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.30</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox-tools</artifactId> <version>2.0.30</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox-debugger</artifactId> <version>2.0.30</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox-app2</artifactId> <version>2.0.30</version> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.68</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox-graphics2d</artifactId> <version>2.0.30</version> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox-font2d</artifactId> <version>2.0.30</version> </dependency> <dependency> <groupId>com.github.jai-imageio</groupId> <artifactId>jai-imageio-core</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>com.github.jai-imageio</groupId> <artifactId>jai-imageio-jpeg2000</artifactId> <version>1.3.0</version> </dependency> </dependencies>編寫代碼:
創(chuàng)建一個服務(wù)類或控制器類,用于處理 PDF 到圖像的轉(zhuǎn)換。以下是一個簡單的示例:
import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.pdfbox.tools.imageio.ImageIOUtil; import org.springframework.stereotype.Service; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; @Service public class PdfToImageService { public void convertPdfToImages(String pdfFilePath, String outputFolderPath) { try { PDDocument document = PDDocument.load(new File(pdfFilePath)); PDFRenderer pdfRenderer = new PDFRenderer(document); for (int page = 0; page < document.getNumberOfPages(); ++page) { BufferedImage image = pdfRenderer.renderImageWithDPI(page, 300); // 300 DPI ImageIOUtil.writeImage(image, outputFolderPath + "page_" + (page + 1) + ".png", 300); } document.close(); } catch (IOException e) { e.printStackTrace(); } } }使用服務(wù)類:
在您的控制器類或其他需要的地方使用
PdfToImageService:import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class PdfToImageController { @Autowired private PdfToImageService pdfToImageService; @GetMapping("/convertPdfToImages/{pdfFileName}") public String convertPdfToImages(@PathVariable String pdfFileName) { String pdfFilePath = "path/to/pdf/files/" + pdfFileName + ".pdf"; String outputFolderPath = "path/to/output/folder/"; pdfToImageService.convertPdfToImages(pdfFilePath, outputFolderPath); return "PDF to images conversion complete."; } }這是一個簡單的示例,您可以根據(jù)實際需求進(jìn)行擴(kuò)展和修改。確保您的項目中有適當(dāng)?shù)奈募x取和寫入權(quán)限,并根據(jù)需要添加錯誤處理。
二、SpringBoot+OCR對pdf文件內(nèi)指定區(qū)域的內(nèi)容識別提取
在Spring Boot中使用OCR對PDF文件的指定區(qū)域進(jìn)行內(nèi)容識別和提取,您需要結(jié)合PDF處理庫和OCR庫。以下是一個基本的步驟,其中使用了Apache PDFBox作為PDF處理庫,Tesseract作為OCR庫。
1. 添加 Maven 依賴:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.30</version>
</dependency>
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.5.5</version>
</dependency>
<!-- 其他可能需要的依賴 -->
</dependencies>
2. 編寫服務(wù)類:
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import org.springframework.stereotype.Service;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
@Service
public class PdfOcrService {
public String extractTextFromPdfRegion(String pdfFilePath, Rectangle region) {
try {
PDDocument document = PDDocument.load(new File(pdfFilePath));
PDFTextStripper pdfStripper = new PDFTextStripper();
pdfStripper.setSortByPosition(true);
String pdfText = pdfStripper.getText(document);
String extractedText = performOCR(pdfText, region);
document.close();
return extractedText;
} catch (IOException e) {
e.printStackTrace();
return "Error extracting text from PDF.";
}
}
private String performOCR(String pdfText, Rectangle region) {
ITesseract tesseract = new Tesseract();
String extractedText = "";
try {
extractedText = tesseract.doOCR(pdfText, region);
} catch (Exception e) {
e.printStackTrace();
}
return extractedText;
}
}
3. 使用服務(wù)類:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.awt.Rectangle;
@RestController
public class PdfOcrController {
@Autowired
private PdfOcrService pdfOcrService;
@GetMapping("/extractText/{pdfFileName}")
public String extractTextFromPdfRegion(@PathVariable String pdfFileName) {
String pdfFilePath = "path/to/pdf/files/" + pdfFileName + ".pdf";
// Define the region you want to extract (x, y, width, height)
Rectangle region = new Rectangle(100, 100, 300, 200);
return pdfOcrService.extractTextFromPdfRegion(pdfFilePath, region);
}
}
在上述代碼中,PdfOcrService 類加載PDF文檔并使用PDFBox提取文本。然后,它調(diào)用performOCR 方法,該方法使用Tesseract OCR庫對指定區(qū)域的文本進(jìn)行識別。
請注意,這只是一個基本示例,您可能需要根據(jù)實際需求進(jìn)行調(diào)整。確保在生產(chǎn)環(huán)境中處理異常和錯誤,以確保應(yīng)用程序的穩(wěn)定性。
到此這篇關(guān)于SpringBoot+OCR實現(xiàn)PDF內(nèi)容識別的示例代碼的文章就介紹到這了,更多相關(guān)SpringBoot實現(xiàn)PDF內(nèi)容識別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解析SpringBoot中@Autowire注解的實現(xiàn)原理
在開發(fā)Java項目時,依賴注入是一種常見的實現(xiàn)方式,SpringBoot框架通過@Autowired注解來實現(xiàn)依賴注入的功能,本文將介紹SpringBoot中 Autowired注解實現(xiàn)的原理2023-06-06
SpringBoot?中使用?Validation?校驗參數(shù)的方法詳解
Validation?是用于檢查程序代碼中參數(shù)的有效性的框架,作為?Spring?框架中的一個參數(shù)校驗工具,集成在?spring-context?包中,這篇文章主要介紹了SpringBoot?中使用?Validation?校驗參數(shù),需要的朋友可以參考下2022-05-05
Java concurrency集合之 CopyOnWriteArrayList_動力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了Java concurrency集合之 CopyOnWriteArrayList的相關(guān)資料,需要的朋友可以參考下2017-06-06
詳解lombok @Getter @Setter 使用注意事項
這篇文章主要介紹了詳解lombok @Getter @Setter 使用注意事項,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11

