2013-05-30 65 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。 –

相關問題