Dynamically create PDF in Struts 2

Good evening;

I have a problem that I am working on a struts2 web application. I am dynamically creating a PDF using a database. I want to show it on a webpage, but I don’t know how I do it, it can help me.

Thanks...

+1
source share
3 answers

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 great for me. If in doubt, read more about the type of stream result that Struts provides 2. The answer to this question is so simple, but it was hard to get to it.

+5
source

You can write content using the input stream, or the best way is to create a custom type of result in which you can set the appropriate title and other things, here is a link for some help

Struts2 Custom Result Type

+1
source
 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 am using iText to create pdf. You can put this scriptlet in jsp and call this jsp to show the created pdf

+1
source

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


All Articles