一、maven安裝
<dependency>
<groupId>org.icepdf.os</groupId>
<artifactId>icepdf-core</artifactId>
<version>6.2.2</version>
</dependency>
二、Java代碼實(shí)現(xiàn)
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
public class CapturePdfFirstPageUtil {
/**
* 生成一本書(shū)的縮略圖
*
* @param inputFile 需要生成縮略圖的書(shū)籍的完整路徑
* @param outputFile 生成縮略圖的放置路徑
*/
public static void generateBookIamge(String inputFile, String outputFile) {
Document document = null;
try {
float rotation = 0f;
// 縮略圖顯示倍數(shù)横蜒,1表示不縮放,0.5表示縮小到50%
float zoom = 0.8f;
document = new Document();
document.setFile(inputFile);
// maxPages = document.getPageTree().getNumberOfPages();
BufferedImage p_w_picpath = (BufferedImage) document.getPageImage(0, GraphicsRenderingHints.SCREEN,
Page.BOUNDARY_CROPBOX, rotation, zoom);
Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
ImageWriter writer = (ImageWriter) iter.next();
FileOutputStream out = new FileOutputStream(new File(outputFile));
ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
writer.setOutput(outImage);
writer.write(new IIOImage(p_w_picpath, null, null));
} catch (Exception e) {
System.out.println("生成書(shū)的縮略圖失敗 : " + inputFile);
System.out.println(e);
}
}
public static void main(String[] args) {
CapturePdfFirstPageUtil.generateBookIamge("C:\\Users\\Downloads\\我是帥子男一號(hào).pdf", "C:\\Users\\Desktop\\帥子男一號(hào).jpg");
}
}