pdf转图片(每页一张图)或zip文件(压缩包里的文件pdf每页内容的图片文件)


import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.log4j.Logger;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

import sun.nio.ch.FileChannelImpl;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Pdf2ImgUtil {

    private static Logger logger = Logger.getLogger(Pdf2ImgUtil.class.getName());
    
    public static int pdf2Img(String pdfPath,String imgName,String imgPath, float scale) throws Exception  {
        File file = new File(pdfPath);
         if(!file.exists()){
             String msg = "文件:"+file.getAbsolutePath()+"不存在!";
             logger.error(msg);
             throw new RuntimeException(msg);
         }
        new File(imgPath).mkdirs();
        long t = System.currentTimeMillis();

        RandomAccessFile raf = null;
        sun.nio.ch.FileChannelImpl channel = null;
        ByteBuffer buf = null;
        try{
              raf = new RandomAccessFile(file , "r");
              channel = (FileChannelImpl) raf.getChannel();
              buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            
            
            PDFFile pdffile = new PDFFile(buf);
            int pageNums =  pdffile.getNumPages(); 
            for(int i = 1;i<=pageNums;i++){
                PDFPage page = pdffile.getPage(i);
                if(page == null){
                    return 0;
                }
                Rectangle rect = new Rectangle(
                            0,
                            0,
                            (int)page.getBBox().getWidth(),
                            (int)page.getBBox().getHeight()
                        );
                int width = (int) (rect.width *scale);
                int height = (int) (rect.height *scale);
                Image img = page.getImage(
                            width,
                            height,
                            rect, 
                            null,
                            true,
                            true
                        );
                BufferedImage tag = new BufferedImage(
                            width,
                            height,
                            BufferedImage.TYPE_INT_BGR
                        );
                tag.getGraphics().drawImage(img, 0, 0, width, height, null);
                FileOutputStream out = new FileOutputStream(imgPath+ "\\"+ imgName + i  + ".png");
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag);
                param.setQuality(1f, true);
                encoder.setJPEGEncodeParam(param);
                encoder.encode(tag);
                out.close();
            }
            buf.clear();
            
            System.out.println("pdf2Img:"+pdfPath+"  time:"+(System.currentTimeMillis()-t));

             return pageNums;
        }catch(IOException e){
            String msg = "文档转换出错:"+e.getMessage();
            logger.error(msg, e);
            throw  e;
        }finally{            
            if(channel != null){
                try {
                    channel.close();
                } catch (IOException e) {
                    logger.error("pdf2Img finally ", e);
                }
            }
             
            if(raf != null){
                try {
                    raf.close();
                } catch (IOException e) {
                    logger.error("pdf2Img finally ", e);
                }
            }
        
            Method method;
            try {
                //释放文件,不然文件会被占用
                method = FileChannelImpl.class.getDeclaredMethod("unmap", MappedByteBuffer.class);
                method.setAccessible(true);
                method.invoke(FileChannelImpl.class, buf);
        
            } catch (NoSuchMethodException e) {
                logger.error("pdf2Img finally ", e);
            } catch (SecurityException e) {
                logger.error("pdf2Img finally ", e);
            } catch (IllegalAccessException e) {
                logger.error("pdf2Img finally ", e);
            } catch (IllegalArgumentException e) {
                logger.error("pdf2Img finally ", e);
            } catch (InvocationTargetException e) {
                logger.error("pdf2Img finally ", e);
            }
            
        }
        
    }
    
    public static int pdf2ImgZip(String pdfPath,String imgName,String imgPath, float scale) throws Exception  {
        File file = new File(pdfPath);
         if(!file.exists()){
             String msg = "文件:"+file.getAbsolutePath()+"不存在!";
             logger.error(msg);
             throw new RuntimeException(msg);
         }
        new File(imgPath).mkdirs();
        long t = System.currentTimeMillis();

        RandomAccessFile raf = null;
        sun.nio.ch.FileChannelImpl channel = null;
        ByteBuffer buf = null;

        String temp = "image2zip.zip";            
        ZipOutputStream zipOS = null;
        
        try{
              raf = new RandomAccessFile(file , "r");
              channel = (FileChannelImpl) raf.getChannel();
              buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
              
              zipOS = new ZipOutputStream(new FileOutputStream(temp));
              
            PDFFile pdffile = new PDFFile(buf);
            int pageNums =  pdffile.getNumPages(); 
            for(int i = 1;i<=pageNums;i++){
                PDFPage page = pdffile.getPage(i);
                if(page == null){
                    return 0;
                }
                Rectangle rect = new Rectangle(
                            0,
                            0,
                            (int)page.getBBox().getWidth(),
                            (int)page.getBBox().getHeight()
                        );
                int width = (int) (rect.width *scale);
                int height = (int) (rect.height *scale);
                Image img = page.getImage(
                            width,
                            height,
                            rect, 
                            null,
                            true,
                            true
                        );
                BufferedImage tag = new BufferedImage(
                            width,
                            height,
                            BufferedImage.TYPE_INT_BGR
                        );
                tag.getGraphics().drawImage(img, 0, 0, width, height, null);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag);
                param.setQuality(1f, true);
                encoder.setJPEGEncodeParam(param);
                encoder.encode(tag);
                
                //
                ZipEntry entry = new ZipEntry((i) +".png");
                zipOS.putNextEntry(entry);
                zipOS.write(out.toByteArray());
                zipOS.flush();
                
                zipOS.closeEntry();//Closes the current ZIP entry and positions the stream for writing the next entry
                //
                                
                out.close();
                raf.close();
            }
            zipOS.close();
            buf.clear();

            System.out.println("pdf2ImgZip:"+pdfPath+"  time:"+(System.currentTimeMillis()-t));
             return pageNums;
        }catch(Exception e){
            String msg = "文档转换出错:"+e.getMessage();
            logger.error(msg, e);
            throw e;
        }finally{
            
            try {
                if(zipOS!=null)zipOS.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            
            Method method;
            try {
                //释放文件,不然文件会被占用
                method = FileChannelImpl.class.getDeclaredMethod("unmap", MappedByteBuffer.class);
                method.setAccessible(true);
                method.invoke(FileChannelImpl.class, buf);
         
            } catch (NoSuchMethodException e) {
                logger.error("pdf2ImgZip finally ", e);
            } catch (SecurityException e) {
                logger.error("pdf2ImgZip finally ", e);
            } catch (IllegalAccessException e) {
                logger.error("pdf2ImgZip finally ", e);
            } catch (IllegalArgumentException e) {
                logger.error("pdf2ImgZip finally ", e);
            } catch (InvocationTargetException e) {
                logger.error("pdf2ImgZip finally ", e);
            }
            if(channel != null){
                try {
                    channel.close();
                } catch (IOException e) {
                    logger.error("pdf2Img finally ", e);
                }
            }
             
            if(raf != null){
                try {
                    raf.close();
                } catch (IOException e) {
                    logger.error("pdf2ImgZip finally ", e);
                }
            }
    
        }
        
    }
    
    public static void main(String[] args) {
                
        String  filePath = "C:\\Users\\Administrator\\Desktop\\新建 Microsoft Word 文档.pdf";
        String targetDir = "C:\\Users\\Administrator\\Desktop\\新建文件夹 (5)";
        try {
            Pdf2ImgUtil.pdf2ImgZip(filePath, "", targetDir, 2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("e");
    }
    
    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现读取压缩包中的PDF文件并将其中的图片上传到服务器,你可以按照以下步骤进行操作: 1. 使用Java的压缩包相关库(如`java.util.zip.ZipInputStream`)来解压缩包。首先,你需要打开压缩包并获取到其中的PDF文件。 ```java String zipFilePath = "path/to/your/zip/file.zip"; try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath))) { ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { if (!entry.isDirectory() && entry.getName().endsWith(".pdf")) { // 找到了PDF文件,进行处理 // 在这可以读取PDF文件内容图片 } } } catch (IOException e) { e.printStackTrace(); } ``` 2. 使用PDF库(如Apache PDFBox或iText)来解析PDF文件,提取其中的图片。 ```java PDDocument document = PDDocument.load(new File("path/to/your/pdf/file.pdf")); PDFRenderer pdfRenderer = new PDFRenderer(document); for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) { BufferedImage image = pdfRenderer.renderImageWithDPI(pageIndex, 300, ImageType.RGB); // 处理每个页面的图片 // 在这可以将图片上传到服务器 } document.close(); ``` 3. 将提取到的图片上传到服务器。你可以使用Java中的HTTP库(如Apache HttpClient或HttpURLConnection)来进行文件上传操作。具体的上传方式取决于你使用的服务器端接口。 ```java // 使用Apache HttpClient进行文件上传 HttpPost request = new HttpPost("http://your-server-url/upload"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", imageBytes, ContentType.IMAGE_JPEG, "image.jpg"); HttpEntity multipart = builder.build(); request.setEntity(multipart); HttpClient httpClient = HttpClientBuilder.create().build(); HttpResponse response = httpClient.execute(request); // 处理上传结果 // ... ``` 以上是一个基本的实现思路,你可以根据具体的需求进行适当的调整和扩展。同时,请确保在代码中处理异常,适当关闭资源,并进行错误处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值