java pdf 多页转换为png格式的图片 适用于 无论pdf有多少页均可
废话不说,直接上代码
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
/**
*
* @author wdg pdf 转换为pdf
*
*/
public class PdfToPng {
/***
*
*
* 使用方式
*
* maven 项目中需要引入:
* <dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.21</version>
</dependency>
*
*
*
* 方法是将多张pdf 转换为png 格式的图片
* @param pdffile pdf 文件路径
* @param targetPath png 文件存储路径
* @param height_offset 多张图片之间合成间隔距离
*/
public static void pdfFileToImage(File pdffile, String targetPath,int height_offset) {
try {
FileInputStream instream = new FileInputStream(pdffile);
InputStream byteInputStream = null;
try {
PDDocument doc = PDDocument.load(instream);
PDFRenderer renderer = new PDFRenderer(doc);
int pageCount = doc.getNumberOfPages();
List<BufferedImage> list = new ArrayList<BufferedImage>();
if (pageCount > 0) {
int totalHeight = 0;
int width = 0;
for (int i = 0; i < pageCount; i++) {
BufferedImage image = renderer.renderImage(i, 1.25f);
list.add(image);
totalHeight += image.getHeight();
if (width < image.getWidth()) {
width = image.getWidth();
}
image.flush();
}
BufferedImage tag = new BufferedImage(width, totalHeight, BufferedImage.TYPE_INT_RGB);
tag.getGraphics();
Graphics g = tag.createGraphics();
int startHeight = 0;
for (BufferedImage image : list) {
g.drawImage(image, 0, startHeight, width, image.getHeight(), null);
g.drawImage(image, 0, startHeight, width, image.getHeight(), null);
startHeight += image.getHeight() + height_offset;
}
g.dispose();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
ImageOutputStream imOut;
imOut = ImageIO.createImageOutputStream(bs);
ImageIO.write(tag, "png", imOut);
byteInputStream = new ByteArrayInputStream(bs.toByteArray());
byteInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
File uploadFile = new File(targetPath);
FileOutputStream fops;
fops = new FileOutputStream(uploadFile);
fops.write(readInputStream(byteInputStream));
fops.flush();
fops.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
public static void main(String[] args) {
File file = new File("D:\\pdfpath\\ceshi2.pdf");
// 上传的是png格式的图片结尾
String targetfile = "D:\\pdfpath\\wdg3.png";
pdfFileToImage(file, targetfile,10);
}
}
希望对你有所帮助