Хорошо, мне удалось заставить его работать. Я использовал часть кода @hrdkisback, в дополнение к изменениям в методе создания отчета. Вот полный код, если кто-то сталкивается с подобной проблемой.
Контроллер:
@RequestMapping(value = "/daily-orders/{restaurantId}/export", method = RequestMethod.POST)
public void exportDailyOrders(@PathVariable Long restaurantId, HttpServletResponse httpServletResponse) throws IOException, JRException {
byte[] dailyOrdersBytes = exportService.exportDailyOrders(restaurantId);
ByteArrayOutputStream out = new ByteArrayOutputStream(dailyOrdersBytes.length);
out.write(dailyOrdersBytes, 0, dailyOrdersBytes.length);
httpServletResponse.setContentType("application/pdf");
httpServletResponse.addHeader("Content-Disposition", "inline; filename=dailyOrdersReport.pdf");
OutputStream os;
try {
os = httpServletResponse.getOutputStream();
out.writeTo(os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Служба:
@Override
public byte[] exportDailyOrders(Long restaurantId) throws IOException, JRException {
List<RestaurantDailyOrdersRowMapper> restaurantDailyOrders = orderDAO.getRestaurantDailyOrders(restaurantId);
File file = ResourceUtils.getFile("classpath:reports/daily-orders.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(file.getAbsolutePath());
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(restaurantDailyOrders);
Map<String, Object> parameters = new HashMap<>();
parameters.put("createdBy", "Nikola");
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
ByteArrayOutputStream byteArrayOutputStream = getByteArrayOutputStream(jasperPrint);
return byteArrayOutputStream.toByteArray();
}
protected ByteArrayOutputStream getByteArrayOutputStream(JasperPrint jasperPrint) throws JRException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, byteArrayOutputStream);
return byteArrayOutputStream;
}
component.ts
exportDailyOrdersToPdf() {
this.exportService.generateDocumentReport(1).subscribe(response => {
console.log(response);
let url = window.URL.createObjectURL(response.data);
let a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.setAttribute('target', 'blank');
a.href = url;
a.download = response.filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}, error => {
console.log(error);
});}
service.ts
generateDocumentReport(restaurantId: number): Observable<any> {
let headers = new HttpHeaders();
headers.append('Accept', 'application/pdf');
let requestOptions: any = { headers: headers, responseType: 'blob' };
return this.httpClient.post('https://localhost:8080/main/daily-orders/' + restaurantId + '/export', '', requestOptions)
.pipe(map((response)=>{
return {
filename: 'dailyOrdersReport.pdf',
data: new Blob([response], {type: 'application/pdf'})
};
}));}