Java 使用PDFBox将图像转换为PDF文件

Java 使用PDFBox将图像转换为PDF文件,java,pdf-generation,pdfbox,Java,Pdf Generation,Pdfbox,我想将一些图像转换为PDDocument对象,而不是保存到硬件。如何从这个PDDocument对象获取输入流 我写的如下,得到了“CreateInputStream调用,之前没有将数据写入流。”错误 资料来源部分为: public ByteArrayOutputStream imagesToPdf(final List<ImageEntity> images) throws IOException { final PDDocument doc = new PDDocument

我想将一些图像转换为
PDDocument
对象,而不是保存到硬件。如何从这个
PDDocument
对象获取输入流

我写的如下,得到了“CreateInputStream调用,之前没有将数据写入流。”错误

资料来源部分为:

public ByteArrayOutputStream imagesToPdf(final List<ImageEntity> images) throws IOException {
    final PDDocument doc = new PDDocument();
    
    final int count = images.size();
    InputStream in = null;
    PDPageContentStream contentStream = null;
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        for (int i = 0; i < count; i ++) {
            final ImageEntity image = images.get(i);
            byte[] byteCode = image.getByteCode();

            in = new ByteArrayInputStream(byteCode);
            BufferedImage bi = ImageIO.read(in);

            float width = bi.getWidth();
            float height = bi.getHeight();
            PDPage page = new PDPage(new PDRectangle(width, height));
            doc.addPage(page); 

            PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, byteCode, null);
            contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
            
            float scale = 1f;
            contentStream.drawImage(pdImage, 0, 0, pdImage.getWidth()*scale, pdImage.getHeight()*scale);
            
            IOUtils.closeQuietly(contentStream);
            IOUtils.closeQuietly(in);
        }

        PDStream ps = new PDStream(doc);
        is = ps.createInputStream();
        IOUtils.copy(is, baos);

        return baos;
    } finally {
        IOUtils.closeQuietly(contentStream);
        IOUtils.closeQuietly(in);
    }
}
public ByteArrayOutputStream imagesToPdf(最终列表图像)引发IOException{
最终PDDocument文档=新PDDocument();
最终整数计数=images.size();
InputStream in=null;
PDPageContentStream contentStream=null;
最终ByteArrayOutputStream bas=新ByteArrayOutputStream();
试一试{
for(int i=0;i
不创建一个对象,从中可以按照您假定的序列化形式检索
文档。它实际上是创建一个属于文档
doc
的PDF流对象

你想做的只是

doc.save(baos);

@用户1737352太棒了!在这种情况下,请将答案标记为已接受(单击左上角的勾号)。抱歉,我无法单击左上角的三角形符号,因为我的声誉低于15。在两个三角形下方应有一个勾号符号,您可以将其切换为灰色或绿色。勾号表示接受,三角形表示赞成或反对投票。无论你的名声如何,作为提出问题的人,你应该能够接受。太棒了。您给出了一个简单而正确的好主意。这是一个在没有物理存储的情况下将多个图像转换为单个pdf的好主意。令人惊叹的。
doc.save(baos);