在 Web 应用程序 iText 中创建 PDF

发布于 2024-12-03 22:17:43 字数 9333 浏览 1 评论 0原文

我知道这可能是一个愚蠢的问题,因为我是一个十足的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) 如何在 Center 中对齐汽车报告?

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

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

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

任何帮助将不胜感激!

I know this may be stupid question i am gonna put here since i am a complete java noob. may be you guys can help me out to get this problem solved.

I am working on an application where a user would need the result dislayed on jsp page in pdf form, and the pdf is being generated as output stream in HTTP request, means when a user clicks on a button(on jsp) to generate PDF with result i.e. PDF getting generated on fly and sent to client browser.

Using iText, i am able to generate custom generated pdfs on the fly

Heres the Code snippet

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;
    }


}

The Above code fetching the data (count) from the database by making the connection and displaying in cells. with the above code i am able to create pdf on fly and output as showing below.

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

Query 1) How Can I align the car report in Center?

Query 2) Data and text are being displayed inside a cell, how can i set the border of the cell to "0".

Query 3) How can i color a particular cell ( the blank one)?

Query 4) Is it possible to Insert a image on top of the header of the pdf?

Any help would be greatly appreciated !!!!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不奢求什么 2024-12-10 22:17:43

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

解决方案:c.setHorizo​​ntalAlignment(Element.ALIGN_CENTER);

Query 1) How Can I align the car report in Center?

Solution : c.setHorizontalAlignment(Element.ALIGN_CENTER);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文