使用pdfbox,是否可以将PDF(或PDF字节[])转换为图像字节[]?我在网上查看了几个例子,我发现的唯一一个例子描述了如何直接将转换后的文件写入文件系统或将其转换为Java AWT对象 .
我宁愿不招致将图像文件写入文件系统的IO,读入byte [],然后删除它 .
所以我可以这样做:
String destinationImageFormat = "jpg";
boolean success = false;
InputStream is = getClass().getClassLoader().getResourceAsStream("example.pdf");
PDDocument pdf = PDDocument.load( is, true );
int resolution = 256;
String password = "";
String outputPrefix = "myImageFile";
PDFImageWriter imageWriter = new PDFImageWriter();
success = imageWriter.writeImage(pdf,
destinationImageFormat,
password,
1,
2,
outputPrefix,
BufferedImage.TYPE_INT_RGB,
resolution);
除此之外:
InputStream is = getClass().getClassLoader().getResourceAsStream("example.pdf");
PDDocument pdf = PDDocument.load( is, true );
List<PDPage> pages = pdf.getDocumentCatalog().getAllPages();
for ( PDPage page : pages )
{
BufferedImage image = page.convertToImage();
}
我不清楚的是如何将BufferedImage转换为byte [] . 我知道这会转换为imageWriter.writeImage()中的文件输出流,但我不清楚API是如何工作的 .
3 回答
您可以使用ImageIO.write写入OutputStream . 要获取byte [],请使用ByteArrayOutputStream,然后在其上调用toByteArray() .
添加maven依赖:
并且,将pdf转换为图像:
编辑: