【问题标题】:Issue when converting Base 64 encoded graphic image to PDF file将 Base 64 编码的图形图像转换为 PDF 文件时出现问题
【发布时间】:2013-05-30 06:21:39
【问题描述】:

我们正在获取 Base 64 编码的图形图像作为 Web 服务响应,我们必须将其转换为 PDF 文件。我们使用下面的代码 sn-p 将 base 64 编码的图形图像转换为 pdf doc。

// First decode the Base 64 encoded graphic image
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(s);

// Create the pdf file
File file = new File("output.png");
FileOutputStream fop = new FileOutputStream(file);

fop.write(decodedBytes);
fop.flush();
fop.close();

但是当我们打开 pdf 文件时,出现以下错误。

Adobe Reader 无法打开“output.pdf”,因为它不是受支持的文件类型或文件已损坏。

我们尝试了如下的 PDF 框,

BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(s);

ImageToPDF imageToPdf = new ImageToPDF();
imageToPdf.createPDFFromImage("output.pdf", decodedBytes.toString());

这也没有帮助我们。请建议我一种从 Base 64 编码的图形图像创建 pdf 文件的方法。

【问题讨论】:

    标签: java pdf pdfbox


    【解决方案1】:

    我觉得你在这里错过了一步。请尝试关注

    • 首先,从Base64数据创建图像如下(取自here

    字符串 base64String = "BORw0KGgoAAAANSUhEUgAAAUAAAAHgCAYAAADUjLREAAAgAElEQVR4AexdB4BU1dX+ZmZ7ZWGX3pHeu6goitgQDCZGjdHYu4nGqL81mmaJvdd";

        BASE64Decoder decoder = new BASE64Decoder();
        byte[] decodedBytes = decoder.decodeBuffer(base64String);
        log.debug("Decoded upload data : " + decodedBytes.length);
    
    
    
         String uploadFile = "/tmp/test.png";
         log.debug("File save path : " + uploadFile);
    
         BufferedImage image = ImageIO.read(new ByteArrayInputStream(decodedBytes));
         if (image == null) {
              log.error("Buffered Image is null");
          }
         File f = new File(uploadFile);
    
         // write the image
          ImageIO.write(image, "png", f);
    

    请注意,此示例使用sun.misc.BASE64Decoder,但我建议不要使用它,而是使用其他一些开源解码器(例如 apache commend-codec 库很好并且被广泛使用。)。

    • 获得图像文件后,使用ImageToPDF 将其转换为PDF 文件。

    【讨论】:

    • 感谢 Santosh 的评论。我想将 Base 64 编码的图形图像直接转换为 pdf 文件,而不是先将其转换为图像,然后再转换为 pdf。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2017-12-04
    • 2010-10-06
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多