Writing a Servlet to View a Document in a Web Browser
This Tech Tip appeared in Imaging News April 2005.
This tech tip demonstrates how to write a simple servlet that allows any document supported by the RasterMaster imaging SDK library to be viewed in a standard Web browser. The documents are converted in real time to PNG images.
The following is an example of the URL format used to view images:
http://yourserver/docviewer/Document2PNG?filename=mydoc.pdf&page=2
/**
* Copyright (C) 2005 by Snowbound Software Corp. All rights reserved.
*/
package com.snowbound.techtip;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Snow.Snowbnd;
public class Document2PNGServlet extends HttpServlet
{
private final static int PNG_FORMAT = 43;
private final static String IMAGE_DIRECTORY = "c:/images/";
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
ServletConfig config = getServletConfig();
ServletContext application = config.getServletContext();
Snowbnd snow = new Snowbnd();
// get the page number to convert from the page parameter
int pageIndex = Integer.parseInt(request.getParameter("page"));
// get the filename to convert from the filename parameter
String filename = IMAGE_DIRECTORY + request.getParameter("filename");
// create a temporary byte array that is at least as big as the expected output size
byte[] tmpOutputBytes = new byte[15000000];
// decompress the specified page
snow.IMG_decompress_bitmap(filename, pageIndex);
// write out the page to a byte array in PNG format
int outputSize = snow.IMG_save_bitmap(tmpOutputBytes, PNG_FORMAT);
// copy only the data portion to our output array
byte[] outputBytes = new byte[outputSize];
System.arraycopy(tmpOutputBytes, 0, outputBytes, 0, outputSize);
// set the content type of the image data to be sent to the browser
response.setContentType(application.getMimeType(".png"));
response.setContentLength(outputSize);
// send the bytes to the response object
sendBytes(outputBytes, response);
}
/**
* This method will send the contents of the byte array
* to the servlet response output stream.
*
* @param bytes the output byte array
* @param response the HttpServletResponse object to write to
* @throws IOException
*/
protected void sendBytes(byte[] bytes, HttpServletResponse response)
throws IOException
{
ServletOutputStream servletoutputstream = response.getOutputStream();
servletoutputstream.write(bytes);
servletoutputstream.flush();
}
}
Learn More
In addition to our Tech Tips section, our document and image Solutions Section provides business application and industry-specific examples including image conversion and web viewing.

