1 |
torben |
2516 |
/* Sample servlet to demonstrate the usage of iText for generation pdf documents.
|
2 |
|
|
*
|
3 |
|
|
* For more in-depth look at the API docs or the book "iText in action"
|
4 |
|
|
*
|
5 |
|
|
* How to add page header/footer via PdfPageEventHelper :
|
6 |
|
|
* http://faq.javaranch.com/java/ItextExample
|
7 |
|
|
*/
|
8 |
|
|
|
9 |
|
|
import java.io.ByteArrayOutputStream;
|
10 |
|
|
import java.io.IOException;
|
11 |
|
|
|
12 |
|
|
import javax.servlet.ServletException;
|
13 |
|
|
import javax.servlet.http.HttpServlet;
|
14 |
|
|
import javax.servlet.http.HttpServletRequest;
|
15 |
|
|
import javax.servlet.http.HttpServletResponse;
|
16 |
|
|
|
17 |
|
|
import com.itextpdf.text.Document;
|
18 |
|
|
import com.itextpdf.text.Image;
|
19 |
|
|
import com.itextpdf.text.PageSize;
|
20 |
|
|
import com.itextpdf.text.Paragraph;
|
21 |
|
|
import com.itextpdf.text.pdf.PdfWriter;
|
22 |
|
|
|
23 |
|
|
/**
|
24 |
|
|
* Servlet implementation class PdfServlet
|
25 |
|
|
*/
|
26 |
|
|
public class PdfServlet extends HttpServlet {
|
27 |
|
|
private static final long serialVersionUID = 1L;
|
28 |
|
|
|
29 |
|
|
|
30 |
|
|
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
31 |
|
|
// Custom size Rectangle pageSize = new Rectangle(200f, 200f);
|
32 |
|
|
// PageSize.A4.rotate(); //A4 in landscape mode
|
33 |
|
|
Document document = new Document(PageSize.A4);
|
34 |
|
|
|
35 |
|
|
|
36 |
|
|
|
37 |
|
|
|
38 |
|
|
ByteArrayOutputStream out = new ByteArrayOutputStream(32000);
|
39 |
|
|
try {
|
40 |
|
|
PdfWriter writer = PdfWriter.getInstance(document,out);
|
41 |
|
|
document.open();
|
42 |
|
|
document.add(new Paragraph("Hello World"));
|
43 |
|
|
|
44 |
|
|
document.add(new Paragraph("Lorem ipsum"));
|
45 |
|
|
Image img = Image.getInstance("http://app.t-hoerup.dk/Test3/ImageServlet");
|
46 |
|
|
img.scaleAbsolute(100, 100);
|
47 |
|
|
img.setRotationDegrees(45);
|
48 |
|
|
document.add(img);
|
49 |
|
|
|
50 |
|
|
|
51 |
|
|
} catch (Exception e) {
|
52 |
|
|
// handle exception
|
53 |
|
|
}
|
54 |
|
|
document.close();
|
55 |
|
|
byte rawDocument[] = out.toByteArray();
|
56 |
|
|
|
57 |
|
|
response.setContentType("application/pdf");
|
58 |
|
|
|
59 |
|
|
response.setHeader("Cache-Control", "no-cache");
|
60 |
|
|
response.setDateHeader("Expires", 0);
|
61 |
|
|
|
62 |
|
|
//You will probably like to add this header in production, with some proper filename
|
63 |
|
|
//response.setHeader("Content-disposition", "attachment; filename=pdfname.pdf");
|
64 |
|
|
|
65 |
|
|
|
66 |
|
|
response.setContentLength(rawDocument.length);
|
67 |
|
|
response.getOutputStream().write( rawDocument );
|
68 |
|
|
}
|
69 |
|
|
|
70 |
|
|
}
|