Sometime we may want to add the PDF generation functionality to a web application, where user on clicking some link or button is served with PDF output. Hence the PDF should be generated on fly and sent to client browser.
Consider following simple action class for Struts which uses this mechanism to generate a dummy PDF and sent the output to browser.
Notice that, we have passed response.getOutputStream() object to getInstance() method. Thus the output generated by iText will be sent directly to the response. Also don’t forget to set the content type of the response to application/pdf.
Consider following simple action class for Struts which uses this mechanism to generate a dummy PDF and sent the output to browser.
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
public class PdfHelloWorldAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Document document = new Document();
try{
response.setContentType("application/pdf");
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(new Paragraph("Hello vaani"));
document.add(new Paragraph(new Date().toString()));
}catch(Exception e){
e.printStackTrace();
}
document.close();
return null;
}
}
Notice that, we have passed response.getOutputStream() object to getInstance() method. Thus the output generated by iText will be sent directly to the response. Also don’t forget to set the content type of the response to application/pdf.
No comments:
Post a Comment