突破点是base64编码的数据通过流可以直接写入pdf文件。
下面的方法主要用到的apache提供的Base64 API.
需要在项目中导入commons-codec.jar.
思路:
1.获取到数据库中的blob数据,获得Blob对象
ResultSet rs = preparedStatement.executeQuery();
Blob blob = rs.getBlob(String columnName);
2.通过Blob对象的getBinaryStream()方法获取到输入流,可以进行数据的读取,然后写出数据到ByteArrayOutputStream流
ByteArrayOutputStream baos = null;
BufferedOutputStream bout = null;
try {
baos = new ByteArrayOutputStream();
bout = new BufferedOutputStream(baos);
byte[] buffer = new byte[1024];
int len = is.read(buffer);
while (len != -1) {
bout.write(buffer, 0, len);
len = is.read(buffer);
}
bout.flush();
//将数据转为字节数组
byte[] bytes = baos.toByteArray();
//使用Base64进行编码
String result = Base64.encodeBase64String(bytes).trim();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
bout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
3.使用Base64进行解码
byte[] bytes = Base64.decodeBase64(base64String);
4.最后可以通过输入流将上面进行解码的字节数组读出并写入到文件中,至此就可以生成pdf了