Example usage for com.itextpdf.text Document Document

List of usage examples for com.itextpdf.text Document Document

Introduction

In this page you can find the example usage for com.itextpdf.text Document Document.

Prototype


public Document(Rectangle pageSize) 

Source Link

Document

Constructs a new Document -object.

Usage

From source file:Separator.java

License:Apache License

public static void splitPDFFile(String fileName) {
    // splitting "documents" up by consecutive orientations
    try {/*from ww  w.java 2 s .  com*/
        int[] oriens = new int[pReader.getNumberOfPages()];
        ArrayList<Integer> splitSizes = new ArrayList<Integer>();
        int splitSize = 1;
        int position = 0;
        for (int i = 1; i <= pReader.getNumberOfPages(); i++) {
            String picName = System.getProperty("user.home")
                    + "\\Desktop\\Scan Folder\\Temp Pictures\\my_image_" + i + ".jpg";
            oriens[i - 1] = getOrientation(new Picture(picName));
            System.out.print(oriens[i - 1]);
            if (i == 1) {
                splitSizes.add(1);
            } else if (oriens[i - 1] == oriens[i - 2]) {
                splitSize++;
                if (i == pReader.getNumberOfPages()) {
                    splitSizes.set(position, splitSize);
                }
            } else if (oriens[i - 1] != oriens[i - 2]) {
                splitSizes.set(position, splitSize);
                position++;
                splitSizes.add(1);
                splitSize = 1;
            } else {
                System.out.println("Error");
            }

        }
        System.out.println("\n\n" + splitSizes);
        System.out.println("\nSuccessfully read input file: " + fileName + "\n");
        int totalPages = pReader.getNumberOfPages();
        System.out.println("There are total " + totalPages + " pages in this input file\n");
        split = 0;

        // Page numbers start from 1 to n; writing each set of pages to one file
        for (int pageNum = 1; pageNum <= totalPages; pageNum += splitSizes.get(split - 1)) {
            String outFile = System.getProperty("user.home") + "\\Desktop\\Scan Folder\\Temp PDFs\\temp_"
                    + split + ".pdf";
            Document document = new Document(pReader.getPageSizeWithRotation(pageNum));
            PdfCopy writer = new PdfCopy(document, new FileOutputStream(outFile));
            document.open();
            int tempPageCount = 0;
            for (int pN = 0; pN < splitSizes.get(split); pN++) {
                PdfImportedPage page = writer.getImportedPage(pReader, pageNum + pN);
                writer.addPage(page);
                tempPageCount++;
            }

            System.out.println("pageNum: " + pageNum + "     splitSizes.get(split): " + splitSizes.get(split));

            document.close();
            /*
             * The following will trigger the PDF file being written to the
             * system
             */

            writer.close();

            crop(outFile, fileName, split, verFlag);

            System.out.println("Split: [" + tempPageCount + " page]: " + outFile);
            split++;
            verFlag = !verFlag; // alternating to determine the cropped orientation of the PDF
        }
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "There was an error while splitting up\n" + "the PDF.", "Error!",
                JOptionPane.OK_OPTION);
        System.exit(0);
    }
}

From source file:Main_Frame.java

