PDF-Renderer是Sun公布的一个开源项目, 它主要目的是方便用户展示PDF文档。 通过解析PDF文档, 使用户能够在自己的应用中查看, 预览,绘制PNG和合并到3D的场景中。 关于该项目的介绍可以看这里。不过貌似很久没更新了。也是,Sun都已被Oracle收购很久了~
不过前段时间搞PDF打印的时候也实践了一下PDF-Renderer,下面是一段实例代码:
public class TestPDFRenderer {
public void Pdf_Png(int pageNumber) {
int pagen = pageNumber;
File file = new File("E:/maven.pdf");
PDFFile pdffile = null;
// set up the PDF reading
try {
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0,
channel.size());
pdffile = new PDFFile(buf);
} catch (Exception e) {
e.printStackTrace();
}
//if (pagen < pdffile.getNumPages())
//return;
// print出该pdf文档的页数
System.out.println(pdffile.getNumPages());
// 设置将第pagen也生成png图片
PDFPage page = pdffile.getPage(pagen);
// create and configure a graphics object
int width = (int) page.getBBox().getWidth();
int height = (int) page.getBBox().getHeight();
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// do the actual drawing
PDFRenderer renderer = new PDFRenderer(page, g2, new Rectangle(0, 0,
width, height), null, Color.WHITE);
try {
page.waitForFinish();
} catch (Exception e) {
e.printStackTrace();
}
renderer.run();
g2.dispose();
try {
ImageIO.write(img, "gif", new File("D:/Image.gif"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
new TestPDFRenderer().Pdf_Png(1);
}
}
生成了gif之后,可以利用打印机将该图片打印出来。
不过,也许是使用了针式打印机的缘故吧,打印出来的效果很差。