問題1: JasperReport打印出來的整個pdf文件為空白文件;
問題2:JasperReport定義變量后打印PDF變量為null;
問題1原因是因?yàn)槿鄙贁?shù)據(jù)源JRDataSource
JasperFillManager.fillReport(jasperReport, params,new JREmptyDataSource());
如果你打印的jrxml文件單純是一些文本,沒有數(shù)據(jù),那么你需要在fillReport
函數(shù)傳入一個空的數(shù)據(jù)源,如果沒有數(shù)據(jù)源生成的PDF就是空白的,如下圖:
問題2原因是把field 和 parameter 搞混了,如果只是參數(shù),那么你就定義成parameter,如果是數(shù)據(jù)信息就定義成字段即可;
小提示:如果你需要將數(shù)據(jù)進(jìn)行打印出來,那么定義成field,此時你的數(shù)據(jù)就是數(shù)據(jù)源:JRDataSource datasource = new JRBeanCollectionDataSource(dataList);
文章來源:http://www.zghlxwxcb.cn/news/detail-690887.html
最后附上相關(guān)源碼:文章來源地址http://www.zghlxwxcb.cn/news/detail-690887.html
//主函數(shù)
public static void main(String[] args){
String str = "/Documents/work/ccount_4.jrxml"; //jrxml文件地址
Map<String, Object> params = new HashMap<>();
params.put("tenantName","ccccccc"); //封裝變量tenantName
pdfByJrxml(str,params); //PDF文件生成邏輯
}
//Jasper生產(chǎn)PDF文件
public static String pdfByJrxml(String jrxmlPath, Map<String, Object> params) {
try {
InputStream resourceAsStream = new FileInputStream(jrxmlPath);
JasperDesign jasperDesign = JRXmlLoader.load(resourceAsStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
//fillReport 重點(diǎn)是這個方法,如果沒有數(shù)據(jù),那么需要制定空的數(shù)據(jù)源,否則生成的PDF是空白的
JasperPrint jasperPrint =
JasperFillManager.fillReport(jasperReport, params,new JREmptyDataSource());
byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
testWriteLocalFile(bytes); //將PDF文件輸出到本地
} catch (Exception e) {
logger.error("generate pdf error{}", e);
}
}
//本地生成PDF文件
public static void testWriteLocalFile(byte[] bytes){
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file;
String filePath = "/xxx/Documents/work/";
try {
File dir = new File(filePath);
if(!dir.exists()&&dir.isDirectory()){//判斷文件目錄是否存在
dir.mkdirs();
}
file = new File(filePath+"d.pdf");
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}```
到了這里,關(guān)于JasperReport定義變量后打印PDF變量為null以及整個pdf文件為空白的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!