private void jMenuItem29ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem29ActionPerformed
    try {/*from ww  w.j a va 2s .  c om*/
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con1 = DriverManager.getConnection("jdbc:odbc:College");
        Statement stm1 = con1.createStatement();
        //Statement stm1 = con1.createStatement();
        ResultSet rs = stm1.executeQuery("SELECT * from Slot_Details");
        //ResultSet rs1 = stm2.executeQuery("SELECT * from Slot_Details");
        String[] start = new String[10];
        String[] end = new String[10];
        int line = 0;
        while (rs.next()) {

            start[line] = rs.getString("START");
            end[line] = rs.getString("END");
            line++;
        }

        /*   try{
        Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); 
        Connection con2=DriverManager.getConnection("jdbc:odbc:College");*/
        Statement stm2 = con1.createStatement();
        ResultSet query_set = stm2.executeQuery("SELECT * from format");
        /* Step-2: Initialize PDF documents - logical objects */
        Document my_pdf_report = new Document(PageSize.A4);
        PdfWriter.getInstance(my_pdf_report, new FileOutputStream("C:\\Users\\Durga\\Desktop\\Time_Table.pdf"));
        my_pdf_report.open();
        //we have four columns in our table

        PdfPTable table = new PdfPTable(10);
        //table.setWidthPercentage(100);
        //          table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

        String a[] = { "//////", "//////", "//////", "//////", "//////", "//////", "//////", "//////", "L", "U",
                "N", "C", "H", "//////", "//////", "//////", "//////", "//////", "//////" };

        int len = 1;
        table.addCell("Day");

        table.addCell("Branch");

        String s;

        for (int i = 0; i < line; i++) {
            int j = i;
            if (i == 5)
                table.addCell(a[0]);
            if (i >= 5)
                j = line - 1;
            table.addCell("Period" + (i) + " \n[" + start[j] + "-" + end[j] + "]");

        }

        table.getDefaultCell().setFixedHeight(70);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        while (query_set.next()) {
            String Day = query_set.getString("Day");
            table.addCell(Day);

            String Branch = query_set.getString("Branch");
            table.addCell(Branch);

            for (int i = 0; i < line; i++) {
                if (i == 5) {
                    table.addCell(a[len++]);

                    table.addCell(query_set.getString("slot" + (i + 1)) + "G1");
                } else if (i == 6) {
                    table.addCell(query_set.getString("slot" + (i + 1)) + "G2");
                } else
                    table.addCell(query_set.getString("slot" + (i + 1)));

            }
        }

        /* Attach report table to PDF */
        // my_pdf_report.add(my_report_table);  
        my_pdf_report.add(table);
        my_pdf_report.close();

        /* Close all DB related objects */
        query_set.close();
        stm2.close();
        //con2.close();     
        // }
        /*  catch(Exception e)
           {
           System.out.println(e);
            }*/
        stm1.close();
        con1.close();
    } catch (Exception e) {
        System.out.println(e);
    }

    if (Desktop.isDesktopSupported()) //Open pdf file
    {
        try {
            File myFile = new File("C:\\Users\\Durga\\Desktop\\Time_Table.pdf");
            Desktop.getDesktop().open(myFile);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        //System.out.println(ex);
    }
}

From source file:imprimer.java

public void openPDF() {

    Document document = new Document(PageSize.A4);
    try {/*from w w  w. j  a va2s  . com*/
        PdfWriter.getInstance(document, new FileOutputStream("imprimer test.pdf"));

        document.open();

        imagee(document);

        SimpleDateFormat td = new SimpleDateFormat("dd-MM-yyyy");
        java.util.Date now = new java.util.Date();
        String tdnow = td.format(now);
        Paragraph pa = new Paragraph("Attestation de travail",
                FontFactory.getFont(FontFactory.TIMES, 30, Font.UNDERLINE, BaseColor.DARK_GRAY));
        pa.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(pa);
        for (int i = 0; i < 3; i++) {
            document.add(new Paragraph(" "));
        }

        Paragraph p = new Paragraph(text,
                FontFactory.getFont(FontFactory.TIMES, 16, Font.NORMAL, BaseColor.DARK_GRAY));
        document.add(p);

        Paragraph time = new Paragraph("                Fait  Ouarzazate le : " + tdnow,
                FontFactory.getFont(FontFactory.TIMES, 17, Font.BOLD, BaseColor.DARK_GRAY));
        Paragraph a = new Paragraph("");
        Paragraph si = new Paragraph("                 Signature:",
                FontFactory.getFont(FontFactory.TIMES, 17, Font.BOLD, BaseColor.DARK_GRAY));

        time.setAlignment(Paragraph.ALIGN_CENTER);
        si.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(time);
        document.add(si);
        document.add(a);
        document.close();

        System.out.println("date2");
        /* Open Pdf */
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            desktop.open(new File("imprimer test.pdf"));
        } else {
            System.out.println("Open is not supported");
        }

        System.out.println("date");

    } catch (Exception ex) {
        System.out.println("qsdqs");
    }
}

