The code works and generates the pdf, but only the static html part and not the javascript generated chart:
<!-- report.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
</head>
<p>this is chart</p>
<body>
<div style="width: 800px; height: 400px;">
<canvas id="barChart"></canvas>
</div>
<script type="text/javascript" src="/static/js/ChartInitialization.js"></script>
</body>
</html>
Here is the script, which is working fine with the HTML when opened in the browser and it generates the chart correctly:
var barData = [10, 20, 30, 40, 50];
var barChart = new Chart(document.getElementById('barChart').getContext('2d'), {
type: 'bar',
data: {
labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5'],
datasets: [{
label: 'Bar Chart',
data: barData,
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}]
},
});
Here is the controller code:
package com.example.chartjs.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
@Controller
@RequestMapping("/pdf")
public class PDFController {
@Autowired
private TemplateEngine templateEngine;
@GetMapping("/generate")
public void generatePDF(HttpServletResponse response) {
Context context = new Context();
String htmlContent = templateEngine.process("report", context);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(htmlContent);
renderer.layout();
renderer.createPDF(os, false);
renderer.finishPDF();
} catch (Exception e) {
e.printStackTrace();
}
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=report.pdf");
try (OutputStream out = response.getOutputStream()) {
os.writeTo(out);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I’m not sure if the javascript code is executing after the generation of the pdf, or is there some other issue.