如何在Java中使用ApachePDFBoxAPI将PDF的字节数组转换为jpg图像的字节数组?
我在我的项目中被分配了这个任务。我从一个服务中获取PDF的字节数组,我必须将其转换为JPG图像的字节数组并返回JPG的字节数组。有人能帮我吗 我尝试了下面的解决方案,即将PDF字节数组转换为JPG,但不返回JPG的字节数组如何在Java中使用ApachePDFBoxAPI将PDF的字节数组转换为jpg图像的字节数组?,java,apache,file-io,pdfbox,Java,Apache,File Io,Pdfbox,我在我的项目中被分配了这个任务。我从一个服务中获取PDF的字节数组,我必须将其转换为JPG图像的字节数组并返回JPG的字节数组。有人能帮我吗 我尝试了下面的解决方案,即将PDF字节数组转换为JPG,但不返回JPG的字节数组 import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.pdfbox.util.PDFImageWriter
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.pdfbox.util.PDFImageWriter;
import org.apache.pdfbox.pdmodel.PDDocument;
public class DocumentService{
public byte[] convertPDFtoImage(byte[] bytes) {
InputStream targetStream = new ByteArrayInputStream(bytes);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PDDocument document = null;
try {
document = PDDocument.load(targetStream);
PDFImageWriter writer = new PDFImageWriter();
writer.writeImage(document, "jpg", null, 1, 2, "C:\\Shailesh\\aaa");
} catch (Exception e) {
log.error(e.getMessage(), e);
e.printStackTrace();
}
}
}
我找到了一个解决方案,但没有找到渲染器。renderImageWithDPI(pageNumber,300)方法将pageNumber作为方法参数,并且它一次只能转换PDF的一页。但是我需要以字节数组的形式将完整的PDf格式转换成JPG格式
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
public class DocumentService {
public byte[] convertPDFtoImage(byte[] bytesPDF) {
InputStream targetStream = new ByteArrayInputStream(bytesPDF);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PDDocument document = null;
try {
document = PDDocument.load(targetStream);
PDFRenderer renderer = new PDFRenderer(document);
int pageNumber = 1;
BufferedImage bi = renderer.renderImageWithDPI(pageNumber, 300);
ImageIO.write(bi, "jpg", baos);
baos.flush();
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (document != null) {
try {
document.close();
baos.close();
log.info("End convert PDF to Images process");
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
return baos.toByteArray();
}
}
谷歌搜索“JavaConvertPDF-toJPG”似乎是一个明显的起点。我对我的问题进行了编辑,使其更加具体和清晰。谁能提出一个解决方案?