Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

PDF View and Download Issue

Avatar

Level 6

Hello Team,

 

Since AEM (6.5 in my case) by default downloads DAM PDFs.

 

We added below lines and we can view PDFs upon clicking.

 

<LocationMatch "\.(?i:pdf)$">
ForceType application/pdf
Header set Content-Disposition inline
</LocationMatch>

 

PROBLEM:

We also have to give way to download as an option. so for that, created Servlet (Code Below) and set Content-Disposition as "attachment". When we try to access PDF using "docdown" selector directly from Publish Machine, It downloads.

where as from Dispatcher URL, It always show "inline" and It does not download, always open in view mode.

 

Code Below:

 

@SlingServletResourceTypes(resourceTypes = "dam:Asset", methods = HttpConstants.METHOD_GET, selectors = "docdown", extensions = "pdf")
@ServiceDescription("Download PDF Servlet")
public class DownloadPDFServlet extends SlingSafeMethodsServlet {

protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) {
try {
final String pdfPath = request.getRequestPathInfo().getResourcePath();
if (StringUtils.isEmpty(pdfPath)) {
return;
}
Resource pdfRes = request.getResourceResolver().getResource(pdfPath);
streamPDF(response, pdfRes);
} catch (final IOException e) {
LOG.error("Could not get response", e);
response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
 
private void streamPDF(final SlingHttpServletResponse response, final Resource pdfRes) throws IOException {
String fileName = pdfRes.getPath().substring(pdfRes.getPath().lastIndexOf("/") + 1);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
Asset asset = pdfRes.adaptTo(Asset.class);
final InputStream in = asset.getOriginal().getStream();
final OutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
out.close();
in.close();
}

 

 

 

 

1 Accepted Solution

Avatar

Correct answer by
Level 6

We fixed using below:

 


<LocationMatch "^((?!docdown).)*\.pdf$">
ForceType application/pdf
Header set Content-Disposition inline
</LocationMatch>

View solution in original post

2 Replies

Avatar

Correct answer by
Level 6

We fixed using below:

 


<LocationMatch "^((?!docdown).)*\.pdf$">
ForceType application/pdf
Header set Content-Disposition inline
</LocationMatch>

Avatar

Administrator

@arvind Tthank you for sharing the solution with the AEM community. This would help the community in posterity. 



Kautuk Sahni