package DigiLibPdf;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class DigiLibPdfCreator extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public DigiLibPdfCreator(){
super();
System.out.println("Initialized " + this.getClass().getName());
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws javax.servlet.ServletException, java.io.IOException {
ByteArrayOutputStream pdfOutStream = null;
try {
// get the PDF-data
pdfOutStream = PdfDocumentFromUrl(request, this.getServletContext());
// generate filename
String filename = "image_download.pdf";
// set HTTP headers
response.setHeader("Cache-Control","max-age=30");
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline; filename="+filename);
response.setContentLength(pdfOutStream.size());
// write pdf to output stream
ServletOutputStream out = response.getOutputStream();
pdfOutStream.writeTo(out);
out.flush();
}
catch (DocumentException de){
// inform the user about what went wrong
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println(this.getClass().getName() + " caught an exception: "
+ de.getClass().getName() + "
");
de.printStackTrace(writer);
writer.println("");
}
finally {
if (pdfOutStream != null){
pdfOutStream.reset();
}
}
}
protected ByteArrayOutputStream PdfDocumentFromUrl(HttpServletRequest request, ServletContext servletcontext)
throws DocumentException {
Document doc = new Document();
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
PdfWriter docwriter = null;
try{
docwriter = PdfWriter.getInstance(doc, outstream);
doc.addAuthor(this.getClass().getName());
doc.addCreationDate();
doc.addKeywords("digilib");
doc.addTitle("digilib Image Printer");
doc.addCreator(this.getClass().getName());
// get width and height from the request
int docW = 1, docH=1;
doc.setPageSize(new Rectangle(0,0,docW,docH));
// download the image from the URL
Image img = Image.getInstance(new URL(request.getParameter("url")));
img.scaleToFit(docW,docH);
doc.add( img ); //
doc.open();
// add all the images
}
catch (DocumentException de) {
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (doc!=null){
doc.close();
}
if (docwriter!=null){
docwriter.close();
}
}
return outstream;
}
}