【问题标题】:Groovy - how to Decode a base 64 string and save it to a pdf/doc in local directoryGroovy - 如何解码 base 64 字符串并将其保存到本地目录中的 pdf/doc
【发布时间】:2018-04-02 09:37:08
【问题描述】:

问题

我需要帮助来解码 base 64 字符串并使用 groovy 将其保存到本地目录中的 pdf/doc 这个脚本应该在 SOAP UI 中工作 base64 字符串长度为 52854 个字符

我已经尝试了以下

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()
}

但是 - 它给了我以下错误

没有方法签名:静态 org.apache.commons.codec.binary.Base64.decodeBase64() 适用于参数类型:(java.lang.String) 值:[base64stringlong] 可能的解决方案:decodeBase64([B) , encodeBase64([B), encodeBase64([B, boolean)

【问题讨论】:

标签: groovy soapui


【解决方案1】:

假设 base64 编码文本来自文件,soapUI 的最小示例是:

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()

File.withOutputStream 方法将确保在闭包返回时关闭流。

或者,要将字节数组转换为 PDF,我使用了iText。我将itextpdf-5.5.13.jar 放到soapUI 的bin/ext 目录中并重新启动,然后它就可以用于Groovy。

【讨论】:

  • 非常感谢@craigcaulfield 抱歉回复晚了。我使用 itextpdf-5.5.13.jar 尝试了您的方法,但是在尝试运行此 No signature of method: java.lang.String.getText() is applicable for argument types: (java.lang.String) values: [UTF-8] Possible solutions: getAt(java.lang.String), getAt(java.util.Collection), getAt(groovy.lang.IntRange), getAt(int), getAt(groovy.lang.Range), getAt(groovy.lang.EmptyRange) 时出现以下错误@我需要导入任何其他库吗?
  • 这是我用于根据您之前的建议从 base64 字符串保存到 pdf 的代码 def encodedContent = actualbase64.getText('UTF-8') //actualbase64 is the base 64 encoded string byte[] b1 = encodedContents.decodeBase64() def document = new Document() PdfWriter.getInstance(document, new FileOutputStream('D:/path/to/file/base64Decoded.pdf')) document.open() document.add(new Paragraph(new String(b1))) document.close()
  • 上面的示例假设您正在将文件中的编码内容读入字符串。但是,您的actualbase64 已经是一个字符串,因此您不需要def encodedContent = actualbase64.getText('UTF-8') 行。只需使用byte[] b1 = actualbase64.decodeBase64()
  • 那行得通——再次感谢@craigcaulfield。但是现在 pdf 内容像下面这样乱码,我怎样才能将其显示为完全格式化的文本。如果我使用转换器手动转换它,那么%PDF-1.5 5 0 obj <</Type /Page/Parent 3 0 R/Contents 6 0 R/MediaBox [0 0 595.29998779 841.90002441]/Resources<</Font<</FAAAAI 8 0 R/FAAABF 15 0.
  • 这个方法对我在soapUI中经常遇到的简单文本文件很有效,但是更丰富的内容可能需要更多的按摩。因为这些 cmets 中没有太多空间,所以最好解决这个问题并提出一个单独的问题,并提供一个您正在使用的文档示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-20
  • 2021-10-14
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多