From source file:imprimer.java

public void attestation_travail_prof() {

    Document document = new Document(PageSize.A4);
    try {//  ww w  .j a  v a  2  s.  c o  m
        PdfWriter.getInstance(document, new FileOutputStream("Attestation de travail Professeur.pdf"));
        document.open();

        imagee(document);
        SimpleDateFormat td = new SimpleDateFormat("dd-MM-yyyy");
        java.util.Date now = new java.util.Date();
        String tdnow = td.format(now);
        Paragraph pa = new Paragraph("Attestation de travail",
                FontFactory.getFont(FontFactory.TIMES, 30, Font.UNDERLINE, BaseColor.DARK_GRAY));
        pa.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(pa);
        for (int i = 0; i < 3; i++) {
            document.add(new Paragraph(" "));
        }

        Paragraph p = new Paragraph(text3,
                FontFactory.getFont(FontFactory.TIMES, 16, Font.NORMAL, BaseColor.DARK_GRAY));
        document.add(p);

        Paragraph time = new Paragraph("                Fait  Ouarzazate le : " + tdnow,
                FontFactory.getFont(FontFactory.TIMES, 17, Font.BOLD, BaseColor.DARK_GRAY));
        Paragraph a = new Paragraph("");
        Paragraph si = new Paragraph("                 Signature:",
                FontFactory.getFont(FontFactory.TIMES, 17, Font.BOLD, BaseColor.DARK_GRAY));

        time.setAlignment(Paragraph.ALIGN_CENTER);
        si.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(time);
        document.add(si);
        document.add(a);
        document.close();

        System.out.println("date2");
        /* Open Pdf */
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            desktop.open(new File("Attestation de travail Professeur.pdf"));
        } else {
            System.out.println("Open is not supported");
        }

        System.out.println("date");
    } catch (Exception ex) {

        System.out.println("qsdqs");
    }
}

From source file:imprimer.java

public void conje() {
    Document document = new Document(PageSize.A4);
    try {//from  ww w. j  av  a2  s.c om
        PdfWriter.getInstance(document, new FileOutputStream("conjee.pdf"));

        document.open();
        imagee(document);
        SimpleDateFormat td = new SimpleDateFormat("dd-MM-yyyy");
        java.util.Date now = new java.util.Date();
        String tdnow = td.format(now);
        Paragraph pa = new Paragraph("Dcision de cong",
                FontFactory.getFont(FontFactory.TIMES, 30, Font.UNDERLINE, BaseColor.DARK_GRAY));
        pa.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(pa);
        for (int i = 0; i < 4; i++) {
            document.add(new Paragraph(" "));
        }

        Paragraph p = new Paragraph(text2,
                FontFactory.getFont(FontFactory.TIMES, 14, Font.NORMAL, BaseColor.DARK_GRAY));
        document.add(p);
        Paragraph p3 = new Paragraph("DECIDE :",
                FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, BaseColor.DARK_GRAY));
        p3.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(p3);
        Paragraph p4 = new Paragraph("ARTICLE I Un cong dun .",
                FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLDITALIC, BaseColor.DARK_GRAY));
        document.add(p4);
        Paragraph p5 = new Paragraph(
                "           Est accord    :    \n" + "           C.I.N           :    \n"
                        + "           GRADE           :    \n" + "           Pour la priode :   ",
                FontFactory.getFont(FontFactory.TIMES, 15, Font.NORMAL, BaseColor.DARK_GRAY));
        document.add(p5);
        Paragraph p6 = new Paragraph("ARTICLE II",
                FontFactory.getFont(FontFactory.TIMES, 16, Font.BOLDITALIC, BaseColor.DARK_GRAY));
        document.add(p6);
        Paragraph p7 = new Paragraph(
                "Lintress(e) est autoris  quitter le territoire national durant la priode indique ci-dessus",
                FontFactory.getFont(FontFactory.TIMES, 18, Font.NORMAL, BaseColor.DARK_GRAY));
        document.add(p7);
        Paragraph p8 = new Paragraph("ARTICLE III",
                FontFactory.getFont(FontFactory.TIMES, 16, Font.BOLDITALIC, BaseColor.DARK_GRAY));
        document.add(p8);
        Paragraph p9 = new Paragraph(
                "Lintress(e) est tenu daviser le service du personnel de sa reprise de travail aprs expiration du  cong sus-vis.",
                FontFactory.getFont(FontFactory.TIMES, 18, Font.NORMAL, BaseColor.DARK_GRAY));
        document.add(p9);
        for (int i = 0; i < 4; i++) {
            document.add(new Paragraph(" "));
        }

        Paragraph time = new Paragraph(
                "             Cachet et signature                                        Fait  Ouarzazate le :"
                        + tdnow + "\n" + "\n",
                FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, BaseColor.DARK_GRAY));

        Paragraph si = new Paragraph("Signature du demandeur",
                FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, BaseColor.DARK_GRAY));
        time.setAlignment(Paragraph.ALIGN_LEFT);
        si.setAlignment(Paragraph.ALIGN_RIGHT);
        document.add(time);
        document.add(si);
        document.close();

        System.out.println("date2");
        /* Open Pdf */
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            desktop.open(new File("conjee.pdf"));
        } else {
            System.out.println("Open is not supported");
        }

        System.out.println("date");
    } catch (Exception ex) {

        System.out.println("qsdqs");
    }
}

