Struts2 Show pdf file in jsp

My requirement is to create a dynamic report in pdf format with some data from the database, which I do using iText. Now I want to display this pdf file on a web page along with a menu, a header, a footer, etc.

So, if the user has some kind of pdf viewer, then this pdf file should be displayed on the user's computer with the print option for printing this pdf.

+3
source share
3 answers

This is how I do it. You can call this action inside iframe or in 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> 
+8
source

I do this using an action with inputStream , as Anu suggested. And using the PDF.JS library.

Online demo

Github

0
source
 public ByteArrayInputStream generatePDF(List<Object> items) { try { List<InputStream> listInputStream = new ArrayList<InputStream>(); for (int i = 0; i < items.size(); i++) { listInputStream.add(new ByteArrayInputStream(getBytes(items.get(i))); } HttpServletResponse response = ServletActionContext.getResponse(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, buffer); document.open(); PdfContentByte cb = writer.getDirectContent(); for (InputStream inputStream : listInputStream) { PdfReader reader = new PdfReader(inputStream); for (int i = 1; i <= reader.getNumberOfPages(); i++) { document.setPageSize(reader.getPageSize(i)); document.newPage(); PdfImportedPage page = writer.getImportedPage(reader, i); cb.addTemplate(page, 0, 0); } } document.close(); byte[] bytes = null; bytes = buffer.toByteArray(); response.setContentLength(bytes.length); return new ByteArrayInputStream(bytes); } catch(Exception e){ System.out.println(e); } } 
0
source

Source: https://habr.com/ru/post/1432291/


All Articles