Saturday, 7 April 2012

Creating Pdf By Using Struts2

Struts Framework and Stream Result type configuration for the Action to send binary stream to the browser as PDF
content type

In this example I shall be showing step by step ways to follow through various pieces of code to process or achieve
an objective of presenting binary content type to browser based client and this is presented to the client with the
same name as mentioned in struts.xml configuration file.

Struts.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
  <package name="stream-example" namespace="/sample-stream"
                 extends="struts-default">
    <action name="pdfAction" class="com.lkr.struts2.pdf.GeneratingPdfAction" 
                        method="generatingPdf">
       <result name="test-stream" type="stream">
         <param name="inputName">fileStream</param>
  <param name="contentType">application/pdf</param>
         <param name="contentDisposition">filename="test.pdf"</param>
       </result>
    </action>
  </package>
</struts>

Action class "GeneratingPdfAction.java" is having a generatingPdf method that assigns an input stream to a private
instance variable, this variable is mentioned as the inputName param value to the result tag.

In this example, the inputName param is having value as fileStream, that is defined as an instance variable
in Action class.


GeneratingPdfAction

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package com.lkr.struts2.pdf;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class GeneratingPdfAction {
 private InputStream fileStream;
 private static String FILE = "c:/temp/FirstPdf.pdf";
 private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
   Font.BOLD);
 private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
   Font.NORMAL, BaseColor.RED);
 private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
   Font.BOLD);
 private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
   Font.BOLD);

 public void setFileStream(InputStream arg) {
  fileStream = arg;
 }

 public InputStream getFileStream() {
  return fileStream;
 }


 public String generatingPdf() throws Exception {
  
  try {
   Document document = new Document();
   PdfWriter.getInstance(document, new FileOutputStream(FILE));
   document.open();
   addMetaData(document);
   addTitlePage(document);
   addContent(document);
   document.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
  try{
   fileStream = new DataInputStream(
     new FileInputStream(FILE));
  } catch (IOException ioEx) {
   ioEx.printStackTrace();
  }
  
  return "test-stream";
 }
 
 private static void addMetaData(Document document) {
  document.addTitle("My first PDF");
  document.addSubject("Using iText");
  document.addKeywords("Java, PDF, iText");
  document.addAuthor("Konda Reddy. Lingamdinne");
  document.addCreator("Konda Reddy. Lingamdinne");
 }

 private static void addTitlePage(Document document)
   throws DocumentException {
  Paragraph preface = new Paragraph();
  // We add one empty line
  addEmptyLine(preface, 1);
  // Lets write a big header
  preface.add(new Paragraph("Title of the document", catFont));

  addEmptyLine(preface, 1);
  // Will create: Report generated by: _name, _date
  preface.add(new Paragraph(
    "Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    smallBold));
  addEmptyLine(preface, 3);
  preface.add(new Paragraph(
    "This document describes something which is very important ",
    smallBold));

  addEmptyLine(preface, 8);

  preface.add(new Paragraph(
    "This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.de ;-).",
    redFont));

  document.add(preface);
  // Start a new page
  document.newPage();
 }

 private static void addContent(Document document) throws DocumentException {
  Anchor anchor = new Anchor("First Chapter", catFont);
  anchor.setName("First Chapter");

  // Second parameter is the number of the chapter
  Chapter catPart = new Chapter(new Paragraph(anchor), 1);

  Paragraph subPara = new Paragraph("Subcategory 1", subFont);
  Section subCatPart = catPart.addSection(subPara);
  subCatPart.add(new Paragraph("Hello"));

  subPara = new Paragraph("Subcategory 2", subFont);
  subCatPart = catPart.addSection(subPara);
  subCatPart.add(new Paragraph("Paragraph 1"));
  subCatPart.add(new Paragraph("Paragraph 2"));
  subCatPart.add(new Paragraph("Paragraph 3"));

  // Add a list
  Paragraph paragraph = new Paragraph();
  addEmptyLine(paragraph, 5);
  subCatPart.add(paragraph);

  // Add a table
  createTable(subCatPart);

  // Now add all this to the document
  document.add(catPart);

  // Next section
  anchor = new Anchor("Second Chapter", catFont);
  anchor.setName("Second Chapter");

  // Second parameter is the number of the chapter
  catPart = new Chapter(new Paragraph(anchor), 1);

  subPara = new Paragraph("Subcategory", subFont);
  subCatPart = catPart.addSection(subPara);
  subCatPart.add(new Paragraph("This is a very important message"));

  // Now add all this to the document
  document.add(catPart);

 }

 private static void createTable(Section subCatPart)
   throws BadElementException {
  PdfPTable table = new PdfPTable(3);

  // t.setBorderColor(BaseColor.GRAY);
  // t.setPadding(4);
  // t.setSpacing(4);
  // t.setBorderWidth(1);

  PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
  c1.setHorizontalAlignment(Element.ALIGN_CENTER);
  table.addCell(c1);

  c1 = new PdfPCell(new Phrase("Table Header 2"));
  c1.setHorizontalAlignment(Element.ALIGN_CENTER);
  table.addCell(c1);

  c1 = new PdfPCell(new Phrase("Table Header 3"));
  c1.setHorizontalAlignment(Element.ALIGN_CENTER);
  table.addCell(c1);
  table.setHeaderRows(1);

  table.addCell("1.0");
  table.addCell("1.1");
  table.addCell("1.2");
  table.addCell("2.1");
  table.addCell("2.2");
  table.addCell("2.3");

  subCatPart.add(table);

 }

 private static void addEmptyLine(Paragraph paragraph, int number) {
  for (int i = 0; i < number; i++) {
   paragraph.add(new Paragraph(" "));
  }
 }

}


web.xml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, 
    Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <display-name>Struts 2 Stream Result type</display-name>
  <filter>
  <filter-name>sample-filter</filter-name>
  <filter-class> 
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>sample-filter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

This example application creates PDF file and reads the PDF file from the path mentioned in the Action class and  
generatingPdf method.
This result type definition in struts.xml file sends those to the client as downloadable file name.

No comments:

Post a Comment