RANJEET KUMAR
RANJEET KUMAR

Reputation: 11

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...

Upvotes: 1

Views: 5330

Answers (3)

Diego Ramos
Diego Ramos

Reputation: 1059

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.

Upvotes: 5

Anupam
Anupam

Reputation: 8016

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

Upvotes: 1

Umesh Awasthi
Umesh Awasthi

Reputation: 23587

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

Upvotes: 1

Related Questions