我有一些值要导出为PDF,我如何在struts中执行此操作?在struts 1.x中导出为pdf
我想做以下事情,当用户点击按钮或链接时,有选项按钮或链接,而不是用户应该得到下载选项来下载导出的PDF文件。
我有一个需要导出为PDF的结果集。
请帮助我如何去。
问候
我有一些值要导出为PDF,我如何在struts中执行此操作?在struts 1.x中导出为pdf
我想做以下事情,当用户点击按钮或链接时,有选项按钮或链接,而不是用户应该得到下载选项来下载导出的PDF文件。
我有一个需要导出为PDF的结果集。
请帮助我如何去。
问候
下面是一个例子,可以帮助你做你想要什么:
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();
}
}
但是实现它之前,你必须把itext.jar
到您的WEB-INF/lib
文件夹。 你也发现了很多方法来操纵你的pdf文件。
直到这我也做了同样的事情,但需要与struts应用程序集成,而不是创建文件到特定的位置,我想给用户下载的选项。我认为我们必须在哪里设置“content-dispostion”,我不知道在哪里以及如何去做。 –
看看这个动作类的例子,它可以帮助你。
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);
}
}
还根据它更新您的struts-config.xml。
Struts不会导出为PDF。如果你想实现它,你应该使用[iText](http://itextpdf.com/)或其他PDF库。 –