使用Java将PDF文件转成图片

news/2024/5/19 0:01:37 标签: jar, maven, swing, jdbc, git

使用Java将PDF文件转成图片

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

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by David on 2016/11/15.
 */
public class Pdf2Pic {
    /**
     * 根据pdf文件拆分图片
     * @param ossKey
     * @param file
     * @return
     * @throws IOException
     */
    public static String splitPic(String ossKey,File file) throws IOException {
        // load a pdf from a byte buffer

        RandomAccessFile raf = new RandomAccessFile(file, "r");
        FileChannel channel = raf.getChannel();
        ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel
                .size());
        PDFFile pdffile = new PDFFile(buf);

        System.out.println("页数: " + pdffile.getNumPages());

        String getPdfFilePath = CheckResultConstances.PATH_PDF_PIC+ossKey;

        //目录不存在,则创建目录
        File p=new File(getPdfFilePath);
        if(!p.exists()){
            p.mkdir();
        }

        System.out.println("getPdfFilePath is  :"+getPdfFilePath);

        for (int i = 1; i <= pdffile.getNumPages(); i++) {
            // draw the first page to an image
            PDFPage page = pdffile.getPage(i);

            // get the width and height for the doc at the default zoom
            Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
                    .getWidth(), (int) page.getBBox().getHeight());

            // generate the image
            Image img = page.getImage(rect.width, rect.height, // width &
                    // height
                    rect, // clip rect
                    null, // null for the ImageObserver
                    true, // fill background with white
                    true // block until drawing is done
            );

            BufferedImage tag = new BufferedImage(rect.width, rect.height,
                    BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height,
                    null);

            String dstName=getPdfFilePath+File.separator + i + ".jpg";
            FileOutputStream out = new FileOutputStream(dstName); // 输出到文件流
            System.out.println("成功保存图片到 :  " +getPdfFilePath+File.separator + i + ".jpg");
//
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//            encoder.encode(tag); // JPEG编码


            String formatName = dstName.substring(dstName.lastIndexOf(".") + 1);
            //FileOutputStream out = new FileOutputStream(dstName);
            //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            //encoder.encode(dstImage);
            ImageIO.write(tag, /*"GIF"*/ formatName /* format desired */ , new File(dstName) /* target */ );


            out.close();

        }
        return getPdfFilePath;

        // show the image in a frame
        // JFrame frame = new JFrame("PDF Test");
        // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // frame.add(new JLabel(new ImageIcon(img)));
        // frame.pack();
        // frame.setVisible(true);
    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                            File file = new File("/Users/David/Downloads/test.pdf");
                   new Pdf2Pic().splitPic("123",file);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

}

pom.xml依赖配置(将附件中的该jar包上传到nexus内部仓库):

<dependency>
	<groupId>com.sun.pdfview</groupId>
	<artifactId>pdfrenderer</artifactId>
	<version>0.9.0</version>
</dependency>

参考:

https://my.oschina.net/shma1664/blog/270513

http://superich2008.iteye.com/blog/2047830


http://www.niftyadmin.cn/n/1547121.html

相关文章

c 读文件

c 读文件 #include <stdio.h>#include <stdlib.h>#include <string.h>#defineszBUF 30000intmain(intargc, char*argv[]){ charfilename[szBUF]{0}; charbuf[szBUF]{0}; chara[szBUF]; char*need_find_start "<RoomType>"; i…

计算机控制系统考试题目,计算机控制系统模拟试题一.doc

文档介绍&#xff1a;计算机控制系统模拟试题一填空题(20分)1、计算机控制系统就是利用计算机来实现生产过程自动控制的系统,它的工作原理可以分为、和三个步骤; 计算机控制系统的典型形式有、、、、和。2、工业控制机的特点是、、、、、和; 工业控制计算机的硬件组成有、、、、…

Base64字符解码保存文件

Base64字符解码保存文件 /*** 将base64字符解码保存文件* param base64Code* param targetPath* throws Exception*/public void decoderBase64File(String base64Code, String targetPath)throws Exception, IOException {byte[] buffer new BASE64Decoder().decodeBuffer(ba…

Rails初步,常用命令和网址

1.gem update --systemgem update rails更新特定版本&#xff1a;gem install rails --version 2.2.22.从本地更新&#xff1a;gem install --local rubygems-update-1.3.7.gem3.下载gems&#xff1a;http://rubyforge.org/frs/?group_id1264.Instant Rails&#xff1a;http:/…

计算机软件专利副本,计算机软件授予专利有哪些

对于这个问题&#xff0c;解答如下, 授予专利权的“三性”要求对专利申请和审查来说都十分重要。根据我国专利法第22条规定&#xff0c;授予专利权的发明和实用新型&#xff0c;应当具备新颖性、创造性和实用性。基因专利也必须符合“三性”&#xff0c;在实用性上还有更高要求…

GlusterFS安装和系统要求(二)

一、系统要求 安装的GlusterFS之前&#xff0c;确认您的系统符合以下最低要求&#xff1a; 1.存储服务器 GlusterFS支持大多数的符合商业标准的x86-64bit硬件平台。存储可以是直接附加的存储&#xff0c;RAID盘&#xff0c;以SATA/SAS/FC盘做后端的FC/Infiniband/iSCSI SAN盘。…

Maven pom.xlm中添加jar到bootclasspath

Maven pom.xlm中添加jar到bootclasspath 例如&#xff1a;添加jra中的jar包(jre/lib/rt.jar)到 JAVA_HOME <properties><maven-compiler.version>3.1</maven-compiler.version><java.version>1.8</java.version></properties><!-- 编译…

消除计算机硬盘的碎片应该使用,Win10系统如何对磁盘碎片进行彻底清理优化

win10系统用户在操作使用电脑进行工作学习的过程中&#xff0c;电脑磁盘也会产生大量的垃圾文件和磁盘碎片&#xff0c;这些垃圾文件和磁盘碎片不仅会占用磁盘空间容量&#xff0c;还会影响到系统运行速度&#xff0c;遇到这种情况我们应该怎么办呢&#xff1f;其实我们可以手动…