最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java實(shí)現(xiàn)將txt/word/pdf轉(zhuǎn)成圖片并在線預(yù)覽的功能

 更新時(shí)間:2023年05月30日 10:46:04   作者:知北游z  
本文將基于aspose-words(用于txt、word轉(zhuǎn)圖片),pdfbox(用于pdf轉(zhuǎn)圖片),封裝成一個(gè)工具類來實(shí)現(xiàn)txt、word、pdf等文件轉(zhuǎn)圖片的需求并實(shí)現(xiàn)在線預(yù)覽功能,需要的可以參考一下

如果不想網(wǎng)頁(yè)上的文章被復(fù)制(沒錯(cuò),說的就是某點(diǎn)),如果想實(shí)現(xiàn)文檔不需要下載下來就能在線預(yù)覽查看(常見于文檔付費(fèi)下載網(wǎng)站、郵箱附件預(yù)覽),該怎么做?常見的做法就是將他們轉(zhuǎn)化成圖片。以下代碼基于 aspose-words(用于txt、word轉(zhuǎn)圖片),pdfbox(用于pdf轉(zhuǎn)圖片),封裝成一個(gè)工具類來實(shí)現(xiàn)txt、word、pdf等文件轉(zhuǎn)圖片的需求。

首先在項(xiàng)目的pom文件里添加下面兩個(gè)依賴

<dependency>    
    <groupId>com.luhuiguo</groupId>    
    <artifactId>aspose-words</artifactId>    
    <version>23.1</version></dependency>
<dependency>    
    <groupId>org.apache.pdfbox</groupId>    
    <artifactId>pdfbox</artifactId>    
    <version>2.0.4</version>
</dependency>

一、將文件轉(zhuǎn)換成圖片,并生成到本地

1、將word文件轉(zhuǎn)成圖片

public static void wordToImage(String wordPath, String imagePath) throws Exception {
        Document doc = new Document(wordPath);
        File file = new File(wordPath);
        String filename = file.getName();
        String pathPre = imagePath + File.separator + filename.substring(0, filename.lastIndexOf("."));
        for (int i = 0; i < doc.getPageCount(); i++) {
            Document extractedPage = doc.extractPages(i, 1);
            String path = pathPre + (i + 1) + ".png";
            extractedPage.save(path, SaveFormat.PNG);
        }
    }

驗(yàn)證:

public static void main(String[] args) throws Exception {
        FileConvertUtil.wordToImage("D:\\書籍\\電子書\\其它\\《山海經(jīng)》異獸圖.doc", "D:\\test\\word");
    }

驗(yàn)證結(jié)果:

2、將txt文件轉(zhuǎn)成圖片(同word文件轉(zhuǎn)成圖片)

public static void txtToImage(String txtPath, String imagePath) throws Exception {
        wordToImage(txtPath, imagePath);
    }

驗(yàn)證:

public static void main(String[] args) throws Exception {
        FileConvertUtil.wordToImage("D:\\書籍\\電子書\\其它\\《山海經(jīng)》異獸圖.doc", "D:\\test\\word");
    }

驗(yàn)證結(jié)果:

3、將pdf文件轉(zhuǎn)圖片

public static void pdfToImage(String pdfPath, String imagePath) throws Exception {
        File file = new File(pdfPath);
        String filename = file.getName();
        String pathPre = imagePath + File.separator + filename.substring(0, filename.lastIndexOf("."));
        PDDocument doc = PDDocument.load(file);
        PDFRenderer renderer = new PDFRenderer(doc);
        for (int i = 0; i < doc.getNumberOfPages(); i++) {
            BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
            String pathname = pathPre + (i + 1) + ".png";
            ImageIO.write(image, "PNG", new File(pathname));
        }
        doc.close();
    }

驗(yàn)證:

public static void main(String[] args) throws Exception {
        FileConvertUtil.pdfToImage("D:\\書籍\\電子書\\其它\\自然哲學(xué)的數(shù)學(xué)原理.pdf", "D:\\test\\pdf");
    }

驗(yàn)證結(jié)果:

