如何传递一个集合变量值到另一个pdf生成类 [英] how to pass one collection variable value into another pdf generating class

查看:164
本文介绍了如何传递一个集合变量值到另一个pdf生成类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML解析器类,其中我正在读取XML类和解析,并基于一些值,我从数据库获取,并与两个值我计算薪水,我现在我已经做了我想传递这个变量到另一个pdf类,我想为特定的ID相关人生成pdf

i Have one XML parser class in which i am reading XML class and parsing and on the basis of some value which i am getting from database and with both values i am calculating salary that i have done now i want to pass this variable into another pdf class wher i want to generate pdf for the particular ID associated person

public class XMLParser extends HttpServlet {
    public static HashMap<String, String> hMap1 = new HashMap<String, String>();
    public static HashMap<String, String> hMap2 = new HashMap<String, String>();
    public static HashMap<String, Double> hMap3 = new HashMap<String, Double>();


    public static String series1, series2, ID;
    int s1, s2;
    double s3;
    static double z;

    public void getAllUserNames(String fileName) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            File file = new File(fileName);
            if (file.exists()) {
                Document doc = db.parse(file);
                Element docEle = doc.getDocumentElement();
                // Print root element of the document
                System.out.println("Root element of the document: " + docEle.getNodeName());

                NodeList studentList = docEle.getElementsByTagName("emplopyee");
                // NodeList st1 = docEle.getElementsByTagName("emplopyee");

                // Print total student elements in document
                System.out.println("Total emplopyee: " + studentList.getLength());

                if (studentList != null && studentList.getLength() > 0) {
                    for (int i = 0; i < studentList.getLength(); i++) {

                        Node node = studentList.item(i);

                        if (node.getNodeType() == Node.ELEMENT_NODE) {

                            System.out.println("=====================");

                            Element e = (Element)node;


                            NodeList nodeList1 = e.getElementsByTagName("ID");
                            ID = nodeList1.item(0).getChildNodes().item(0).getNodeValue();


                            System.out.println("ID: " + nodeList1.item(0).getChildNodes().item(0).getNodeValue());
                            NodeList nodeList2 = e.getElementsByTagName("Name");
                            series1 = nodeList2.item(0).getChildNodes().item(0).getNodeValue();
                            System.out.println("Name: " + nodeList2.item(0).getChildNodes().item(0).getNodeValue());

                            NodeList nodeList3 = e.getElementsByTagName("Days");


                            String series2 = nodeList3.item(0).getChildNodes().item(0).getNodeValue();
                            s3 = Double.parseDouble(series2);
                            System.out.println(s3);
                            Class.forName("com.mysql.jdbc.Driver");
                            Connection con =
                                DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", null);
                            Statement st = con.createStatement();
                            ResultSet rs = st.executeQuery("Select * from emp1 where eid = '" + ID + "' ");

                            while (rs.next()) {
                                int n1 = Integer.parseInt(rs.getString(1));
                                String n2 = rs.getString(2);
                                int n3 = Integer.parseInt(rs.getString(3));
                                int n4 = Integer.parseInt(rs.getString(4));
                                System.out.println(n1);
                                System.out.println(n2);
                                System.out.println(n3);
                                System.out.println(n4);
                                z = s3 * n3;

                                System.out.println(z);
                            }
                        }
                    }

                    hMap3.put(ID, z);
                    System.out.println(hMap3); //----> this thing i want to print in pdf
                }


                else {
                    System.exit(1);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                                                                                       java.io.IOException {
        XMLParser parser = new XMLParser();
        parser.getAllUserNames("D:\\employee.xml");
        ServletContext context = this.getServletContext();
        RequestDispatcher dispatcher = context.getRequestDispatcher("/FirstPdf");
        dispatcher.forward(request, response);
    }
}

另一个pdf生成类

public class FirstPdf extends HttpServlet {
    private static String FILE = "c:/temp/SecondPdf.pdf";
    private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
    private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED);
    private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);
    private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                                                                                       java.io.IOException {
        try {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(FILE));
            document.open();
            addMetaData(document);
            addTitlePage(document);
            addContent(document);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void addMetaData(Document document) {
        document.addTitle("Salary PDF");
        document.addSubject("Using iText");
        document.addKeywords("Java, PDF, iText");
        document.addAuthor("Saurabh");
        document.addCreator("Saurabh Gupta");
    }

    private static void addTitlePage(Document document) throws DocumentException {
        Paragraph preface = new Paragraph();


        preface.add(new Paragraph("Title of the document", catFont));

        addEmptyLine(preface, 1);

        preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(),
                                  smallBold));
        addEmptyLine(preface, 3);
        preface.add(new Paragraph("This document describes something which is very important ", smallBold));

