Reputation: 7953
I have some values to be exported to PDF, how can i do this in struts?
I would like to do the following, have option button or link when the user clicks on the button or link than the user should get a download option to download the exported PDF file.
I have a resultset which needs to be exported to PDF.
Please help me how to go about.
Regards
Upvotes: 0
Views: 3621
Reputation: 46
Take a look to this example of an action class it may help you out.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.lowagie.text.pdf.*;
import com.lowagie.text.*;
import java.io.*;
public class download extends org.apache.struts.action.Action {
/* forward name="success" path="" */
private static final String SUCCESS = "success";
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Document document=new Document();
System.out.println(clientIp);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=temp.pdf");
try
{
OutputStream out = response.getOutputStream();
PdfWriter.getInstance(document,out);
document.open();
document.add(new Paragraph("Hello Pdf"));
document.close();
}
finally
{
return mapping.findForward(SUCCESS);
}
}
Also update your struts-config.xml according to it.
Upvotes: 2
Reputation: 46
Here is an example that may help you to do what you want:
import java.io.*;
import java.sql.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class CreatePDF{
public static void main(String arg[])throws Exception{
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("C:/data.pdf"));
document.open();
PdfPTable table = new PdfPTable(2);
table.addCell("Name");
table.addCell("Address");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test",
"root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("Select * from data");
while(rs.next()) {
table.addCell(rs.getString("name"));
table.addCell(rs.getString("address"));
}
document.add(table);
document.close();
}
}
But before implementing it you have to put itext.jar
into your WEB-INF/lib
folder.
And you also found plenty of methods to manipulate your pdf file.
Upvotes: 1