android原生对于pdf的支持很少,只支持将控件生成图片写入,对于直接写入文字内容支持不好,所以就用了开源库IText,jar包可以直接去官网下载。下载后导入项目即可。
/**param contemt 需要写入的内容,param reportAddree 生成的pdf保存的路径**/
public static void generatePdfReport(String content, String reportAddress) {
Document document = new Document();
new Thread(new Runnable() {
@Override
public void run() {
try {
FileOutputStream outputStream;
outputStream = new FileOutputStream(reportAddress);
PdfWriter.getInstance(document, outputStream);
document.open();
document.setPageCount(1);
document.add(new Paragraph(content, setChineseFont()));
document.close();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private static Font setChineseFont() {
BaseFont bf = null;
Font fontChinese = null;
try {
// STSong-Light : Adobe的字体
// UniGB-UCS2-H : pdf 字体
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
fontChinese = new Font(bf, 12, Font.NORMAL);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fontChinese;
}