Struts2 Display pdf file in jsp

12,043

This is how I am doing it. You can call this action inside an iframe or in a regular jsp

public class GeneratePdf extends ActionSupport{
    private InputStream inputStream;
    public String execute(){
        HttpServletResponse response = ServletActionContext.getResponse();
        Document document = new Document();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try {
            PdfWriter.getInstance(document, buffer);
            document.open();
                        // do your thing
            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        byte[] bytes = null;
        bytes = buffer.toByteArray();
        response.setContentLength(bytes.length);

        if(bytes!=null){
            inputStream = new ByteArrayInputStream ( bytes );
        }
 return SUCCESS;
}

public InputStream getInputStream() {
        return inputStream;
    }
}

In your struts.xml

   <action name="GeneratePdf" class="com.xxx.action.GeneratePdf">
    <result name="success" type="stream">
            <param name="contentType">application/pdf</param>
            <param name="inputName">inputStream</param>
            <param name="contentDisposition">filename="test.pdf"</param>
            <param name="bufferSize">1024</param>
    </result>
   </action>   
Share:
12,043
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin about 2 years

    My requirement is to create a dynamic report pdf file with some data from database which I'm doing it using iText. Now, I want to display this pdf file inline in the webpage alongwith menu,header, footer, etc.

    So, If the user has some pdf viewer then this pdf should be displayed in user machine with print option to print that pdf.

  • Zemzela
    Zemzela about 12 years
    this params should be taken from GeneratePdf class, especially contentDisposition in order to have different name of pdf. If you have method public String getContentDisposition() in GeneratePdf in action you will get that param like this: <param name="contentDisposition">${contentDisposition}</param>
  • Anupam
    Anupam about 12 years
    @Zemzela Exactly. This was just an example to show the OP how does the basic setup works. I didn't mentioned filename param as I have not shown its getter in the action class.
  • Zemzela
    Zemzela about 12 years
    I did one mistake, just to fix it: <param name="contentDisposition">filename=${contentDisposition}</pa‌​ram>
  • Med
    Med about 10 years
    Thanks for the tip ! This with an "inline;" in the contentDisposition param saved my day. =)