4、同時(shí)支持多種文件類型轉(zhuǎn)成圖片

 public static void fileToImage(String sourceFilePath, String imagePath) throws Exception {
        String ext = sourceFilePath.substring(sourceFilePath.lastIndexOf("."));
        switch (ext) {
            case ".doc":
            case ".docx":
                wordToImage(sourceFilePath, imagePath);
                break;
            case ".pdf":
                pdfToImage(sourceFilePath, imagePath);
                break;
            case ".txt":
                txtToImage(sourceFilePath, imagePath);
                break;
            default:
                System.out.println("文件格式不支持");
        }
    }

二、利用多線程提升文件寫入本地的效率

? 在將牛頓大大的長(zhǎng)達(dá)669頁(yè)的巨作《自然哲學(xué)的數(shù)學(xué)原理》時(shí)發(fā)現(xiàn)執(zhí)行時(shí)間較長(zhǎng),執(zhí)行花了140,281ms。但其實(shí)這種IO密集型的操作是通過使用多線程的方式來提升效率的,于是針對(duì)這點(diǎn),我又寫了一版多線程的版本。

同步執(zhí)行導(dǎo)出 自然哲學(xué)的數(shù)學(xué)原理.pdf 耗時(shí):

優(yōu)化后的代碼如下:

public static void pdfToImageAsync(String pdfPath, String imagePath) throws Exception {
        long old = System.currentTimeMillis();
        File file = new File(pdfPath);
        PDDocument doc = PDDocument.load(file);
        PDFRenderer renderer = new PDFRenderer(doc);
        int pageCount = doc.getNumberOfPages();
        int numCores = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(numCores);
        for (int i = 0; i < pageCount; i++) {
            int finalI = i;
            executorService.submit(() -> {
                try {
                    BufferedImage image = renderer.renderImageWithDPI(finalI, 144); // Windows native DPI
                    String filename = file.getName();
                    filename = filename.substring(0, filename.lastIndexOf("."));
                    String pathname = imagePath + File.separator + filename + (finalI + 1) + ".png";
                    ImageIO.write(image, "PNG", new File(pathname));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        doc.close();
        long now = System.currentTimeMillis();
        System.out.println("pdfToImage 多線程 轉(zhuǎn)換完成..用時(shí):" + (now - old) + "ms");
    }

多線程執(zhí)行導(dǎo)出 自然哲學(xué)的數(shù)學(xué)原理.pdf 耗時(shí)如下:

從上圖可以看到本次執(zhí)行只花了24045ms,只花了原先差不多六分之一的時(shí)間,極大地提升了執(zhí)行效率。除了pdf,word、txt轉(zhuǎn)圖片也可以做這樣的多線程改造:

//將word轉(zhuǎn)成圖片(多線程)
    public static void wordToImageAsync(String wordPath, String imagePath) throws Exception {
        Document doc = new Document(wordPath);
        File file = new File(wordPath);
        String filename = file.getName();
        String pathPre = imagePath + File.separator + filename.substring(0, filename.lastIndexOf("."));
        int numCores = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(numCores);
        for (int i = 0; i < doc.getPageCount(); i++) {
            int finalI = i;
            executorService.submit(() -> {
                try {
                    Document extractedPage = doc.extractPages(finalI, 1);
                    String path = pathPre + (finalI + 1) + ".png";
                    extractedPage.save(path, SaveFormat.PNG);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
        }
    }
    //將txt轉(zhuǎn)成圖片(多線程)
    public static void txtToImageAsync(String txtPath, String imagePath) throws Exception {
        wordToImageAsync(txtPath, imagePath);
    }

三、將文件轉(zhuǎn)換成圖片流

? 有的時(shí)候我們轉(zhuǎn)成圖片后并不需要在本地生成圖片,而是需要將圖片返回或者上傳到圖片服務(wù)器,這時(shí)候就需要將轉(zhuǎn)換后的圖片轉(zhuǎn)成流返回以方便進(jìn)行傳輸,代碼示例如下:

1、將word文件轉(zhuǎn)成圖片流

public static List<byte[]> wordToImageStream(String wordPath) throws Exception {
    Document doc = new Document(wordPath);
    List<byte[]> list = new ArrayList<>();
    for (int i = 0; i < doc.getPageCount(); i++) {
        try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()){
            Document extractedPage = doc.extractPages(i, 1);
            extractedPage.save(outputStream, SaveFormat.*PNG*);
            list.add(outputStream.toByteArray());
        }
    }
    return list;
}

2、將txt文件轉(zhuǎn)成圖片流

public static List<byte[]> txtToImageStream(String txtPath) throws Exception {
    return *wordToImagetream*(txtPath);
}

3、將pdf轉(zhuǎn)成圖片流

public static List<byte[]> pdfToImageStream(String pdfPath) throws Exception {
    File file = new File(pdfPath);
    PDDocument doc = PDDocument.*load*(file);
    PDFRenderer renderer = new PDFRenderer(doc);
    List<byte[]> list = new ArrayList<>();
    for (int i = 0; i < doc.getNumberOfPages(); i++) {
        try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
            ImageIO.*write*(image, "PNG", outputStream);
            list.add(outputStream.toByteArray());
        }
    }
    doc.close();
    return list;
}

4、支持多種類型文件轉(zhuǎn)成圖片流

public static List<byte[]> fileToImageStream(String pdfPath) throws Exception {
    String ext = pdfPath.substring(pdfPath.lastIndexOf("."));
    switch (ext) {
        case ".doc":
        case ".docx":
            return *wordToImageStream*(pdfPath);
        case ".pdf":
            return *pdfToImageStream*(pdfPath);
        case ".txt":
            return *txtToImageStream*(pdfPath);
        default:
            System.*out*.println("文件格式不支持");
    }
    return null;
}

最后附上完整的工具類代碼:

package com.fhey.service.common.utils.file;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.aspose.words.SaveOptions;
import javassist.bytecode.ByteArray;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class FileConvertUtil {
    //文件轉(zhuǎn)成圖片
    public static void fileToImage(String sourceFilePath, String imagePath) throws Exception {
        String ext = sourceFilePath.substring(sourceFilePath.lastIndexOf("."));
        switch (ext) {
            case ".doc":
            case ".docx":
                wordToImage(sourceFilePath, imagePath);
                break;
            case ".pdf":
                pdfToImage(sourceFilePath, imagePath);
                break;
            case ".txt":
                txtToImage(sourceFilePath, imagePath);
                break;
            default:
                System.out.println("文件格式不支持");
        }
    }
    //將pdf轉(zhuǎn)成圖片
    public static void pdfToImage(String pdfPath, String imagePath) throws Exception {
        File file = new File(pdfPath);
        String filename = file.getName();
        String pathPre = imagePath + File.separator + filename.substring(0, filename.lastIndexOf("."));
        PDDocument doc = PDDocument.load(file);
        PDFRenderer renderer = new PDFRenderer(doc);
        for (int i = 0; i < doc.getNumberOfPages(); i++) {
            BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
            String pathname = pathPre + (i + 1) + ".png";
            ImageIO.write(image, "PNG", new File(pathname));
        }
        doc.close();
    }
    //txt轉(zhuǎn)成轉(zhuǎn)成圖片
    public static void txtToImage(String txtPath, String imagePath) throws Exception {
        wordToImage(txtPath, imagePath);
    }
    //將word轉(zhuǎn)成圖片
    public static void wordToImage(String wordPath, String imagePath) throws Exception {
        Document doc = new Document(wordPath);
        File file = new File(wordPath);
        String filename = file.getName();
        String pathPre = imagePath + File.separator + filename.substring(0, filename.lastIndexOf("."));
        for (int i = 0; i < doc.getPageCount(); i++) {
            Document extractedPage = doc.extractPages(i, 1);
            String path = pathPre + (i + 1) + ".png";
            extractedPage.save(path, SaveFormat.PNG);
        }
    }
    //pdf轉(zhuǎn)成圖片(多線程)
    public static void pdfToImageAsync(String pdfPath, String imagePath) throws Exception {
        long old = System.currentTimeMillis();
        File file = new File(pdfPath);
        PDDocument doc = PDDocument.load(file);
        PDFRenderer renderer = new PDFRenderer(doc);
        int pageCount = doc.getNumberOfPages();
        int numCores = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(numCores);
        for (int i = 0; i < pageCount; i++) {
            int finalI = i;
            executorService.submit(() -> {
                try {
                    BufferedImage image = renderer.renderImageWithDPI(finalI, 144); // Windows native DPI
                    String filename = file.getName();
                    filename = filename.substring(0, filename.lastIndexOf("."));
                    String pathname = imagePath + File.separator + filename + (finalI + 1) + ".png";
                    ImageIO.write(image, "PNG", new File(pathname));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        doc.close();
        long now = System.currentTimeMillis();
        System.out.println("pdfToImage 多線程 轉(zhuǎn)換完成..用時(shí):" + (now - old) + "ms");
    }
    //將word轉(zhuǎn)成圖片(多線程)
    public static void wordToImageAsync(String wordPath, String imagePath) throws Exception {
        Document doc = new Document(wordPath);
        File file = new File(wordPath);
        String filename = file.getName();
        String pathPre = imagePath + File.separator + filename.substring(0, filename.lastIndexOf("."));
        int numCores = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(numCores);
        for (int i = 0; i < doc.getPageCount(); i++) {
            int finalI = i;
            executorService.submit(() -> {
                try {
                    Document extractedPage = doc.extractPages(finalI, 1);
                    String path = pathPre + (finalI + 1) + ".png";
                    extractedPage.save(path, SaveFormat.PNG);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
        }
    }
    //將txt轉(zhuǎn)成圖片(多線程)
    public static void txtToImageAsync(String txtPath, String imagePath) throws Exception {
        wordToImageAsync(txtPath, imagePath);
    }
    //將文件轉(zhuǎn)成圖片流
    public static List<byte[]> fileToImageStream(String pdfPath) throws Exception {
        String ext = pdfPath.substring(pdfPath.lastIndexOf("."));
        switch (ext) {
            case ".doc":
            case ".docx":
                return wordToImageStream(pdfPath);
            case ".pdf":
                return pdfToImageStream(pdfPath);
            case ".txt":
                return txtToImageStream(pdfPath);
            default:
                System.out.println("文件格式不支持");
        }
        return null;
    }
    //將pdf轉(zhuǎn)成圖片流
    public static List<byte[]> pdfToImageStream(String pdfPath) throws Exception {
        File file = new File(pdfPath);
        PDDocument doc = PDDocument.load(file);
        PDFRenderer renderer = new PDFRenderer(doc);
        List<byte[]> list = new ArrayList<>();
        for (int i = 0; i < doc.getNumberOfPages(); i++) {
            try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                ImageIO.write(image, "PNG", outputStream);
                list.add(outputStream.toByteArray());
            }
        }
        doc.close();
        return list;
    }
    //將word轉(zhuǎn)成圖片流
    public static List<byte[]> wordToImageStream(String wordPath) throws Exception {
        Document doc = new Document(wordPath);
        List<byte[]> list = new ArrayList<>();
        for (int i = 0; i < doc.getPageCount(); i++) {
            try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()){
                Document extractedPage = doc.extractPages(i, 1);
                extractedPage.save(outputStream, SaveFormat.PNG);
                list.add(outputStream.toByteArray());
            }
        }
        return list;
    }
    //將txt轉(zhuǎn)成圖片流
    public static List<byte[]> txtToImageStream(String txtPath) throws Exception {
        return wordToImageStream(txtPath);
    }
}

到此這篇關(guān)于Java實(shí)現(xiàn)將txt/word/pdf轉(zhuǎn)成圖片并在線預(yù)覽的功能的文章就介紹到這了,更多相關(guān)Java圖片在線預(yù)覽內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 手把手教你如何在idea中搭建SpringBoot項(xiàng)目

    手把手教你如何在idea中搭建SpringBoot項(xiàng)目

    這篇文章主要介紹了如何搭建一個(gè)SpringBoot項(xiàng)目,包括環(huán)境準(zhǔn)備、創(chuàng)建新項(xiàng)目、探索項(xiàng)目結(jié)構(gòu)以及展望未來,通過詳細(xì)的步驟和實(shí)用的技巧,幫助開發(fā)者快速上手SpringBoot開發(fā),文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2025-02-02
  • 詳解如何用spring Restdocs創(chuàng)建API文檔

    詳解如何用spring Restdocs創(chuàng)建API文檔

    這篇文章將帶你了解如何用spring官方推薦的restdoc去生成api文檔。具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • java開發(fā)主流定時(shí)任務(wù)解決方案全橫評(píng)詳解

    java開發(fā)主流定時(shí)任務(wù)解決方案全橫評(píng)詳解

    這篇文章主要為大家介紹了java開發(fā)主流定時(shí)任務(wù)解決方案全橫評(píng)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-09-09
  • springboot使用kafka的過程

    springboot使用kafka的過程

    本文介紹了Spring Boot集成Kafka的步驟,包括啟動(dòng)服務(wù)、配置生產(chǎn)者與消費(fèi)者,以及Kafka從依賴Zookeeper到Kraft模式的版本演進(jìn),本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧
    2025-06-06
  • Java并發(fā)編程ReentrantReadWriteLock加讀鎖流程

    Java并發(fā)編程ReentrantReadWriteLock加讀鎖流程

    這篇文章主要介紹了Java并發(fā)編程ReentrantReadWriteLock加讀鎖流程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-05-05
  • Intellij IDEA 旗艦版創(chuàng)建 Spring MVC 項(xiàng)目踩過的坑

    Intellij IDEA 旗艦版創(chuàng)建 Spring MVC 項(xiàng)目踩過的坑

    IDEA旗艦版可以直接創(chuàng)建Spring MVC項(xiàng)目,但創(chuàng)建后的項(xiàng)目并不是直接就可以運(yùn)行,還需要進(jìn)行一些配置。這篇文章主要介紹了Intellij IDEA 旗艦版創(chuàng)建 Spring MVC 項(xiàng)目踩坑記 ,需要的朋友可以參考下
    2020-03-03
  • Java對(duì)象和JSON字符串之間的轉(zhuǎn)換方法(全網(wǎng)最清晰)

    Java對(duì)象和JSON字符串之間的轉(zhuǎn)換方法(全網(wǎng)最清晰)

    這篇文章主要介紹了如何在Java中使用Jackson庫(kù)將對(duì)象轉(zhuǎn)換為JSON字符串,并提供了一個(gè)簡(jiǎn)單的工具類示例,該工具類支持基本的轉(zhuǎn)換功能,文中給出了詳細(xì)的代碼示例,需要的朋友可以參考下
    2025-02-02
  • Java JNA庫(kù)詳解與本地系統(tǒng)交互實(shí)戰(zhàn)記錄(推薦)

    Java JNA庫(kù)詳解與本地系統(tǒng)交互實(shí)戰(zhàn)記錄(推薦)

    JNA 是一個(gè)開源庫(kù),它提供了 Java 程序調(diào)用本地共享庫(kù)(如 DLLs 在 Windows 或 .so 文件在 Linux/Unix)的功能,本文給大家介紹Java JNA庫(kù)詳解與本地系統(tǒng)交互實(shí)戰(zhàn),感興趣的朋友一起看看吧
    2025-11-11
  • Spring @Value注解失效問題解決方案

    Spring @Value注解失效問題解決方案

    這篇文章主要介紹了Spring @Value注解失效問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • Spring?Boot中的JdbcClient與JdbcTemplate使用對(duì)比分析

    Spring?Boot中的JdbcClient與JdbcTemplate使用對(duì)比分析

    這篇文章主要介紹了Spring Boot中的JdbcClient與JdbcTemplate使用對(duì)比分析,一起看看Spring Boot 中 JdbcClient 和 JdbcTemplate 之間的差異
    2024-01-01

最新評(píng)論

奉化市| 项城市| 太仆寺旗| 溧水县| 阳江市| 丰台区| 景泰县| 乌审旗| 乌审旗| 灌阳县| 浪卡子县| 高清| 临邑县| 曲靖市| 黔东| 会东县| 彩票| 阿勒泰市| 拉萨市| 安吉县| 申扎县| 介休市| 大余县| 祁门县| 正阳县| 海兴县| 富锦市| 边坝县| 乌拉特前旗| 独山县| 肇源县| 长治县| 佳木斯市| 福建省| 宁波市| 邻水| 米泉市| 康马县| 灵璧县| 伊金霍洛旗| 宁乡县|