对于大家想知道人类的方式来做到这一点,这里是我的工作流程:
1 - 生成PDF文件,抢个字节,并将其转换为base64字符串后。
我可以很容易地做到这一点与使用Python pyfpdf lib和使用Django作为后端:
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')
}
)
记住这个例子可以用其他后端做/库!
2 - 在您的Android项目上设置一个字符串您希望用于接收PDF回复/回叫的模型字段。所以我们的PDF将会像这样到达。
{
"name" : "my_doc.pdf",
"content64" : "aGVsbG8gd29ybGQ="
}
所以在Java中,我们可以设置自定义POJO
class PDF{
private String name;
private String content64;
// (...)
}
3 - 基于64位将是一个简单的字符串!要获得真正的文件作为字节只写这样
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() {
@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);