在 Java 中创建 PDF 的缩略图

2022-09-01 19:14:02

我正在寻找一个Java库,它可以从第一页获取PDF并创建缩略图(PNG)。

我已经看过JPedal,但它疯狂的许可费完全令人望而却步。我目前正在使用iText来操作PDF文件,但我相信它不会进行缩略图生成。我可以在命令行上使用类似Ghostscript的东西,但如果可能的话,我希望保持我的项目全Java。


答案 1

PDF Renderer是一个LGPL许可的纯java库,它使它变得简单(取自他们的示例页面):

File file = new File("test.pdf");
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);

// draw the first page to an image
PDFPage page = pdffile.getPage(0);

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

//generate the image
Image img = page.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
                );

答案 2

PDF 渲染器很好,只要您只使用它们使用的 PDF 文件的子集即可。使用JPod和JPedal,您需要为一个活跃且开发的库付费,而不是一个死项目。


推荐