Dynamically Creating PDF in Struts 2
Good Evening ;
I have a problem that I am working on struts2 web 开发者_开发问答application. I am dynamically creating a PDF using data base. i want to show it in a web page but I don`t know how I do it is any one can help me.
Thanks...
Action code:
public class PDFAction extends ActionSupport {
private InputStream inputStream;
public String getPDF(){
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PdfWriter.getInstance(document, buffer);
document.open();
Paragraph p = new Paragraph();
p.add("INSTITUTO POLITÉCNICO NACIONAL, ESCUELA SUPERIOR DE CÓMPUTO, DIEGO A. RAMOS");
document.add(p);
document.close();
inputStream = new ByteArrayInputStream(buffer.toByteArray());
return SUCCESS;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}
Struts.xml:
<action name="getPDF" class="action.PDFAction" method="getPDF">
<result name="success" type="stream">
<param name="inputName">inputStream</param>
<param name="contentType">application/pdf</param>
<param name="contentDisposition">filename="mypdf.pdf"</param>
<param name="bufferSize">2048</param>
</result>
</action>
Try it, it works like a charm, works perfect for me. If you are in doubt read more about stream result type that Struts 2 provides. The answer to this is so simple yet it was hard to get to it.
You can write the content using the input stream or best way is to create custom result type where you can set appropriate header and other things here is a link for some help
Struts2 Custom Result Type
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PdfWriter.getInstance(document, buffer);
document.open();
////Do your stuff here
document.close();
DataOutput dataOutput = new DataOutputStream(response.getOutputStream());
byte[] bytes = buffer.toByteArray();
response.setContentLength(bytes.length);
for(int i = 0; i < bytes.length; i++)
{
dataOutput.writeByte(bytes[i]);
}
I m using iText for creating pdf. You can put this scriptlet in a jsp and call this jsp to show the pdf generated
精彩评论