在Web应用程序iText中创建PDF

时间:2011-09-11 19:41:04

标签: pdf servlets itext

我知道这可能是我要放在这里的愚蠢问题,因为我是一个完整的java菜鸟。也许你们可以帮助我解决这个问题。

我正在开发一个应用程序,用户需要在pdf格式的jsp页面上显示结果,并且pdf在HTTP请求中作为输出流生成,意味着当用户点击按钮(在jsp上)到生成带有结果的PDF,即PDF即时生成并发送到客户端浏览器。

使用iText,我可以动态生成自定义生成的pdf

以下是代码段

public class PdfSample extends HttpServlet {

    public PdfSample() {
        super();
    }

        //connection to DB.... code goes here.....

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws javax.servlet.ServletException, java.io.IOException {
        DocumentException ex = null;
        ByteArrayOutputStream baosPDF = null;
        try {
            baosPDF = generatePDFDocumentBytes(req, this.getServletContext());
            StringBuffer sbFilename = new StringBuffer();
            sbFilename.append("filename_");
            sbFilename.append(System.currentTimeMillis());
            sbFilename.append(".pdf");
            resp.setHeader("Cache-Control", "max-age=30");
            resp.setContentType("application/pdf");
            StringBuffer sbContentDispValue = new StringBuffer();
            sbContentDispValue.append("inline");
            sbContentDispValue.append("; filename=");
            sbContentDispValue.append(sbFilename);
            resp.setHeader("Content-disposition", sbContentDispValue.toString());
            resp.setContentLength(baosPDF.size());
            ServletOutputStream sos;
            sos = resp.getOutputStream();
            baosPDF.writeTo(sos);
            sos.flush();
        } catch (DocumentException dex) {
            resp.setContentType("text/html");
            PrintWriter writer = resp.getWriter();
            writer.println(this.getClass().getName() + " caught an exception: "
                    + dex.getClass().getName() + "<br>");
            writer.println("<pre>");
            dex.printStackTrace(writer);
            writer.println("</pre>");
        } finally {
            if (baosPDF != null) {
                baosPDF.reset();
            }
        }
    }

