A Java servlet for opening PDF files

We will see how to open or save a file with Java

Let’s write our class right away, we’ll call it OpenPdf

public class ApriPdf extends HttpServlet{

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


		OutputStream out = null;

		File file = new File(filePath);


		if(file.exists()){
			out = response.getOutputStream();
			response.setContentType("application/pdf;charset=UTF-8");
			response.setHeader("Content-Disposition","inline;filename=Nome_del_file.pdf");
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] buf = new byte[4096];
			
			try {
				for (int readNum; (readNum = fis.read(buf)) != -1;) {
					bos.write(buf, 0, readNum);
				}
			} catch (IOException ex) { 
				log.debug(ex.getMessage());
				ex.printStackTrace();
			}
			
			byte[] bytes = bos.toByteArray();
			int lengthRead = 0;
			InputStream is = new ByteArrayInputStream(bytes);
			
			while ((lengthRead = is.read(buf)) > 0) {
				out.write(buf);
			}
			
			fis.close();
			bos.close();
			is.close();
			out.close();
		}
	}
}

Through the header we can decide whether to download our PDF file (attachment), or to view it in the browser window (inline).

At this point we are missing the servlet configuration in the web.xml file

<servlet>
    <servlet-name>ApriPdf</servlet-name>
    <servlet-class>posizione.logica.della.classe.ApriPdf</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>ApriPdf</servlet-name>
    <url-pattern>ApriPdf</url-pattern>
</servlet-mapping>

That’s enough. We just need to call our servlet from the physical address that we created http://host/OpenPdf from the browser to view or download the file.

We periodically check the functioning of the links in our articles. If you notice any links that do not work, please let us know in the comments. If you enjoyed the article consider supporting the blog with a small donation. Thank you. Patreon / Ko-fi / Liberapay / Paypal

Leave a Reply

Your email address will not be published. Required fields are marked *