2013-05-30 70 views
0

我们将Base 64编码的图形图像作为webservice响应,我们必须将其转换为PDF文件。我们使用波纹管代码片段将base 64编码的图形图像转换为pdf doc。将Base 64编码的图形图像转换为PDF文件时的问题

// 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文件,我们得到了波纹管错误。

Adob​​e 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文件。

回答

0

我在这里错过了一步。请尝试以下

  • 首先,从如下中的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文件。
+0

感谢Santosh的评论。我想直接将Base 64编码图形图像转换为pdf文件,而不是先将其转换为图像,然后再转换为pdf。 –

相关问题