从Java中的二进制数据创建pdf [英] create pdf from binary data in java

查看:136
本文介绍了从Java中的二进制数据创建pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Web服务获取此字符串.

" JVBERi0xLjQKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL1Jlc291cmNlcyAyIDAgUgovR3JvdXAgPDwvVHlwZSAvRJJyZLZYYZJYZJYZ1Y

它应该是pdf文件,我尝试了来自Apache的 pdfbox 库,但是它将内容写为pdf内的文本.我已经尝试过使用 ByteArrayInputStream ,但是创建的pdf无效,已损坏,这是我编写的一些代码.

public void escribePdf(String texto, String rutaSalida) throws IOException{

    byte[] biteToRead = texto.getBytes();
    InputStream is = new ByteArrayInputStream(biteToRead );
    DataOutputStream out = new DataOutputStream(new  BufferedOutputStream(new FileOutputStream(new File(rutaSalida))));
    int c;
    while((c = is.read()) != -1) {
        out.writeByte(c);
    }
    out.close();
    is.close();

}

解决方案

这是Base64编码的数据(很可能是UTF-8),必须在使用前解码.例如:

import sun.misc.BASE64Decoder;

...

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

....

对于Java> = 1.8,请使用:

byte[] decodedBytes = java.util.Base64.getDecoder().decode(biteToRead);

I'm getting this string from a web service.

"JVBERi0xLjQKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL1Jlc291cmNlcyAyIDAgUgovR3JvdXAgPDwvVHlwZSAvR3JvdXAgL1MgL1RyYW5zcGFyZW5jeSAvQ1MgL0RldmljZVJHQj4"

It is supposed to be a pdf file, i tried this library pdfbox from apache, but it writes the content as a text inside the pdf. I've tried with ByteArrayInputStream but the pdf created is not valid, corrupted, this is some of the code i've wrote.

public void escribePdf(String texto, String rutaSalida) throws IOException{

    byte[] biteToRead = texto.getBytes();
    InputStream is = new ByteArrayInputStream(biteToRead );
    DataOutputStream out = new DataOutputStream(new  BufferedOutputStream(new FileOutputStream(new File(rutaSalida))));
    int c;
    while((c = is.read()) != -1) {
        out.writeByte(c);
    }
    out.close();
    is.close();

}

解决方案

That is Base64 encoded (most probably UTF-8) data, you must decode it before using; such as:

import sun.misc.BASE64Decoder;

...

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

....

Edit: For java >= 1.8, use:

byte[] decodedBytes = java.util.Base64.getDecoder().decode(biteToRead);

这篇关于从Java中的二进制数据创建pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