Disclaimer
Without knowing your specific requirements I would recommend using a servlet instead of using a Sling Model. A Sling Model is meant to be a representation of a JCR resource in the repository not be abused as servlet.
A Sling Model has a different "life cycle" than a servlet. While a servlet is instantiated as a OSGi service/component (which is a singleton in most cases) a Sling Model can be instantiated multiple times during a single request. So be aware of that difference and the consequences.
That said, you have two options to write the PDF to the response with a Sling Model:
- During the initialisation of the Sling Model
- When a specific method is called
Example for 1:
@Model(adaptables = SlingHttpServletRequest.class)
public class MyModel {
@SlingObject
private SlingHttpServletResponse response;
@OSGiService
private PDFService pdfService;
@PostConstruct
public void init() {
response.setContentType("application/pdf");
[... code to write PDF to response ...]
}
}
The method annotated with @PostConstruct
is called after all annotated fields are injected, so that you can run your initialisation code.
Example for 2:
@Model(adaptables = SlingHttpServletRequest.class)
public class MyModel {
@SlingObject
private SlingHttpServletResponse response;
@OSGiService
private PDFService pdfService;
public void writePDFtoResponse() {
response.setContentType("application/pdf");
[... code to write PDF to response ...]
}
}
Obviously, with the second example you would have to have some kind of code that instantiates the model and calls writePDFtoResponse()
.
response
? Depending one the requirement you could do it with a Sling Model, but usually something like this is done by a Servlet. Can you please explain what the requirement is and why you think a Model would be better than a Servlet? – Jens