    protected ByteArrayOutputStream generatePDFDocumentBytes(
            final HttpServletRequest req, final ServletContext ctx)
            throws DocumentException
    {
        Document doc = new Document();
        ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
        PdfWriter docWriter = null;
        try {
            docWriter = PdfWriter.getInstance(doc, baosPDF);
            doc.addAuthor("Sample");
            doc.addCreationDate();
            doc.addProducer();
            doc.addCreator("Sample");
            doc.addTitle("Sample Report");
            doc.setPageSize(PageSize.LETTER);
            doc.open();
            String strServerInfo = ctx.getServerInfo();
            if (strServerInfo != null) {
            }
            doc.add(makeHTTPParameterInfoElement(req));
        } catch (DocumentException dex) {
            baosPDF.reset();
            throw dex;
        } finally {
            if (doc != null) {
                doc.close();
            }
            if (docWriter != null) {
                docWriter.close();
            }
        }

        if (baosPDF.size() < 1) {
            throw new DocumentException("document has " + baosPDF.size()
                    + " bytes");
        }
        return baosPDF;
    }
    protected Element makeHTTPParameterInfoElement(final HttpServletRequest req) {
        Table tab = null;
        tab = makeTable("", "White Color Car", "Black Color Car", "Total");
        return (Element) tab;
    }
    private static Table makeTable(final String firstColumnTitle,
            final String secondColumnTitle, final String thirdColumnTitle,
            final String fourthColumnTitle) {

        Paragraph paragraph, paragraph1;
        int val1 = 0;
        int val2 = 0;
        int val3 = 0;
        int val4 = 0;
        Table tab = null;
        try {
            tab = new Table(4);

        } catch (BadElementException ex) {
            throw new RuntimeException(ex);
        }
        Cell c = null;
        try {
        paragraph = new Paragraph("Car Report");
        paragraph.setAlignment(1);
        c = new Cell(paragraph);
        c.setColspan(tab.getColumns());
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        tab.setBorderWidth(1);
        tab.setBorderColor(Color.BLACK);
        tab.setPadding(2);
        tab.setSpacing(3);
        tab.setBackgroundColor(Color.WHITE);
        tab.addCell(c);
        tab.addCell(new Cell(firstColumnTitle));
        tab.addCell(new Cell(secondColumnTitle));
        tab.addCell(new Cell(thirdColumnTitle));
        tab.addCell(new Cell(fourthColumnTitle));
        tab.endHeaders();

        String startDate1 = "01/06/2011";
        String endDate1 = "11/09/2011";

        SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
        try {
            Date startDate = sdf1.parse(startDate1);
            Date endDate = sdf1.parse(endDate1);
            java.sql.Date sdate = new java.sql.Date(startDate.getTime());
            java.sql.Date edate = new java.sql.Date(endDate.getTime());

             String newWhiteColor = "select count(*) from .......";
         String newBlackColor = "select count(*) from .......";
         String totalWhiteColor= "select count(*) from .....";
         String totalBlackColor = "select count(*) from .......";

                    Connection connection = null;
            PreparedStatement preparedStatement = null;
            PreparedStatement preparedStatement1 = null;
            PreparedStatement preparedStatement2 = null;
            PreparedStatement preparedStatement3 = null;

            ResultSet resultSet = null;
            ResultSet resultSet1 = null;
            ResultSet resultSet2 = null;
            ResultSet resultSet3 = null;

            connection = getSimpleConnection1();

            // New Car recently sold out - White Color
            preparedStatement = connection
                    .prepareStatement(newWhiteColor);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                val1 = resultSet.getInt(1);
            }

            // New Car recently sold out - Black Color
            preparedStatement3 = connection
                    .prepareStatement(newBlackColor);
            resultSet3 = preparedStatement3.executeQuery();
            while (resultSet3.next()) {
                val2 = resultSet3.getInt(1);
            }

            // Total White Color cars sold out
            preparedStatement1 = connection
                    .prepareStatement(totalWhiteColor);
            resultSet1 = preparedStatement1.executeQuery();
            while (resultSet1.next()) {
                val3 = resultSet1.getInt(1);
            }

            // Total Black Color cars sold out
            preparedStatement2 = connection
                    .prepareStatement(totalBlackColor);
            resultSet2 = preparedStatement2.executeQuery();
            while (resultSet2.next()) {
                val4 = resultSet2.getInt(1);
            }

            Integer newWhite = val1;
            Integer newBlack = val2;
            Integer totalWhite = val3;
            Integer totalBlack = val4;
                Integer totalNewCars = newWhite + new Black;
            Integer totalCars= totalWhite + totalBlack ;

            tab.addCell(new Cell("New Cars Sold Out"));
            tab.addCell(new Cell(newWhite.toString()));
            tab.addCell(new Cell(newBlack.toString()));
                tab.addCell(new Cell(totalNewCars.toString()));
            tab.addCell(new Cell("Total Cars Sold out"));
            tab.addCell(new Cell(totalWhite.toString()));
            tab.addCell(new Cell(totalBlack.toString()));
            tab.addCell(new Cell(totalCars.toString()));

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return tab;
    }


}

上面的代码通过建立连接并在单元格中显示来从数据库中获取数据(计数)。使用上面的代码,我可以在飞行和输出上创建pdf,如下所示。

-------------------------------------------------------------------------------------------------- 
Car Report
--------------------------------------------------------------------------------------------------
                   | White Color Car          |Black Color Car       |  Total                
--------------------------------------------------------------------------------------------------
  New Cars Sold out|         5                |      8               |    13
--------------------------------------------------------------------------------------------------
Total Cars Sold Out|        6                 |      4               |    10
--------------------------------------------------------------------------------------------------

查询1)如何在中心对齐汽车报告?

查询2)数据和文本正在单元格内显示,如何将单元格的边框设置为“0”。

查询3)如何为特定单元格(空白单元格)着色?

查询4)是否可以在pdf标题的顶部插入图片?

任何帮助都将非常感谢!!!!!

1 个答案:

答案 0 :(得分:0)

查询1) 如何在中心对齐汽车报告?

解决方案:c.setHorizontalAlignment(Element.ALIGN_CENTER);