From source file:imprimer.java

public void conje_exp() {
    Document document = new Document(PageSize.A4);
    try {//from   w  w w. ja va 2 s.c om
        PdfWriter.getInstance(document, new FileOutputStream("conjee_exp.pdf"));

        document.open();
        imagee(document);
        SimpleDateFormat td = new SimpleDateFormat("dd-MM-yyyy");
        java.util.Date now = new java.util.Date();
        String tdnow = td.format(now);
        Paragraph pa = new Paragraph("Dcision de cong",
                FontFactory.getFont(FontFactory.TIMES, 30, Font.UNDERLINE, BaseColor.DARK_GRAY));
        pa.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(pa);
        for (int i = 0; i < 4; i++) {
            document.add(new Paragraph(" "));
        }

        Paragraph p = new Paragraph(text2,
                FontFactory.getFont(FontFactory.TIMES, 14, Font.NORMAL, BaseColor.DARK_GRAY));
        document.add(p);
        Paragraph p3 = new Paragraph("DECIDE :",
                FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, BaseColor.DARK_GRAY));
        p3.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(p3);
        Paragraph p4 = new Paragraph("ARTICLE I",
                FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLDITALIC, BaseColor.DARK_GRAY));
        document.add(p4);
        Paragraph p5 = new Paragraph(
                "           Un cong Exceptionnel dune dure de jours\n"
                        + "           Est accord    :    \n" + "           C.I.N           :    \n"
                        + "           GRADE           :    \n" + "           Pour la priode :   ",
                FontFactory.getFont(FontFactory.TIMES, 15, Font.NORMAL, BaseColor.DARK_GRAY));
        document.add(p5);
        Paragraph p6 = new Paragraph("ARTICLE II",
                FontFactory.getFont(FontFactory.TIMES, 16, Font.BOLDITALIC, BaseColor.DARK_GRAY));
        document.add(p6);
        Paragraph p7 = new Paragraph(
                "Lintress(e) est autoris  quitter le territoire national durant la priode indique ci-dessus",
                FontFactory.getFont(FontFactory.TIMES, 18, Font.NORMAL, BaseColor.DARK_GRAY));
        document.add(p7);
        Paragraph p8 = new Paragraph("ARTICLE III",
                FontFactory.getFont(FontFactory.TIMES, 16, Font.BOLDITALIC, BaseColor.DARK_GRAY));
        document.add(p8);
        Paragraph p9 = new Paragraph(
                "Lintress(e) est tenu daviser le service du personnel de sa reprise de travail aprs expiration du  cong sus-vis.",
                FontFactory.getFont(FontFactory.TIMES, 18, Font.NORMAL, BaseColor.DARK_GRAY));
        document.add(p9);
        for (int i = 0; i < 4; i++) {
            document.add(new Paragraph(" "));
        }

        Paragraph time = new Paragraph(
                "             Cachet et signature                                        Fait  Ouarzazate le :"
                        + tdnow + "\n" + "\n",
                FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, BaseColor.DARK_GRAY));

        Paragraph si = new Paragraph("Signature du demandeur",
                FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, BaseColor.DARK_GRAY));
        time.setAlignment(Paragraph.ALIGN_LEFT);
        si.setAlignment(Paragraph.ALIGN_RIGHT);
        document.add(time);
        document.add(si);
        document.close();

        System.out.println("date2");
        /* Open Pdf */
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            desktop.open(new File("conjee_exp.pdf"));
        } else {
            System.out.println("Open is not supported");
        }

        System.out.println("date");
    } catch (Exception ex) {

        System.out.println("qsdqs");
    }
}

