How to send information from my java sling model to a servlet that is called by the frontend? | Community
Skip to main content
Level 4
May 28, 2024

How to send information from my java sling model to a servlet that is called by the frontend?

  • May 28, 2024
  • 3 replies
  • 3586 views

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:

 $("#download-pdf").on("click", function () {

    fetch('/bin/pdfgenerator', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/pdf'
      }
    })
      .then(response => {
        if (response.ok) {
          return response.blob();
        } else {
          throw new Error('Error on PDF');
        }
      })
      .then(blob => {
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = 'example.pdf';
        link.click();
      })
      .catch(error => {
        alert("error");
        console.error('Error:', error);
      });
  });


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());
}
}
}

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.

3 replies

EstebanBustamante
Community Advisor and Adobe Champion
Community Advisor and Adobe Champion
May 28, 2024

Hi,

 

I'm sorry, but I don't understand your question correctly. Here are some general guidelines you should keep in mind:

  1. You should extract your PDF logic into an OSGi service so you can use your methods either in the Sling Model or the servlet.

  2. The data which is available in the Sling Model can be retrieved in the Sling servlet as long as you know the path of the resource.

  3. With the above clarification, you should not have a scenario where you really would need to pass data from a Sling Model to a servlet.

Hope this helps

 

Esteban Bustamante
Level 4
May 28, 2024

Ok, I will summarize the problem, we have the following files:

1) PDFServlet.java: a servlet that generates a pdf and then sends it to the frontend to download the generated pdf, the information that the PDF have are hardcoded values.

2) Frontend-functions.js: A javascript file that is used in the frontend of a template (page) that what it does is to call the pdf servlet when a button of the page is clicked, to download the pdf that was generated in the same servlet.

3) productModel.java: A java sling model with getters and its respective information.

The way it works now is only with point 1 and point 2, that is to say, the frontend calls the servlet and the servlet delivers something to the frontend.

Now what I want to do is to use point 1, point 2 and point 3 together, the pdf that the servlet generates I want to have and use the information of the java sling model values (example title, description, images, etc) instead of the hardcoded values that are on the PDFServlet

EstebanBustamante
Community Advisor and Adobe Champion
Community Advisor and Adobe Champion
May 28, 2024

Ok, got it.

 

So, you have two options here:

  1. As I said, you don't have to pass the values from the Sling Model to the servlet. The Sling Model gets the values by adapting a resource, and you have access to the same resource from your servlet. So, you could simply get the resource and adapt it to the model, or read the properties from the resource and then use them in your servlet as usual. Check this as reference: https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/get-component-resource-in-a-servlet/td-p/387895 
  2. Another approach is to simply get those values from the Sling Model into the HTML, and then, via JavaScript, you can retrieve those values from the HTML and pass them to the servlet.
//HTL <sly data-sly-use.model="com.your.Model"></sly> <div id="myDiv" data-title=${model.title @ context='html'} data-title=${model.desc @ context='html'} > //JS var allData = $('#div').data(); $("#download-pdf").on("click", function () { fetch('/bin/pdfgenerator', { method: 'GET', data: allData headers: { 'Content-Type': 'application/pdf' } })

Hope this helps.

Esteban Bustamante
Umesh_Thakur
Community Advisor
Community Advisor
May 29, 2024

from Javascript or jquery--->AEM Servlet-->Slingmodel. this will be the call hierarchy.

you will create an object of sling model in the servlet then will get the data from sling model see the point 3 in below blogpost https://aemhelper.blogspot.com/2021/08/common-myths-around-sling-model.html  to have a sling model object in servlet, servlet will generate the PDF with the data then will respond to the fron-end call with generated PDF.

Hope this helps

Umesh Thakur

kautuk_sahni
Community Manager
Community Manager
June 4, 2024

@aaron_dempwolff Did you find the suggestions from users helpful? Please let us know if you require more information. Otherwise, please mark the answer as correct for posterity. If you have found out solution yourself, please share it with the community.

Kautuk Sahni