KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > HelloServletWorld


1 import java.util.*;
2 import java.io.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import java.awt.Color JavaDoc;
6 import org.faceless.pdf2.*;
7
8 // A Hello World servlet. This is *identical* to HelloWorld.java, except
9
// for the method names and the last 3 lines.
10
//
11
public class HelloServletWorld extends HttpServlet
12 {
13     public void doPost(HttpServletRequest req, HttpServletResponse res)
14         throws ServletException, IOException
15     {
16         doGet(req,res);
17     }
18
19     public void doGet(HttpServletRequest req, HttpServletResponse res)
20         throws ServletException, IOException
21     {
22     // Create a new PDF
23
PDF pdf = new PDF();
24
25     // Create a new page
26
//
27
PDFPage page = pdf.newPage(PDF.PAGESIZE_A4);
28
29     // Create a new "style" to write in - Black 24pt Helvetica.
30
//
31
PDFStyle mystyle = new PDFStyle();
32     mystyle.setFont(new StandardFont(StandardFont.HELVETICA), 24);
33     mystyle.setFillColor(Color.black);
34
35     // Put something on the page.
36
//
37
page.setStyle(mystyle);
38     page.drawText("Hello, PDF-viewing World!", 100, page.getHeight()-100);
39
40     // Automatically go to this page when the document is opened,
41
// zoom to fit.
42
//
43
pdf.setAction(Event.OPEN, PDFAction.goToFit(page));
44
45     // Add some document info
46
//
47
pdf.setInfo("Author", "Joe Bloggs");
48     pdf.setInfo("Title", "My First Document");
49
50     // Write the PDF to the servlet output stream. Set the Content-Type,
51
// which is obvious, and the Content-Length, which isn't that obvious.
52
// Some setups, particularly with the PDF plugin, require this header
53
// to be set.
54
//
55
// First render to a byte array, then write it to the servlet response.
56
//
57
ByteArrayOutputStream tempout = new ByteArrayOutputStream();
58     pdf.render(tempout);
59     res.setContentType("application/pdf");
60     res.setContentLength(tempout.size());
61     tempout.writeTo(res.getOutputStream());
62     }
63 }
64
Popular Tags