From source file:imprimer.java

public void quitter_territoire() {

    Document document = new Document(PageSize.A4);
    try {//from  w w w . j a  v a2 s  . c o m
        PdfWriter.getInstance(document, new FileOutputStream("quitter territoire.pdf"));

        document.open();
        imagee(document);

        document.open();
        imagee(document);
        SimpleDateFormat td = new SimpleDateFormat("dd-MM-yyyy");
        java.util.Date now = new java.util.Date();
        String tdnow = td.format(now);
        Paragraph pa = new Paragraph("Autorisation de quitter le territoire",
                FontFactory.getFont(FontFactory.TIMES, 30, Font.UNDERLINE, BaseColor.DARK_GRAY));
        pa.setAlignment(Paragraph.ALIGN_CENTER);
        document.add(pa);
        for (int i = 0; i < 4; i++) {
            document.add(new Paragraph(" "));
        }

        //      cell = new PdfPCell(new Phrase("Fusion de 2 cellules de la premire colonne"));
        //      cell.setRowspan(2);
        //      table.addCell(cell);
        PdfPTable table = new PdfPTable(2);
        PdfPCell cell = new PdfPCell();
        //contenu du tableau.
        table.addCell("\nNom:\n\n");
        table.addCell("\n\n");
        table.addCell("\nPrenom:\n\n");
        table.addCell("\n\n");
        table.addCell("\nGRADE :\n\n");
        table.addCell("\n\n");
        table.addCell("\nADRESSE PERSONNELLE :\n\n");
        table.addCell("\n\n");
        table.addCell("\nAFFECTATION :\n\n");
        table.addCell("\n\n");

        cell = new PdfPCell(
                new Phrase("\nJai  lhonneur de solliciter une autorisation  dabsence.\n\n"));
        cell.setColspan(2);
        table.addCell(cell);

        table.addCell("\nDU:\n\n");
        table.addCell("\n\n");
        table.addCell("\nAU:\n\n");
        table.addCell("\n\n");
        table.addCell("\nMOTIF :\n\n");
        table.addCell("\n\n");
        table.addCell("\nAVIS DU  CHEF \nDETABLISSEMENT:\n\n");
        table.addCell("\n\nFAVORABLE.def\n\n");
        cell = new PdfPCell(new Phrase("\nFait  Ouarzazate le :" + tdnow + "\n\n"));
        cell.setColspan(2);

        table.addCell(cell);
        table.addCell("Signature du  demandeur\n\n\n\n\n\n\n\n\n");
        table.addCell("Cachet  et  signature\n\n\n\n\n\n\n\n");
        document.add(table);
        document.close();
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            desktop.open(new File("quitter territoire.pdf"));
        } else {
            System.out.println("Open is not supported");
        }

    } catch (Exception ex) {
        System.out.print("catch");
    }
}

