Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6563839
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T13:53:44+00:00 2026-05-25T13:53:44+00:00

I know this may be stupid question i am gonna put here since i

  • 0

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 !!!!!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T13:53:45+00:00Added an answer on May 25, 2026 at 1:53 pm

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

    Solution : c.setHorizontalAlignment(Element.ALIGN_CENTER);

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Good Day Guys, I know this may sound like a stupid question. However, I
This may be a stupid question to ask, but still I need to know
I know this may be a stupid question to ask but I have really
This may seem like a stupid question, but I need to know where the
This may seem a stupid question but I can't find the anwer... This is
So, this may be a really stupid question, but I'm obviously missing something here.
I know this may sound like a stupid question, but numerous google searches haven't
I know this may be a stupid question to ask but I want to
I'm new to Ruby so this may be a stupid question. I know that,
just learning Java and I know this may sound stupid but I have to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.