java PDF转jpg

Posted ESOO

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java PDF转jpg相关的知识,希望对你有一定的参考价值。

最近需要用到pdf转图片,发现不是需要花钱就是有水印限制,不是很好,自己做了个小程序,满足大家的需求:

maven:

<dependencies>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox-tools</artifactId>
            <version>2.0.5</version>
        </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk16</artifactId>
            <version>1.46</version>
        </dependency>
    </dependencies>

code:

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;

/**
 * Created by Administrator on 2019-02-28.
 */
public class PDF2IMG 

    private static final String PASSWORD = "-password";
    private static final String START_PAGE = "-startPage";
    private static final String END_PAGE = "-endPage";
    private static final String PAGE = "-page";
    private static final String IMAGE_TYPE = "-imageType";
    private static final String FORMAT = "-format";
    private static final String OUTPUT_PREFIX = "-outputPrefix";
    private static final String PREFIX = "-prefix";
    private static final String COLOR = "-color";
    private static final String RESOLUTION = "-resolution";
    private static final String DPI = "-dpi";
    private static final String CROPBOX = "-cropbox";
    private static final String TIME = "-time";

    public static void main(String[] args) throws IOException 
        System.setProperty("apple.awt.UIElement", "true");
        String password = "";
        String pdfFile = getFile().getPath();

        String outputFilePath="D:\\\\XS\\\\";

        String outputPrefix = "XSPdfTools";
        String imageFormat = "jpg";
        int startPage = 1;
        int endPage = 2147483647;
        String color = "rgb";
        float cropBoxLowerLeftX = 0.0F;
        float cropBoxLowerLeftY = 0.0F;
        float cropBoxUpperRightX = 0.0F;
        float cropBoxUpperRightY = 0.0F;
        boolean showTime = false;

        int dpi;
        try 
            dpi = Toolkit.getDefaultToolkit().getScreenResolution();
         catch (HeadlessException var28) 
            dpi = 96;
        

        for(int document = 0; document < args.length; ++document) 
            if(args[document].equals("-password")) 
                ++document;
                if(document >= args.length) 
                    usage();
                

                password = args[document];
             else if(args[document].equals("-startPage")) 
                ++document;
                if(document >= args.length) 
                    usage();
                

                startPage = Integer.parseInt(args[document]);
             else if(args[document].equals("-endPage")) 
                ++document;
                if(document >= args.length) 
                    usage();
                

                endPage = Integer.parseInt(args[document]);
             else if(args[document].equals("-page")) 
                ++document;
                if(document >= args.length) 
                    usage();
                

                startPage = Integer.parseInt(args[document]);
                endPage = Integer.parseInt(args[document]);
             else if(!args[document].equals("-imageType") && !args[document].equals("-format")) 
                if(!args[document].equals("-outputPrefix") && !args[document].equals("-prefix")) 
                    if(args[document].equals("-color")) 
                        ++document;
                        color = args[document];
                     else if(!args[document].equals("-resolution") && !args[document].equals("-dpi")) 
                        if(args[document].equals("-cropbox")) 
                            ++document;
                            cropBoxLowerLeftX = Float.valueOf(args[document]).floatValue();
                            ++document;
                            cropBoxLowerLeftY = Float.valueOf(args[document]).floatValue();
                            ++document;
                            cropBoxUpperRightX = Float.valueOf(args[document]).floatValue();
                            ++document;
                            cropBoxUpperRightY = Float.valueOf(args[document]).floatValue();
                         else if(args[document].equals("-time")) 
                            showTime = true;
                         else if(pdfFile == null) 
                            pdfFile = args[document];
                        
                     else 
                        ++document;
                        dpi = Integer.parseInt(args[document]);
                    
                 else 
                    ++document;
                    outputPrefix = args[document];
                
             else 
                ++document;
                imageFormat = args[document];
            
        

        if(pdfFile == null) 
            usage();
         else 
            if(outputPrefix == null) 
                outputPrefix = pdfFile.substring(0, pdfFile.lastIndexOf(46));
            

            PDDocument var30 = null;

            try 
                var30 = PDDocument.load(new File(pdfFile), password);
                ImageType imageType = null;
                if("bilevel".equalsIgnoreCase(color)) 
                    imageType = ImageType.BINARY;
                 else if("gray".equalsIgnoreCase(color)) 
                    imageType = ImageType.GRAY;
                 else if("rgb".equalsIgnoreCase(color)) 
                    imageType = ImageType.RGB;
                 else if("rgba".equalsIgnoreCase(color)) 
                    imageType = ImageType.ARGB;
                

                if(imageType == null) 
                    System.err.println("Error: Invalid color.");
                    System.exit(2);
                

                if(cropBoxLowerLeftX != 0.0F || cropBoxLowerLeftY != 0.0F || cropBoxUpperRightX != 0.0F || cropBoxUpperRightY != 0.0F) 
                    changeCropBox(var30, cropBoxLowerLeftX, cropBoxLowerLeftY, cropBoxUpperRightX, cropBoxUpperRightY);
                

                long startTime = System.nanoTime();
                boolean success = true;
                endPage = Math.min(endPage, var30.getNumberOfPages());
                PDFRenderer renderer = new PDFRenderer(var30);

                for(int endTime = startPage - 1; endTime < endPage; ++endTime) 
                    BufferedImage image = renderer.renderImageWithDPI(endTime, (float)dpi, imageType);
                    String duration = outputPrefix + (endTime + 1) + "." + imageFormat;

                    success &= ImageIOUtil.writeImage(image, duration,dpi);
                

                long var31 = System.nanoTime();
                long var32 = var31 - startTime;
                int count = 1 + endPage - startPage;
                if(showTime) 
                    System.err.printf("Rendered %d page%s in %dms\\n", new Object[]Integer.valueOf(count), count == 1?"":"s", Long.valueOf(var32 / 1000000L));
                

                if(!success) 
                    System.err.println("Error: no writer found for image format \\'" + imageFormat + "\\'");
                    System.exit(1);
                
             catch(Exception ex)
                ex.printStackTrace();
            finally 
                if(var30 != null) 
                    var30.close();
                

            
            System.out.println("转换完成");

        

    

    private static void usage() 
        String message = "Usage: java -jar pdfbox-app-x.y.z.jar PDFToImage [options] <inputfile>\\n\\nOptions:\\n  -password  <password>            : Password to decrypt document\\n  -format <string>                 : Image format: " + getImageFormats() + "\\n" + "  -prefix <string>                 : Filename prefix for image files\\n" + "  -page <number>                   : The only page to extract (1-based)\\n" + "  -startPage <int>                 : The first page to start extraction (1-based)\\n" + "  -endPage <int>                   : The last page to extract(inclusive)\\n" + "  -color <int>                     : The color depth (valid: bilevel, gray, rgb, rgba)\\n" + "  -dpi <int>                       : The DPI of the output image\\n" + "  -cropbox <int> <int> <int> <int> : The page area to export\\n" + "  -time                            : Prints timing information to stdout\\n" + "  <inputfile>                      : The PDF document to use\\n";
        System.err.println(message);
        System.exit(1);
    

    private static String getImageFormats() 
        StringBuilder retval = new StringBuilder();
        String[] formats = ImageIO.getReaderFormatNames();

        for(int i = 0; i < formats.length; ++i) 
            if(formats[i].equalsIgnoreCase(formats[i])) 
                retval.append(formats[i]);
                if(i + 1 < formats.length) 
                    retval.append(", ");
                
            
        

        return retval.toString();
    

    private static void changeCropBox(PDDocument document, float a, float b, float c, float d) 
        Iterator i$ = document.getPages().iterator();

        while(i$.hasNext()) 
            PDPage page = (PDPage)i$.next();
            System.out.println("resizing page");
            PDRectangle rectangle = new PDRectangle();
            rectangle.setLowerLeftX(a);
            rectangle.setLowerLeftY(b);
            rectangle.setUpperRightX(c);
            rectangle.setUpperRightY(d);
            page.setCropBox(rectangle);
        

    


    public static File getFile()
        JFileChooser jfc=new JFileChooser(); //设置当前路径为桌面路径,否则将我的文档作为默认路径
        FileSystemView fsv = FileSystemView .getFileSystemView();
        jfc.setCurrentDirectory(fsv.getHomeDirectory());
        //JFileChooser.FILES_AND_DIRECTORIES 选择路径和文件
        jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
        //弹出的提示框的标题
        jfc.showDialog(new JLabel(), "确定");
        //用户选择的路径或文件
        File file=jfc.getSelectedFile();
        return file;
    

   

 

以上是关于java PDF转jpg的主要内容,如果未能解决你的问题,请参考以下文章

用java实现pdf转jpg图片的全代码,我这里附上参考代码。

java PDF转jpg

java实现word,ppt,excel,jpg转pdf

java pdf转图片问题

Java如何把一个PDF转为tif

JPG转PDF在线转换的方法