From source file:Servlet3.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from   ww  w.  java2  s .  c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        System.out.println("inside servlet");
        String a = request.getParameter("countryf");
        String c = request.getParameter("submit");
        String b = request.getParameter("paramf");

        //code added by Murugappan

        String CurentUID = request.getParameter("UIDvalue2f");
        String URLRequest = request.getRequestURL().append('?').append(request.getQueryString()).toString();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy");
        String date1 = cal.getTime().toString();

        System.out.println("inside servlet");

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con = DriverManager.getConnection("jdbc:odbc:server");

        //iserting data to UserActivity table
        Statement sthistoryinsert3 = con.createStatement();
        String insertstring = "Insert into UserActivity values('" + CurentUID + "','" + date1
                + "','Future Data Forecast','" + a + "','" + b + "','" + URLRequest + "')";
        sthistoryinsert3.executeUpdate(insertstring);
        sthistoryinsert3.close();
        System.out.println("\n Step 1");
        Statement st = con.createStatement();
        //  Statement st2 = con.createStatement();
        XYSeriesCollection dataset = new XYSeriesCollection();
        XYSeries series = new XYSeries(b);

        String query = "SELECT [2000],[2012] FROM country where CountryName='" + a + "' AND SeriesName='" + b
                + "'";
        System.out.println(query);
        ResultSet rs = st.executeQuery(query);
        if (rs == null)
            System.out.println("\n no rows ");
        else
            System.out.println("Rows present ");
        rs.next();

        Double start = Double.parseDouble(rs.getString(1));
        Double end = Double.parseDouble(rs.getString(2));
        Double period = 13.0;
        Double growth = Math.pow((end / start), (1 / period)) - 1;
        System.out.println("growth percentage =" + growth);
        rs.close();
        String query2 = "select [2011],[2012] from country where CountryName='" + a + "' AND SeriesName='" + b
                + "'";
        rs = st.executeQuery(query2);
        rs.next();
        series.add(2011, Double.parseDouble(rs.getString(1)));
        Double second = Double.parseDouble(rs.getString(2));
        series.add(2012, second);

        Double growthvalue = second + (second * growth);

        series.add(2013, growthvalue);
        for (int i = 2014; i <= 2016; i++) {
            System.out.println("actual growth value = " + growthvalue);
            series.add((i++), (growthvalue + growthvalue * growth));
            growthvalue = growthvalue + growthvalue * growth;
        }
        rs.close();
        dataset.addSeries(series);
        DecimalFormat format_2Places = new DecimalFormat("0.00");
        growth = growth * 100;
        growth = Double.valueOf(format_2Places.format(growth));
        JFreeChart chart = ChartFactory.createXYLineChart(
                "Energy forecasting for " + a + " based on " + b + " with growth value estimated at " + growth
                        + "% ",
                "Year", "Energy consumed in millions", dataset, PlotOrientation.VERTICAL, true, true, false);
        // JFreeChart chart1=ChartFactory.createLineChart("World population Growth","Year","population in millions",dataSet1,PlotOrientation.VERTICAL,true,true,false);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        chart.setBackgroundPaint(Color.white);
        final XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setDomainGridlinesVisible(true);
        plot.setRangeGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.black);
        plot.setRangeGridlinePaint(Color.black);

        final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(2, false);
        renderer.setSeriesShapesVisible(2, false);
        plot.setRenderer(renderer);

        /* We have to insert this colored Pie Chart into the PDF file using iText now */

        if (c.equals("View Graph in Browser")) {
            ChartUtilities.writeChartAsPNG(bos, chart, 700, 500);
            response.setContentType("image/png");
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(bos.toByteArray());
            out.flush();
            out.close();
        }

        else {
            int width = 640; /* Width of our chart */
            int height = 480; /* Height of our chart */
            Document PieChart = new Document(new com.itextpdf.text.Rectangle(width, height));
            java.util.Date date = new java.util.Date();
            String chartname = "My_Colored_Chart" + date.getTime() + ".pdf";
            PdfWriter writer = PdfWriter.getInstance(PieChart, new FileOutputStream(chartname));
            PieChart.open();
            /* Add some Metadata to identify document later */
            PieChart.addTitle("How to color your Pie Chart and embed in a PDF file using iText");
            PieChart.addAuthor("Thinktibits");
            PieChart.addKeywords("iText,Color PieChart,JFreeChart,PDF,Example Tutorial");
            PdfContentByte Add_Chart_Content = writer.getDirectContent();
            PdfTemplate template_Chart_Holder = Add_Chart_Content.createTemplate(width, height);
            Graphics2D Graphics_Chart = template_Chart_Holder.createGraphics(width, height,
                    new DefaultFontMapper());
            Rectangle2D Chart_Region = new Rectangle2D.Double(0, 0, 540, 380);
            chart.draw(Graphics_Chart, Chart_Region);
            Graphics_Chart.dispose();
            Add_Chart_Content.addTemplate(template_Chart_Holder, 0, 0);
            PieChart.close();
            //PrintWriter out = response.getWriter();
            //out.println("<!DOCTYPE html> <html> <body> <a href =file:///C:/apache-tomcat-8.0.12/bin/"+chartname+" download=newFileName> Download your file here </a> </body></html>");
            PdfReader reader = new PdfReader(chartname);
            PdfStamper stamper = null;
            try {
                stamper = new PdfStamper(reader, bos);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            try {
                stamper.close();
            } catch (DocumentException e) {

                e.printStackTrace();
            }

            // set some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setContentType("application/pdf");
            response.setContentLength(bos.size());

            OutputStream os = response.getOutputStream();
            bos.writeTo(os);
            os.flush();
            os.close();
        }
    }

    catch (Exception i) {
        i.printStackTrace();
    }

}

