Groovy - how to Decode a base 64 string and save it to a pdf/doc in local directory

孤街浪徒 提交于 2019-12-25 01:54:11

问题


Question

I need help with decoding a base 64 string and saving it to a pdf/doc in local directory using groovy This script should work in SOAP UI The base64 string is 52854 characters long

I have tried the following

File f = new File("c:\\document1.doc")
FileOutputStream out = null 
byte[] b1 = Base64.decodeBase64(base64doccontent);
out = new FileOutputStream(f)
try {
    out.write(b1)
} finally {
    out.close()
}

But - it gives me below error

No signature of method: static org.apache.commons.codec.binary.Base64.decodeBase64() is applicable for argument types: (java.lang.String) values: [base64stringlong] Possible solutions: decodeBase64([B), encodeBase64([B), encodeBase64([B, boolean)


回答1:


Assuming the base64 encoded text is coming from a file, a minimal example for soapUI would be:

import com.itextpdf.text.*
import com.itextpdf.text.pdf.PdfWriter;

String encodedContents = new File('/path/to/file/base64Encoded.txt')
    .getText('UTF-8')
byte[] b1 = encodedContents.decodeBase64();

// Save as a text file
new File('/path/to/file/base64Decoded.txt').withOutputStream {
        it.write b1
} 

// Or, save as a PDF
def document = new Document()
PdfWriter.getInstance(document, 
    new FileOutputStream('/path/to/file/base64Decoded.pdf'))

document.open()
document.add(new Paragraph(new String(b1)))
document.close()

The File.withOutputStream method will ensure the stream is closed when the closure returns.

Or, to convert the byte array to a PDF, I used iText. I dropped itextpdf-5.5.13.jar in soapUI's bin/ext directory and restarted and then it was available for Groovy.



来源:https://stackoverflow.com/questions/49593847/groovy-how-to-decode-a-base-64-string-and-save-it-to-a-pdf-doc-in-local-direct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!