繁体   English   中英

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

[英]Convert images to PDF file using PDFBox

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

我写如下,得到“创建 InputStream 调用之前没有写入数据流。” 错误。

源码部分为:

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);
    }
}
new PDStream(doc)

不会像您假设的那样创建可以以序列化形式从中检索doc的对象。 它实际做的是创建一个属于文档doc的 PDF 流对象

你想做的很简单

doc.save(baos);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM