1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| import com.google.common.collect.Lists; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List;
public class PDFUtil {
private static final int DEFAULT_DPI = 72; private static final String DEFAULT_IMAGE_FORMAT = "png";
private static List<byte[]> pdfToImage(PDDocument doc, String imageFormat, int dpi) throws IOException { PDFRenderer renderer = new PDFRenderer(doc); int totalPageCount = doc.getNumberOfPages(); List<byte[]> outputPages = Lists.newArrayListWithCapacity(totalPageCount); for (int i = 0; i < totalPageCount; i++) { try (ByteArrayOutputStream outputPage = new ByteArrayOutputStream()) { BufferedImage image = renderer.renderImageWithDPI(i, dpi); ImageIO.write(image, imageFormat, outputPage); outputPages.add(outputPage.toByteArray()); } } return outputPages; }
public static List<byte[]> pdfToImage(byte[] input, String imageFormat, int dpi) throws IOException { try (PDDocument doc = PDDocument.load(input)) { return pdfToImage(doc, imageFormat, dpi); } }
public static List<byte[]> pdfToImage(byte[] input) throws IOException { return pdfToImage(input, DEFAULT_IMAGE_FORMAT, DEFAULT_DPI); }
public static List<byte[]> pdfToImage(InputStream input, String imageFormat, int dpi) throws IOException { try (PDDocument doc = PDDocument.load(input)) { return pdfToImage(doc, imageFormat, dpi); } }
public static List<byte[]> pdfToImage(InputStream input) throws IOException { return pdfToImage(input, DEFAULT_IMAGE_FORMAT, DEFAULT_DPI); }
}
|