文章目录
- 一、环境准备
- 二、pdfbox、icepdf工具实现pdf转图片
- 结尾
一、环境准备
- icepdf-core-6.1.2.jar
- pdfbox-2.0.20.jar
二、pdfbox、icepdf工具实现pdf转图片
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
public class PdfToImgUtils {public static List<String> convertToImgByPdfbox(String filePath){
List<String> result = new ArrayList<String>();String targetFormat = "jpg";String targetPath;int resolution = 300;File file = new File(filePath);PDDocument doc = null;try {doc = PDDocument.load(file);if (doc.isEncrypted()) {return result;}List<PDPage> pages = doc.getDocumentCatalog().getAllPages();String format = "_%0" + String.valueOf(pages.size()).length() + "d";for (int i = 0; i < pages.size(); i++) {PDPage page = pages.get(i);BufferedImage image = page.convertToImage(BufferedImage.TYPE_BYTE_GRAY, resolution);targetPath = filePath.substring(0, filePath.lastIndexOf(".")) + String.format(format, i + 1) + "." + targetFormat;File destFile = new File(targetPath);ImageIO.write(image, targetFormat, destFile);result.add(targetPath);}} catch (Exception e) {e.printStackTrace();} finally {if (doc != null) {try {doc.close();} catch (IOException e) {e.printStackTrace();}}}return result;}public static List<String> convertToImgByIcepdf(String filePath) {List<String> result = new ArrayList<String>();Document document = null;float scale = 2f;float rotation = 0f;String targetFormat = "png";String targetPath;try {document = new Document();document.setFile(filePath);String format = "_%0" + String.valueOf(document.getNumberOfPages()).length() + "d";for (int i = 0; i < document.getNumberOfPages(); i++) {BufferedImage image = (BufferedImage)document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);RenderedImage rendImage = image;targetPath = filePath.substring(0, filePath.lastIndexOf(".")) + String.format(format, i + 1) + "." + targetFormat;File file = new File(targetPath);ImageIO.write(rendImage, targetFormat, file);result.add(targetPath);image.flush();}} catch (Exception e) {e.printStackTrace();} finally {document.dispose();}return result;}public static void main(String args[]) throws Exception {Long start = System.currentTimeMillis();PdfToImgUtils.convertToImgByIcepdf("C:\\Users\\Administrator\\Desktop\\ocr\\111.pdf");System.out.println((System.currentTimeMillis() - start) / 1000);}
}
结尾
- 感谢大家的耐心阅读,如有建议请私信或评论留言。
- 如有收获,劳烦支持,关注、点赞、评论、收藏均可,博主会经常更新博客,知识共享。