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>
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 04, 2022Comments
-
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 about 12 yearsthis 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 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 about 12 yearsI did one mistake, just to fix it: <param name="contentDisposition">filename=${contentDisposition}</param>
-
Med about 10 yearsThanks for the tip ! This with an "inline;" in the
contentDisposition
param saved my day. =)