通过改造从服务器接收PDF响应

时间:2015-04-06 13:50:16

标签: android http pdf retrofit

我有一个生成PDF文档的视图。它在浏览器(桌面)上运行良好,但我的最终目标是通过Android应用程序提供它。

现在我正在使用改造库来处理我的请求/响应(仅限json)。

我的问题是我需要传递Callback<>来处理/接收PDF数据然后将其保存到磁盘的数据类型?

1 个答案:

答案 0 :(得分:2)

对于每个想知道以这种方式做到这一点的人都是我的工作流程:

1 - 生成PDF文件后,抓取字节并将其转换为base64字符串。

我可以使用pyfpdf lib并使用Django作为后端使用python轻松实现这一点:

import base64

def my_view(request):
    pdf = MyCustomPDF()
    pdf.add_page()
    pdf.set_margins(12,3,3)
    pdf.render() # PDF is ready to be saved
    b = pdf.output('output.pdf','B') # got the PDF as a byte array
    return JsonResponse(
        {  
            "name" : "my_doc.pdf",
            "content64" : base64.b64encode(b).decode('utf8')
        }
    )

记住这个例子可以用其他后端/ libs来完成!

2 - 在Android项目上,在要用于接收PDF响应/回调的模型上设置字符串字段。所以我们的PDF会像这样到达。

{  
    "name" : "my_doc.pdf",
    "content64" : "aGVsbG8gd29ybGQ="
}

所以在Java上我们可以设置自定义POJO

class PDF{
    private String name;
    private String content64;

    // (...)
}

3 - base64将是一个简单的字符串!要将真实文件作为字节获取,只需编写一个这样的例程

class PDF{
    private String name;
    private String content64;

    // (...)

    public byte[] content64AsByteArray(){ // Helps you convert string to byte formats :B
        return Base64.decode(content64,Base64.DEFAULT);
    }

    public String save(String path) {

        try {

            String path = Environment.getExternalStorageDirectory() + "/" + path;

            File f1 = new File(path);

            OutputStream out = null;
            out = new FileOutputStream(path + "/" + this.name);
            out.write(this.content64AsByteArray());
            out.close();


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return this.path; // I like to return it because i can use it to start a "open file" intent
    }
}

4 - 通过改造

接收回调就像这样
pdfCallback = new Callback<PDF>() {

    @Override public void success(PDF pdf, Response response) {

        if (response.getStatus() == 200) {

            String pathToPDF = pdf.save() // save PDF

        }

    }

    @Override public void failure(RetrofitError error) {
        (...)
    }
}

MyAPI.callbacks.getPDF( (...), pdfCallback);