JasperReport使用JavaBean作为数据源生成PDF
JasperReport - 数据源( Data Sources)
数据源是结构化数据容器。 在生成PDF时,JasperReports引擎从数据源获取数据。 可以从数据库,XML文件,对象数组和对象集合中获取数据。 fillReportXXX()方法希望以net.sf.jasperreports.engine.JRDataSource对象或java.sql.Connection的形式接收数据源。
1.新建Bean
在使用TIBCO Jaspersoft studio或iReport创建jrxml文件之前,首先创建作为数据源的Bean。
首先创建GirlFriend对象,对象有三个属性:name(String),cupSize(String),photoUrl(String)。
// girlFriend
@Data
@AllArgsConstructor
public class GirlFriend {
private String cupSize;
private String photoUrl;
}
2.新建BeanFactory
public class GirlFriendFactory {
public List<GirlFriend> getMyGirfriends() {
List<GirlFriend> girlFriends = new ArrayList<>();
GirlFriend girlFriend1 = new GirlFriend("A","");
GirlFriend girlFriend2 = new GirlFriend("B","");
GirlFriend girlFriend3 = new GirlFriend("C","");
GirlFriend girlFriend4 = new GirlFriend("D","");
girlFriends.add(girlFriend1);
girlFriends.add(girlFriend2);
girlFriends.add(girlFriend3);
girlFriends.add(girlFriend4);
return girlFriends;
}
}
3.创建jrxml文件
首先在Field中创建属性,属性类型与GirlFriend对象的属性名称,类型相同
拖拽组件绘出PDF样式,作为演示,这里简单创建一个PDF
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.14.0.final using JasperReports Library version 6.14.0-2ab0d8625be255bf609c78e1181801213e51db8f -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="testPic" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="0441d0fa-e499-4d53-aa9d-841901e07ec5">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
<queryString>
<![CDATA[]]>
</queryString>
<field name="photoUrl" class="java.lang.String"/>
<field name="cupSize" class="java.lang.String"/>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="79" splitType="Stretch"/>
</title>
<detail>
<band height="90" splitType="Stretch">
<image>
<reportElement x="350" y="20" width="40" height="40" uuid="5a166a5d-6e29-4437-a9b1-d1b469fbbf65">
<property name="com.jaspersoft.studio.unit.width" value="px"/>
<property name="com.jaspersoft.studio.unit.height" value="pixel"/>
<property name="com.jaspersoft.studio.unit.x" value="px"/>
<property name="com.jaspersoft.studio.unit.y" value="px"/>
</reportElement>
<imageExpression><![CDATA[$F{photoUrl}]]></imageExpression>
</image>
<staticText>
<reportElement x="-50" y="36" width="100" height="30" uuid="9cc4940f-4eff-497a-aead-df4259ddfc77"/>
<text><![CDATA[name]]></text>
</staticText>
<textField>
<reportElement x="130" y="30" width="100" height="30" uuid="0f5f8705-a7bc-4a62-a13c-47184f81069c"/>
<textFieldExpression><![CDATA[$F{cupSize}]]></textFieldExpression>
</textField>
</band>
</detail>
<pageFooter>
<band height="54" splitType="Stretch"/>
</pageFooter>
</jasperReport>
4.生成PDF
在项目resources目录下创建jasperReportTemplates文件夹,将创建好的jrxml文件放到jasperReportTemplates目录下。
传入数据源,生成PDF
@Service
public class GirlFriendService {
private final static String PDFPATH = "jasperReportTemplates\\testPic.jrxml";
public byte[] chooseGirlFriend() {
GirlFriendFactory girlFriendFactory = new GirlFriendFactory();
List<GirlFriend> girlFriends = girlFriendFactory.getMyGirfriends();
byte[] pdf = generateJasperReportPDF(PDFPATH, Maps.newHashMap(),
girlFriends);
return pdf;
}
}
public class JasperReportUtils {
private static Map<String, JasperReport> templateCache = new ConcurrentHashMap<>();
public static byte[] generateJasperReportPDF(String templatePath,
Map<String, Object> params,
Collection dataSource) {
log.info("generate pdf, params: {}, data source: {}", params, dataSource);
try (
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()
) {
final JasperReport jasperReport = compileReport(templatePath);
JasperPrint jasperPrint =
JasperFillManager.fillReport(jasperReport,
params,
CollectionUtils.isEmpty(dataSource) ? new JREmptyDataSource()
: new JRBeanCollectionDataSource(dataSource));
final JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
configuration.setPermissions(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING);
exporter.setConfiguration(configuration);
exporter.exportReport();
return outputStream.toByteArray();
} catch (Exception e) {
throw new JasperException("generate pdf error:", e);
}
}
public static JasperReport compileReport(String templatePath) {
templateCache.clear();
JasperReport jasperReport = templateCache.get(templatePath);
if (jasperReport == null) {
try (InputStream inputStream = getResourceAsStream(templatePath)) {
jasperReport = JasperCompileManager.compileReport(inputStream);
templateCache.put(templatePath, jasperReport);
} catch (IOException | JRException e) {
throw new RuntimeException("compile report error", e);
}
}
return jasperReport;
}
private static InputStream getResourceAsStream(String path) {
return JasperReportUtils.class.getClassLoader().getResourceAsStream(path);
}
}
5.创建Controller
@RestController
@RequestMapping("/girlFriend")
public class GirlFriendController {
@Autowired
private GirlFriendService girlFriendService;
@GetMapping
public ResponseEntity<byte[]> chooseGirlfriend() {
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_PDF)
.body(girlFriendService.chooseGirlFriend());
}
}
6.运行结果
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。