1、下载一个 PDFRenderer.jar的包
2、相关代码
import java.awt.Image;
import java.awt.Rectangle;
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;
import javax.imageio.ImageIO;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
public class PdfToJpgUtil
{
public static int convertPdfToJpg(String srcFile, String tarFile,
String tarPath)
{
int pageCnt = 0;
try
{
// 加载PDF文件
File file = new File(srcFile);
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);
pageCnt = pdffile.getNumPages();
for (int i = 1; i <= pdffile.getNumPages(); i++)
{
PDFPage page = pdffile.getPage(i);
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
.getWidth(), (int) page.getBBox().getHeight());
int width = 1700;
int height = rect.height * 1700 / rect.width;
Image img = page
.getImage(width, height, rect, null, true, true);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img, 0, 0, width, height, null);
String path = tarPath + "detail/" + i + ".jpg";
// 输出到文件流
FileOutputStream out = new FileOutputStream(path);
ImageIO.write(tag, "jpg", out);
out.close();
raf.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
return pageCnt;
}
public static void convertPdfToJpg(String srcFile, String tarPath)
{
RandomAccessFile raf=null;
try
{
// 加载PDF文件
File file = new File(srcFile);
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);
if (pdffile.getNumPages() > 0)
{
PDFPage page = pdffile.getPage(1);
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
.getWidth(), (int) page.getBBox().getHeight());
int width = rect.width;
int height = rect.height;
Image img = page
.getImage(width, height, rect, null, true, true);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img, 0, 0, width, height, null);
FileOutputStream out = new FileOutputStream(tarPath); // 输出到文件流
ImageIO.write(tag, "jpg", out);
out.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}finally{
if(raf!=null){
try {
raf.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12060579/viewspace-1788370/
,如需转载,请注明出处,否则将追究法律责任。