PDFRenderer 生成图片

本文介绍了一种将PDF文档页面转换为图片的方法,并提供了实现这一功能的Java代码示例。该方法可以将PDF文档中的指定页面渲染成图片格式,适用于文档预览等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将PDF文档中的页面生成图片,导出。

/**浏览页面,生成页面的图片字节数据
*
* @param fileName 文档名称及路径
* @param page
* @param type
* @return
*/
public byte[] ViewPage(String fileName, int page, String type) {
if(fileName==null||fileName.length()<=0)
return null;
// if(!fileName.endsWith("pdf")||!fileName.endsWith("PDF"))
// return null;
try
{
BitImgType imgType = BitImgType.valueOf(type.toUpperCase());
if(imgType==null)return null;

PDFFile pdfFile = this.getPdfFile(fileName);
if(pdfFile==null)
return null;
PDFPage pdfPage = pdfFile.getPage(page);
if(pdfPage==null)return null;

//get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0,0,
(int)pdfPage.getBBox().getWidth(),
(int)pdfPage.getBBox().getHeight());

//generate the image
Image img = pdfPage.getImage(
rect.width, rect.height, //width & height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
BufferedImage bImg =(BufferedImage)img;
ImageIO.write(bImg, imgType.toString(), baos);

return baos.toByteArray();
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
/**建立PDF文档读取类
*
* @param filePath PDF文件的路径
* @return null 或者PDFFile instance
*/
private PDFFile getPdfFile(String filePath)
{
try
{
File file = new File(filePath);
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);
return pdffile;
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}

下面的代码从PDFRenderer 的example而来

public class PDFViewer {

public static void setup() throws IOException {

//set up the frame and panel
JFrame frame = new JFrame("PDF Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PagePanel panel = new PagePanel();
frame.add(panel);
frame.pack();
frame.setVisible(true);

//load a pdf from a byte buffer
String urlPath = "E:\\ArcGIS 应用\\ESRI技术白皮书\\ESRIData&Maps9.3.pdf";
File file = new File(urlPath);
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);

// show the first page
PDFPage page = pdffile.getPage(0);
panel.showPage(page);
}

public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
PDFViewer.setup();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值