        addEmptyLine(preface, 8);

        preface.add(new Paragraph("This document is simple demonstration of generating salry slip).", redFont));

        document.add(preface);

        document.newPage();
    }

    private static void addContent(Document document) throws DocumentException {
        Anchor anchor = new Anchor("First page", catFont);
        anchor.setName("First Page");

        Chapter catPart = new Chapter(new Paragraph(anchor), 1);

        Paragraph subPara = new Paragraph("Subcategory 1", subFont);
        Section subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("Here we go"));

        subPara = new Paragraph("Subcategory 2", subFont);
        subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("Paragraph 1"));
        subCatPart.add(new Paragraph("Paragraph 2"));
        subCatPart.add(new Paragraph("Paragraph 3"));


        createList(subCatPart);
        Paragraph paragraph = new Paragraph();
        addEmptyLine(paragraph, 5);
        subCatPart.add(paragraph);


        createTable(subCatPart);

        now add;
        all;
        this;
        to the;
        document;
        document.add(catPart);


        anchor = new Anchor("Second Chapter", catFont);
        anchor.setName("Second Chapter");

        Second parameter;
        is the;
        number of;
        the chapter;
        catPart = new Chapter(new Paragraph(anchor), 1);

        subPara = new Paragraph("Subcategory", subFont);
        subCatPart = catPart.addSection(subPara);
        subCatPart.add(new Paragraph("This is a very important message"));


        document.add(catPart);

    }

    private static void createTable(Section subCatPart) throws BadElementException {
        PdfPTable table = new PdfPTable(4);


        PdfPCell c1 = new PdfPCell(new Phrase("Employee ID"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Name"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("No of days that person came"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);


        c1 = new PdfPCell(new Phrase("Salary for the month"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);


        table.setHeaderRows(1);

        table.addCell("1.1");
        table.addCell("1.2");
        table.addCell("1.3");
        table.addCell("1.4");
        table.addCell("2.1");
        table.addCell("2.2");
        table.addCell("2.3");
        table.addCell("2.4");
        subCatPart.add(table);
    }

    private static void createList(Section subCatPart) {
        List list = new List(true, false, 10);
        list.add(new ListItem("First point"));
        list.add(new ListItem("Second point"));
        list.add(new ListItem("Third point"));
        subCatPart.add(list);
    }

    private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(""));
        }
    }
}
enter code here


推荐答案

使用 ServletRequest#setAttribute()并将请求中的数据设为属性

use ServletRequest#setAttribute() and set data in request as attribute

使用 ServletRequest#getAttribute()从请求中获取数据。

use ServletRequest#getAttribute() to get data back from request.

示例代码:

public class XMLParser extends HttpServlet {
   ...

    ServletContext context = this.getServletContext();
    RequestDispatcher dispatcher = context.getRequestDispatcher("/FirstPdf");

    request.setAttribute(key,value);
    dispatcher.forward(request, response);

}


public class FirstPdf extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,java.io.IOException {
        Object value = request.getAttribute(key);
        ...
    }  
}

这篇关于如何传递一个集合变量值到另一个pdf生成类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