Je veux de l'aide pour afficher le rapport Jasper de l'application Spring Boot dans l'application angulaire pense ceci est mon code générant jasper pdf
@GetMapping(value = "/print/{id}")
public void report(HttpServletResponse response, @PathVariable("id") Integer id) throws Exception {
final String invoice_template = "/jasper/invoice_template.jrxml";
Invoice invoice = invoiceRepo.getOne(id);
File pdfFile = File.createTempFile("invoice", ".pdf");
final Map<String, Object> parameters = new HashMap<>();
parameters.put("invoice", invoice);
try (FileOutputStream pos = new FileOutputStream(pdfFile)) {
final JasperReport report = jrxmlTemplateLoader.loadTemplate(invoice_template);
final JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(
Collections.singletonList("Invoice"));
JasperReportsUtils.renderAsPdf(report, parameters, dataSource, pos);
}
try (FileOutputStream pos = new FileOutputStream(pdfFile)) {
final JasperReport report = jrxmlTemplateLoader.loadTemplate(invoice_template);
final JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(
Collections.singletonList("Invoice"));
JasperReportsUtils.renderAsPdf(report, parameters, dataSource, pos);
} catch (final Exception e) {
log.error(String.format("An error occured during PDF creation: %s", e));
}
}
3 Réponses :
Vous pouvez répondre avec le fichier PDF ou quelque chose comme
JasperPrint print = JasperFillManager.fillReport(report, new HashMap<String, String>());
String attachment = "attachment; filename=\"filename.pdf\"";
response.setHeader("Content-Disposition", attachment);
JasperExportManager.exportReportToPdfStream(print, response.getOutputStream());
Cela devrait vous aider à démarrer. Vous devez être plus précis pour obtenir une meilleure aide
Cette question a une implémentation que vous pouvez utiliser JasperReport avec OutputStream n'exportant pas en PDF
pense que Hitham S. AlQadheeb a résolu mon problème avec le code ci-dessous
printInvoice(invoice: Invoice) {
this.invoiceService.printInvoice(invoice.id).subscribe((response) => {
const file = new Blob([response], { type: 'application/pdf' });
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
}
service
printInvoice(id): any {
const httpOptions = {
responseType: 'arraybuffer' as 'json'
// 'responseType' : 'blob' as 'json' //This also worked
};
return this.http.get<any>(this.baseUrl + '/print/' + id, httpOptions);
}
ts composant
@GetMapping(value = "/print/{id}")
public @ResponseBody byte[] report(HttpServletResponse response, @PathVariable("id") Integer id) throws Exception {
final String logo_path = "/jasper/images/stackextend-logo.png";
final String invoice_template = "/jasper/invoice_template.jrxml";
Invoice invoice = invoiceRepo.getOne(id);
File pdfFile = File.createTempFile("invoice", ".pdf");
log.info(String.format("Invoice pdf path : %s", pdfFile.getAbsolutePath()));
final Map<String, Object> parameters = new HashMap<>();
parameters.put("logo", getClass().getResourceAsStream(logo_path));
parameters.put("invoice", invoice);
try (FileOutputStream pos = new FileOutputStream(pdfFile)) {
// Load invoice jrxml template.
final JasperReport report = jrxmlTemplateLoader.loadTemplate(invoice_template);
// Create parameters map.
// final Map<String, Object> parameters = parameters(invoice);
// Create an empty datasource.
final JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(
Collections.singletonList("Invoice"));
// Render as PDF.
JasperReportsUtils.renderAsPdf(report, parameters, dataSource, pos);
} catch (final Exception e) {
log.error(String.format("An error occured during PDF creation: %s", e));
}
byte[] bytes = Files.readAllBytes(Paths.get(pdfFile.getAbsolutePath()));
return bytes;
}
Bonjour à tous, maintenant mon code fonctionne bien sur le serveur local du nœud, mais lorsque je déploie mon application sur le serveur tomcat, j'obtiens l'erreur ci-dessous dans l'erreur de console: Taille du blob: 231 type: "application / json" proto : en-têtes de blob : n {normalizedNames: Map (0), lazyUpdate: null, lazyInit: ƒ} message: "Réponse d'échec Http pour localhost: 8083 / stockservice / api / factures / print / 5 : 400 OK "nom:" HttpErrorResponse "
J'éviterais byte [] (dans l'allocation de mémoire); Je retournerais InputStream
désactiver adblocker si vous voulez vraiment utiliser blob ;-) c'est ce que j'ai fait face
##SpringBootController## its work cool :)
@GetMapping(value = "/ackPending/pdf/{deptId}")
public void missoutInward(@PathVariable("deptId") String dept, ModelAndView model, HttpServletResponse response)
throws IOException {
logger.info("MISSOUT INWARD PDF REPORT :");
final InputStream stream = this.getClass().getResourceAsStream("/missoutInward.jrxml");
try {
final JasperReport report = JasperCompileManager.compileReport(stream);
final JRBeanCollectionDataSource source = new JRBeanCollectionDataSource(
inwardService.findPendingAckInward(dept, 1));
final Map<String, Object> parameters = new HashMap<>();
parameters.put("createdBy", "Admin");
final JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, source);
response.setContentType("application/x-pdf");
response.setHeader("Content-disposition", "inline; filename=App_report_en.pdf");
final OutputStream outStream = response.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, outStream);
/*
* final String filePath = "\\"; logger.info("File saved At :" + filePath);
* JasperExportManager.exportReportToPdfFile(print, filePath + "users.pdf");
*/
} catch (JRException e) {
e.printStackTrace();
}
}
---------------------------------------------------------------------------------------
##ANgular 9#####
service.ts##
findPendingInwardsPdf(deptId: string) {
const httpOptions = {
responseType: 'arraybuffer' as 'json'
// 'responseType' : 'blob' as 'json' //This also worked
};
return this.httpClient.get<Inward[]>(URLS.INWARDS + "ackPending/pdf/" + deptId, httpOptions);
}
------------------
component.ts
search(missout: Missout): void {
this.inwards = null;
this.outwards = null;
if (missout.type == 'Inward') {
let dept = missout.dept;
this.inwardService.findPendingInwardsPdf(dept).subscribe((response) => {
const file = new Blob([response as unknown as BlobPart], { type: 'application/pdf' });
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
})
} else {
this.outwardService.getPendingAck().subscribe(data => {
this.outwards = data;
})
}
}