<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.18</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>jbig2-imageio</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.18</version>
</dependency>
@Test
public void pdf2image2() throws IOException {
PDDocument pdDocument;
FileInputStream fileInputStream = new FileInputStream("d:/test.pdf");
pdDocument = PDDocument.load(fileInputStream);
PDFRenderer renderer = new PDFRenderer(pdDocument);
// 获取 PDF 页数
int pages = pdDocument.getNumberOfPages();
for (int i = 0; i < pages; i++) {BufferedImage image = renderer.renderImage(i, 2.5f, ImageType.BINARY, RenderDestination.PRINT);
FileOutputStream out = new FileOutputStream("d:\\imageresult" + i + ".png");
// PNG
ImageIO.write(image, "png", out);
}
pdDocument.close();}
应用 renderImage 会小很多
aspose
FileInputStream fileInputStream = new FileInputStream("D:\\test.pdf");
Document pdfDocument = new Document(fileInputStream);
Resolution resolution = new Resolution(72);
JpegDevice jpegDevice = new JpegDevice(740, 1046, resolution, 100);
RenderingOptions renderingOptions = new RenderingOptions();
for (int index = 1; index <= pdfDocument.getPages().size(); index++) {
// 输入门路
FileOutputStream out = new FileOutputStream("d:\\image" + index + ".jpg");
jpegDevice.process(pdfDocument.getPages().get_Item(index), out);
out.close();}
pdfDocument.close();
图片压缩
File imageFile = new File("d:\\imageresult0.jpg");
File compressedImageFile = new File("d:\\myimage_compressed.jpg");
InputStream is = new FileInputStream(imageFile);
OutputStream os = new FileOutputStream(compressedImageFile);
float quality = 0.01f;
// create a BufferedImage as the result of decoding the supplied InputStream
BufferedImage image = ImageIO.read(is);
// get all image writers for JPG format
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
if (!writers.hasNext())
throw new IllegalStateException("No writers found");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
writer.write(null, new IIOImage(image, null, null), param);
// close all streams
is.close();
os.close();
ios.close();
writer.dispose();