From source file:adams.flow.transformer.pdfproclet.PDFGenerator.java

License:Open Source License

/**
 * Opens the document for writing./*ww w.  j  a va2  s  . c  o  m*/
 *
 * @throws Exception   if opening fails
 */
public void open() throws Exception {
    resetState();
    if (m_PageOrientation == PageOrientation.PORTRAIT)
        m_Document = new Document(determinePageSize());
    else
        m_Document = new Document(determinePageSize().rotate());
    m_Stream = new FileOutputStream(m_Output.getAbsoluteFile());
    m_Writer = PdfWriter.getInstance(m_Document, m_Stream);
    m_Document.open();
    m_Document.addCreationDate();
    m_Document.addCreator(Environment.getInstance().getProject());
    m_Document.addAuthor(System.getProperty("user.name"));
    m_State = new DocumentState();

    if (isLoggingEnabled())
        getLogger().info("Opening document: " + m_Output);
}

From source file:adams.flow.transformer.pdfproclet.PDFGenerator.java

License:Open Source License

/**
 * Opens the document for appending content.
 *
 * @throws Exception   if opening fails//  w w w .ja  va 2  s .  c  o  m
 */
public void append() throws Exception {
    PdfReader reader;
    File tmpFile;
    int i;
    PdfImportedPage page;
    PdfContentByte cb;

    if (isLoggingEnabled())
        getLogger().info("Appending document: " + m_Output);

    resetState();

    tmpFile = TempUtils.createTempFile("adams", ".pdf");
    if (tmpFile.exists()) {
        if (!tmpFile.delete())
            throw new IllegalStateException("Failed to delete temporary PDF file '" + tmpFile + "'!");
    }
    if (!FileUtils.copy(m_Output, tmpFile))
        throw new IllegalStateException(
                "Failed to move original PDF file '" + m_Output + "' to '" + tmpFile + "'!");

    reader = new PdfReader(tmpFile.getAbsolutePath());
    if (reader.getNumberOfPages() > 0) {
        m_Document = new Document(reader.getPageSize(1));
    } else {
        if (m_PageOrientation == PageOrientation.PORTRAIT)
            m_Document = new Document(determinePageSize());
        else
            m_Document = new Document(determinePageSize().rotate());
    }
    m_Stream = new FileOutputStream(m_Output.getAbsoluteFile());
    m_Writer = PdfWriter.getInstance(m_Document, m_Stream);
    m_Document.open();
    m_Document.addCreationDate();
    m_Document.addCreator(Environment.getInstance().getProject());
    m_Document.addAuthor(System.getProperty("user.name"));
    m_State = new DocumentState();
    cb = m_Writer.getDirectContent();
    for (i = 0; i < reader.getNumberOfPages(); i++) {
        page = m_Writer.getImportedPage(reader, i + 1);
        m_Document.newPage();
        cb.addTemplate(page, 0, 0);
    }
}