How to send information from my java sling model to a servlet that is called by the frontend?
Hi all, what happens is that I have a servlet, what it does is to generate a PDF using html and css, then that pdf is sent to the frontend to download it.
But what I need to do now is to send information from the java sling model of the template to the servlet, to generate a PDF with the information that is inside the template.
How can I do that, the only solutions that I have found are only for the servlet that are sent to call from the java sling model, but my servlet is sent to call from the frontend, this is the code that I use:
Frontend Call:
Servlet PDF:
package com.project.core.servlets;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itextpdf.html2pdf.HtmlConverter;
@WebServlet("/PDFServlet")
public class PDFServlet extends HttpServlet {
@9944223
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// HTML content to be converted to PDF
String htmlContent = "<html><head><style>.my-class { color: red; }</style></head><body><div class=\"my-class\">Hello, World!</div></body></html>";
// Generate PDF from HTML content
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
HtmlConverter.convertToPdf(htmlContent, outputStream);
// Set content type and headers
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"output.pdf\"");
// Write PDF to response output stream
response.getOutputStream().write(outputStream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
response.getWriter().println("Error generating PDF: " + e.getMessage());
}
}
}


