java - Apache PDFBox:有没有办法只使用流?
问题描述
我的代码需要从 S3 InputStream 中提取图像,创建 PDF,将其添加到 ZipOutputStream,最后使用 OutputStream 将其发送回用户。我真的很想在不将任何字节读入内存的情况下完成此操作。目前我正在使用以下代码执行上述所有操作(减去 PDF 转换):
public void myFunction(List<String> fileKeys, OutputStream responseStream) throws Exception {
ZipOutputStream zipOutput = new ZipOutputStream(responseStream);
for (String fileKey : fileKeys) {
S3Object s3Obj = getS3Object(fileKey);
try (InputStream data = s3Obj.getObjectContent()) {
ZipEntry entry = new ZipEntry(fileKey);
zipOutput.putNextEntry(entry);
IOUtils.copy(data, zipOutput);
zipOutput.closeEntry();
} catch (Exception e) {
throw e;
}
}
zipOutput.close();
}
但是,我一生都无法弄清楚如何让 PDFBox 不将图像字节读入内存。也许这是不可能的?我现在有一些工作代码,但监视 JVM 堆显示有很多东西进入内存。
public void myFunction(List<String> fileKeys, OutputStream responseStream) throws Exception {
ZipOutputStream zipOutput = new ZipOutputStream(responseStream);
for (String fileKey : fileKeys) {
S3Object s3Obj = getS3Object(fileKey);
try (InputStream data = s3Obj.getObjectContent()) {
ZipEntry entry = new ZipEntry(fileKey);
zipOutput.putNextEntry(entry);
BufferedImage bim = ImageIO.read(data);
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDImageXObject pdImage = JPEGFactory.createFromImage(doc, bim);
PDPageContentStream contents = new PDPageContentStream(doc, page);
contents.drawImage(pdImage, 50, 50);
contents.beginText();
contents.setFont(PDType1Font.HELVETICA, 8);
contents.showText("Document: " + fileKey);
contents.endText();
contents.close();
COSWriter writer = new COSWriter(zipOutput);
writer.write(doc);
doc.close();
zipOutput.closeEntry();
} catch (Exception e) {
throw e;
}
}
zipOutput.close();
}
解决方案
推荐阅读
- c - memcpy 和内存位置
- file - 使用 perl 在没有子文件夹的文件夹中搜索特定文件
- r - 在 ubuntu 中更新 R 后遇到问题
- c# - 将应用程序发送到后台时,Xamarin.iOS 应用程序中的 HTTP 调用崩溃
- python - 子类化numpy:numpy方法返回ndarray而不是sublassed类型?
- php - PHP PDO Bind Param with having Clause,其中聚合函数与变量混合
- arrays - 如何通过两个键对多维数组进行排序
- java - IntelliJ 插件:以编程方式编辑运行配置设置和/或从上下文创建
- c - 如何在 Visual Studio 调试控制台中生成 BACKSPACE?
- javascript - Telegraf : 发送动画后发送消息