How to generate PDF in new window using itext in Struts2

2.9k views Asked by At
 <action name="PDF" class="OwnerDetail" method="createPDF">
     <result name="success" type="stream">
        <param name="contentType">application/pdf</param>
        <param name="inputName">inputStream</param>
        <param name="contentDisposition">attachment;filename="RegistrationSummaryReport.pdf"</param>
        <param name="bufferSize">1024</param>
    </result>
</action>

The above code generates PDF as an attachment. But I need to open the PDF in a new window. Kindly provide your suggestions

1

There are 1 answers

4
Andrea Ligios On BEST ANSWER

You need to change the contentDisposition. This is an HTTP header, so this is needed when using other technologies than Struts2 too (Servlets, for example).

Content-Disposition has two main values that are interesting for your case:

  • attachment : asks the user which is the action needed between downloading the file, or opening it with a Desktop application.

  • inline (default): tries opening the file in a new tab (or window) with a browser plugin. If a plugin is not found for that Content-Type, it asks the user to choose a Desktop application for opening it.

Then you need simply:

<param name="contentDisposition">
    inline;filename="RegistrationSummaryReport.pdf"
</param>

or just

<param name="contentDisposition">
    filename="RegistrationSummaryReport.pdf"
</param>

EDIT

As suggested in a comment by @BrunoLowagie, I may have omitted an important part.

While it's true that you need inline to open the document in the browser, it's also true that a further step (that I've taken for granted, while it may be not) is needed to open that document in another Tab/Window instead that on the current one, : you need to call the action by specifying the target attribute, or by using javascript window.open():

<s:url var="myUrl" action="downloadPdf" namespace="/foobar" />

<!-- In a new Tab/Window without javascript -->  
<s:a href="%{myUrl} target="_blank">
    download
</s:a>

<!-- In a new Tab/Window with javascript -->    
<s:a href="javascript:window.open('%{myUrl}');>
    download
</s:a>

Read more on this related answer.