自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Spring Boot 初學(xué)者指南:PDF 轉(zhuǎn)換為圖片或 Word 實(shí)現(xiàn)

開發(fā)
Apache PDFBox是開源 Java 工具包,解析 PDF 準(zhǔn)確,支持內(nèi)容提取、文檔創(chuàng)建等,適合初學(xué)者。

一、工具選型與準(zhǔn)備

Apache PDFBox :開源 Java 工具包,解析 PDF 準(zhǔn)確,支持內(nèi)容提取、文檔創(chuàng)建等,適合初學(xué)者。

項(xiàng)目依賴 :在 pom.xml 中添加以下關(guān)鍵依賴:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.27</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
    </dependency>
</dependencies>

二、Spring Boot 實(shí)現(xiàn) PDF 轉(zhuǎn)圖片

1. 文件上傳功能

前端表單 :用于上傳 PDF 文件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PDF 轉(zhuǎn)換為圖片</title>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" accept=".pdf"/>
        <button type="submit">上傳 PDF</button>
    </form>
</body>
</html>

后端接口 :處理文件上傳。

@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
    try {
        // 設(shè)置文件保存路徑
        Path uploadPath = Paths.get("uploads");
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        // 保存文件到本地
        Path filePath = Paths.get(uploadPath + "/" + file.getOriginalFilename());
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        return ResponseEntity.ok("文件上傳成功!");
    } catch (IOException e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上傳失敗!");
    }
}

2. PDF 轉(zhuǎn)圖片核心邏輯

@Service
public class PdfToImageService {

    public void convertPdfToImage(String pdfPath, String outputFolder) throws IOException {
        // 加載 PDF 文件
        try (PDDocument document = PDDocument.load(new File(pdfPath))) {
            PDFRenderer renderer = new PDFRenderer(document);
            // 遍歷每一頁進(jìn)行渲染
            for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) {
                BufferedImage image = renderer.renderImageWithDPI(pageIndex, 300, ImageType.RGB);
                // 保存為圖片
                String imageName = "page_" + (pageIndex + 1) + ".png";
                ImageIO.write(image, "PNG", new File(outputFolder + "/" + imageName));
            }
        }
    }
}

3. 圖片下載功能

@GetMapping("/download/image/{fileName}")
public ResponseEntity<InputStreamResource> downloadImage(@PathVariable String fileName) throws IOException {
    // 設(shè)置資源文件路徑
    String filePath = "uploads/" + fileName;
    InputStreamResource resource = new InputStreamResource(new FileInputStream(filePath));
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(new File(filePath).length())
            .contentType(MediaType.IMAGE_PNG)
            .body(resource);
}

三、Spring Boot 實(shí)現(xiàn) PDF 轉(zhuǎn) Word

(技術(shù)文章篇幅限制,此處僅展示關(guān)鍵代碼片段)

// 引入 OpenAPI 庫
// 在 porm.xml 中添加依賴
<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-core</artifactId>
    <version>1.28.3</version>
</dependency>
<dependency>
    <groupId> org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>

private void convertPdfToWord(String pdfPath, String docPath) throws Exception {
    // 解析 PDF 文本
    InputStream input = new FileInputStream(pdfPath);
    ContentHandler handler = new BodyContentHandler();
    Metadata metadata = new Metadata();
    ParseContext context = new ParseContext();
    PDFParser pdfParser = new PDFParser();
    pdfParser.parse(input, handler, metadata, context);
    String text = handler.toString();

    // 將文本寫入 Word 文檔
    XWPFDocument document = new XWPFDocument();
    XWPFParagraph paragraph = document.createParagraph();
    XWPFRun run = paragraph.createRun();
    run.setText(text);

    // 保存 Word 文檔
    FileOutputStream out = new FileOutputStream(docPath);
    document.write(out);
    out.close();
}

四、測試與運(yùn)行

  • 啟動(dòng)項(xiàng)目 :運(yùn)行 DocumentConverterApplication 類中的 main 方法。
  • 上傳測試 :訪問 /upload 接口上傳 PDF 文件。
  • 轉(zhuǎn)換測試 :調(diào)用 PDF 轉(zhuǎn)換服務(wù),將在指定輸出路徑生成圖片或 Word 文件。
  • 下載測試 :訪問 /download/image/{fileName} 接口,下載轉(zhuǎn)換后的圖片或 Word 文件。
責(zé)任編輯:趙寧寧 來源: Java技術(shù)營地
相關(guān)推薦

2022-04-24 15:21:01

MarkdownHTML

2021-05-10 08:50:32

網(wǎng)絡(luò)管理網(wǎng)絡(luò)網(wǎng)絡(luò)性能

2022-03-28 09:52:42

JavaScript語言

2023-07-28 07:31:52

JavaScriptasyncawait

2023-07-03 15:05:07

預(yù)測分析大數(shù)據(jù)

2010-06-13 11:13:38

UML初學(xué)者指南

2022-07-22 13:14:57

TypeScript指南

2012-03-14 10:56:23

web app

2022-10-10 15:28:45

負(fù)載均衡

2023-02-10 08:37:28

2022-09-05 15:36:39

Linux日志記錄syslogd

2025-02-26 13:00:00

SpringBootJava開發(fā)

2013-03-06 10:40:58

Adobe Edge HTML5

2010-08-26 15:47:09

vsftpd安裝

2013-04-08 16:35:52

Adobe Edge

2018-10-28 16:14:55

Reactreact.js前端

2011-03-02 10:57:27

vsFTPd

2023-02-19 15:31:09

架構(gòu)軟件開發(fā)代碼

2014-04-01 10:20:00

開源Rails

2020-08-16 13:10:46

TensorFlow深度學(xué)習(xí)數(shù)據(jù)集
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)