Example usage for com.itextpdf.text.pdf PdfReader PdfReader

List of usage examples for com.itextpdf.text.pdf PdfReader PdfReader

Introduction

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

Prototype

public PdfReader(final PdfReader reader) 

Source Link

Document

Creates an independent duplicate.

Usage

From source file:example.Example.java

public static void main(String[] args) throws IOException {

    String line, prev = "";

    Example example = new Example();
    String[] exclusions = { "100550310 - Food Technology", "100551710 - Oil and Paints Technology",
            "100552410 - Paper and Pulp Technology", "100552710 - Petro Chemical Engineering" };
    //  File file=new File("/home/sachin/Downloads/2014ENGG_Cutoff_CAP1.txt");
    PdfReader reader = new PdfReader("/home/sachin/Downloads/2014ENGG_Cutoff_CAP2.pdf");
    //  System.out.println("This PDF has " + reader.getNumberOfPages() + " pages.");

    for (int i = 1; i < reader.getNumberOfPages(); i += 1) {
        String page = PdfTextExtractor.getTextFromPage(reader, i);
        InputStream is = new ByteArrayInputStream(page.getBytes());
        // read it with BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        int count = 1;
        while ((line = br.readLine()) != null) {
            if (count == 7) {

                //  System.out.println("substring is"+line.substring(6));
                //   System.out.println("Prev college is"+example.getPrevCollege());
                if (!line.substring(6).trim().equals(example.getPrevCollege())) {
                    // System.out.println("College Name" + line);
                    if (example.getPrevCollege() != "") {
                        example.addObject(example.getSinglecollegedata());
                    }/*from w w  w . j  a v a  2s . c om*/
                    example.setPrevCollege(line.substring(6).trim());
                    CollegeDataObject object = new CollegeDataObject();
                    object.setCollegeName(line.substring(6).trim());
                    int temp;
                    if ((temp = line.substring(6).trim().split(",").length) > 1) {
                        object.setCity(line.substring(6).trim().split(",")[temp - 1].trim());
                        object.setCollegeName(line.substring(6).trim()
                                .replace(line.substring(6).trim().split(",")[temp - 1].trim(), "").trim()
                                .replace(",", "").trim());
                    }
                    example.setSinglecollegedata(object);
                } else {

                }
            }
            if (count == 8) {

                // System.out.print("Branch name" + line);
                if (!line.contains("NT1") && !line.contains("NT2") && !line.contains("NT3")
                        && !line.contains("OBC")) {
                    if (example.getPrevBranch() != "") {
                        example.getSinglecollegedata().AddObject(example.getCastDataObject());
                        CastDataObject object = new CastDataObject();
                        object.setBranchName(line.substring(11).trim());
                        example.setPrevBranch(line.substring(11).trim());
                        example.setCastDataObject(object);
                    } else {
                        CastDataObject object = new CastDataObject();
                        object.setBranchName(line.substring(11).trim());
                        example.setCastDataObject(object);
                        example.setPrevBranch(line.substring(11).trim());
                    }
                } else {
                    break;
                }
            }
            if (count == 10) {
                // System.out.println("open rank"+line);

                if (line.contains("GOPENO") || line.contains("GOPENH")) {
                    //                        if (isNumeric(line)) {
                    //                            if (line.trim().equals(null))
                    //                                line = "0";
                    if (line.split(" ").length > 1) {
                        if (isNumeric(line.split(" ")[1].trim()))
                            example.getCastDataObject().setOpen(line.split(" ")[1].trim());
                    } else {
                        line = br.readLine();
                        if (line.split(" ").length > 1) {
                            if (isNumeric(line.split(" ")[1].trim()))
                                example.getCastDataObject().setOpen(line.split(" ")[1].trim());
                        } else {
                            if (isNumeric(line.trim()))
                                example.getCastDataObject().setOpen(line.trim());
                        }
                    }
                    // }
                }

                while ((line = br.readLine()) != null) {
                    if (line.contains("GSCO") || line.contains("GSCH")) {
                        //                            if (isNumeric(line)) {
                        //                                if (line.trim().equals(null))
                        //                                    line = "0";
                        if (line.split(" ").length > 1) {
                            if (isNumeric(line.split(" ")[1].trim()))
                                example.getCastDataObject().setSc(line.split(" ")[1].trim());
                        } else {
                            line = br.readLine();
                            if (line.split(" ").length > 1) {
                                if (isNumeric(line.split(" ")[1].trim()))
                                    example.getCastDataObject().setSc(line.split(" ")[1].trim());
                            } else {
                                if (isNumeric(line.trim()))
                                    example.getCastDataObject().setSc(line.trim());
                            }
                        }

                        //}
                    }
                    if (line.contains("GSTO") || line.contains("GSTH")) {
                        //                            if (isNumeric(line)) {
                        //                                if (line.trim().equals(null))
                        //                                    line = "0";
                        if (line.split(" ").length > 1) {
                            if (isNumeric(line.split(" ")[1].trim()))
                                example.getCastDataObject().setSt(line.split(" ")[1].trim());
                        } else {
                            line = br.readLine();
                            if (line.split(" ").length > 1) {
                                if (isNumeric(line.split(" ")[1].trim()))
                                    example.getCastDataObject().setSt(line.split(" ")[1].trim());
                            } else {
                                if (isNumeric(line.trim()))
                                    example.getCastDataObject().setSt(line.trim());
                            }
                        }
                        //}
                    }
                    if (line.contains("GVJO") || line.contains("GVJH")) {
                        //                            if (isNumeric(line)) {
                        //                                if (line.trim().equals(null))
                        //                                    line = "0";

                        if (line.split(" ").length > 1) {
                            if (isNumeric(line.split(" ")[1].trim()))
                                example.getCastDataObject().setVj(line.split(" ")[1].trim());
                        } else {
                            line = br.readLine();
                            if (line.split(" ").length > 1) {
                                if (isNumeric(line.split(" ")[1].trim()))
                                    example.getCastDataObject().setVj(line.split(" ")[1].trim());
                            } else {
                                if (isNumeric(line.trim()))
                                    example.getCastDataObject().setVj(line.trim());
                            }
                        }
                        //System.out.println("Line is"+line.trim());

                        //  }
                    }
                    if (line.contains("GNT1O") || line.contains("GNT1H")) {
                        //                            if (isNumeric(line)) {
                        //                                if (line.trim().equals(null))
                        //                                    line = "0";
                        if (line.split(" ").length > 1) {
                            if (isNumeric(line.split(" ")[1].trim()))
                                example.getCastDataObject().setNt1(line.split(" ")[1].trim());
                        } else {
                            line = br.readLine();
                            if (line.split(" ").length > 1) {
                                if (isNumeric(line.split(" ")[1].trim()))
                                    example.getCastDataObject().setNt1(line.split(" ")[1].trim());
                            } else {

                                if (isNumeric(line.trim()))
                                    example.getCastDataObject().setNt1(line.trim());
                            }
                        }
                        //                            }

                    }
                    if (line.contains("GNT2O") || line.contains("GNT2H")) {
                        //                            if (isNumeric(line)) {
                        //                                if (line.trim().equals(null))
                        //                                    line = "0";

                        if (line.split(" ").length > 1) {
                            if (isNumeric(line.split(" ")[1].trim()))
                                example.getCastDataObject().setNt2(line.split(" ")[1].trim());
                        } else {
                            line = br.readLine();
                            if (line.split(" ").length > 1) {
                                if (isNumeric(line.split(" ")[1].trim()))
                                    example.getCastDataObject().setNt2(line.split(" ")[1].trim());
                            } else {
                                if (isNumeric(line.trim()))
                                    example.getCastDataObject().setNt2(line.trim());
                            }
                        }
                        //                            }

                    }
                    if (line.contains("GNT3O") || line.contains("GNT3H")) {
                        //                            if (isNumeric(line)) {
                        //                                if (line.trim().equals(null))
                        //                                    line = "0";
                        if (line.split(" ").length > 1) {
                            if (isNumeric(line.split(" ")[1].trim()))
                                example.getCastDataObject().setNt3(line.split(" ")[1].trim());
                        } else {
                            line = br.readLine();
                            if (line.split(" ").length > 1) {
                                if (isNumeric(line.split(" ")[1].trim()))
                                    example.getCastDataObject().setNt3(line.split(" ")[1].trim());
                            } else {
                                if (isNumeric(line.trim()))
                                    example.getCastDataObject().setNt3(line.trim());
                            }
                        }
                        //   }

                    }
                    if (line.contains("GOBCO") || line.contains("GOBCH")) {
                        //                            if (isNumeric(line)) {
                        //                                if (line.trim().equals(null))
                        //                                    line = "0";
                        if (line.split(" ").length > 1) {
                            if (isNumeric(line.split(" ")[1].trim()))
                                example.getCastDataObject().setOBC(line.split(" ")[1].trim());
                        } else {
                            line = br.readLine();
                            if (line.split(" ").length > 1) {
                                if (isNumeric(line.split(" ")[1].trim()))
                                    example.getCastDataObject().setOBC(line.split(" ")[1].trim());
                            } else {
                                if (isNumeric(line.trim()))
                                    example.getCastDataObject().setOBC(line.trim());
                            }
                        }
                        //    }
                    }

                }

            }
            //                if (count == 14) {
            //                    //   System.out.println("sc rank is"+line);
            //                    if (isNumeric(line)) {
            //                        if (line.trim().equals(null))
            //                            line = "0";
            //                        example.getCastDataObject().setSc(line.trim());
            //                    }
            //
            //
            //                }
            //                if (count == 17) {
            //                    // System.out.println("st rank is"+line);
            //                    if (isNumeric(line)) {
            //                        if (line.trim().equals(null))
            //                            line = "0";
            //                        example.getCastDataObject().setSt(line.trim());
            //
            //                    }
            //                }
            //                if (count == 20) {
            //                    if (isNumeric(line)) {
            //                        if (line.trim().equals(null))
            //                            line = "0";
            //                        if (prev.equals("GVJO")) {
            //                            //   System.out.println("VJ rank is"+line);
            //                            example.getCastDataObject().setVj(line.trim());
            //                            line = br.readLine();
            //                            line = br.readLine();
            //                            line = br.readLine();
            //                            count += 3;
            //                            //   System.out.println("NT1 rank is"+line);
            //                            example.getCastDataObject().setNt1(line.trim());
            //
            //                        } else {
            //                            //   System.out.println("NT1 rank is" + line);
            //                            example.getCastDataObject().setNt1(line.trim());
            //                            count += 3;
            //                        }
            //                    }
            //
            //                }
            //            if (count==23)
            //            {
            //                System.out.println("NT1 rank is"+line);
            //            }
            //                if (count == 26) {
            //
            //                    if (isNumeric(line)) {
            //                        //  System.out.println("NT2 rank is"+line);
            //                        if (line.trim().equals(null))
            //                            line="0";
            //                        example.getCastDataObject().setNt2(line.trim());
            //                    }
            //                }
            //                if (count == 29) {
            //
            //                        if (prev.equals("GNT3O")) {
            //                            //   System.out.println("NT3 rank is" + line);
            //                            if (isNumeric(line)) {
            //                                if (line.trim().equals(null))
            //                                    line="0";
            //                                example.getCastDataObject().setNt3(line.trim());
            //                                line = br.readLine();
            //                                line = br.readLine();
            //                                line = br.readLine();
            //                                //    System.out.println("OBC rank is" + line);
            //                            }
            //                            if (isNumeric(line.split(" ")[0])) {
            //                                if (line.split(" ")[0].trim().equals(null))
            //                                    line="0";
            //                                example.getCastDataObject().setOBC(line.split(" ")[0].trim());
            //                            }
            //                        } else {
            //                            //    System.out.println("OBC rank is" + line);
            //                            if (isNumeric(line.split(" ")[0])) {
            //                                if (line.split(" ")[0].trim().equals(null))
            //                                    line = "0";
            //                                example.getCastDataObject().setOBC(line.split(" ")[0].trim());
            //                            }
            //                        }

            //               }
            count++;
            prev = line;
        }
    }
    //                if (count==7)
    //                {
    //                    if (!line.substring(6).equals(example.getPrevCollege()))
    //                    System.out.println("College name is"+line.substring(6));
    //                    example.setPrevCollege(line.substring(6));
    //
    //                }
    //                if (count==8)
    //                {
    //                    if (!line.contains("NT1") && !line.contains("NT2") && !line.contains("NT3") && !line.contains("OBC"))
    //                    System.out.println("Branch name is"+line.substring(12));
    //                }
    //                count++;
    //                System.out.println(line);
    //            }
    //        }

    //example.getSinglecollegedata().AddObject(example.getCastDataObject());
    example.getSinglecollegedata().AddObject(example.getCastDataObject());
    example.addObject(example.getSinglecollegedata());

    //  System.out.println("Size is" + example.getObject().size());

    //        for (CollegeDataObject collegeDataObject :example.getObject()) {
    //            System.out.println("College Name is " + collegeDataObject.getCollegeName());
    //            for (CastDataObject object : collegeDataObject.getObjects()) {
    //                System.out.println("Branch name is " + object.getBranchName());
    //               // if (isNumeric(object.getOpen()))
    //                System.out.println("Open rank is " + object.getOpen());
    //               // if (isNumeric(object.getSc()))
    //                System.out.println("SC rank is " + object.getSc());
    //              //  if (isNumeric(object.getSt()))
    //                System.out.println("ST rank is " + object.getSt());
    //              //  if (isNumeric(object.getVj()))
    //                System.out.println("VJ rank is " + object.getVj());
    //              //  if (isNumeric(object.getNt1()))
    //                System.out.println("NT1 rank is " + object.getNt1());
    //              //  if (isNumeric(object.getNt2()))
    //                System.out.println("NT2 rank is " + object.getNt2());
    //              //  if (isNumeric(object.getNt3()))
    //                System.out.println("NT3 rank is " + object.getNt3());
    //              //  if (isNumeric(object.getOBC()))
    //                System.out.println("OBC rank is " + object.getOBC());
    //            }
    //        }

    //BufferedReader reader=new Bufferef ll)
    //{
    //   System.out.println(line);
    //}

    MongoClient mongo1 = new MongoClient("localhost");
    MongoDatabase db = mongo1.getDatabase("CollegeFinder");
    MongoCollection<Document> coll = db.getCollection("cap_round2");
    for (CollegeDataObject collegeDataObject : example.getObject()) {
        Document college = new Document();
        college.append("college_name", collegeDataObject.getCollegeName());
        college.append("city", collegeDataObject.getCity());
        System.out.println(collegeDataObject.getCollegeName() + " City " + collegeDataObject.getCity());
        List<Document> branches = new ArrayList<>();
        for (CastDataObject object : collegeDataObject.getObjects()) {
            Document branch = new Document();
            branch.append("branch_name", object.getBranchName());
            branch.append("open", Integer.valueOf(object.getOpen()));
            branch.append("sc", Integer.valueOf(object.getSc()));
            branch.append("st", Integer.valueOf(object.getSt()));
            branch.append("vj", Integer.valueOf(object.getVj()));
            branch.append("nt1", Integer.valueOf(object.getNt1()));
            branch.append("nt2", Integer.valueOf(object.getNt2()));
            branch.append("nt3", Integer.valueOf(object.getNt3()));
            branch.append("obc", Integer.valueOf(object.getOBC()));
            branches.add(branch);
        }
        college.append("Branch", branches);
        coll.insertOne(college);
    }
    //                m.append("name","sachin");
    //                m.append("year", "first year");
    //                m.append("branch", "seond year");
    //                List <Document> list=new ArrayList<>();
    //                list.add(m);
    //                Document s=new Document();
    //                s.append("name", "Arjun");
    //                s.append("year", "first year");
    //                s.append("branch", "seond year");
    //                list.add(s);
    //                Document parent=new Document();
    //                parent.append("embed", list);
    //                coll.insertOne(parent);

    //              p
    //                List <Document> list=new ArrayList<>();
    //                for (int i=0;i<10;i++)
    //                {
    //                    list.add(new Document(m));
    //                }
    //                coll.insertMany(list);
    //     coll.insertOne(parent);

    // TODO code application logic here

    //              coll.find();

}

From source file:ExternalForms.Browser.java

public String getDataFromPDF() {
    String all_inputs = ""; //concatenated string of inputs in order
    try {//  w  w w.  ja v a 2s. c  om

        final int MAX_VARIABLES = connect.getFormVarCount(formID); //get from db
        System.out.println("MAX VARIABLES: " + MAX_VARIABLES);
        //----------------------------------------------------------

        final String DELIMITER = "~"; //pwede mani i-change
        dumbNavigate();
        PdfReader pdfTemplate = new PdfReader(documentsPath + "\\" + formName + ".pdf");
        FileOutputStream fileOutputStream = new FileOutputStream(
                dirPrintables.getAbsolutePath() + "\\" + formName + ".pdf");
        PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
        //System.out.println("TRY: " + stamper.getAcroFields().getField("1"));
        stamper.setFormFlattening(true);
        System.out.println("Display Inputs Per Variable and Concatenate after\n");

        //change textFields--------------------------------------------------------------------
        for (int var = 1; var <= MAX_VARIABLES; var++) {
            String input_from_pdf_field = stamper.getAcroFields().getField("" + var); //get field input using variable
            System.out.println("Input #" + var + " = " + input_from_pdf_field); //display
            all_inputs += DELIMITER + input_from_pdf_field; //concatenate
        }
        stamper.close();
        pdfTemplate.close();
        //--------------------------------------------------------------------------------------
        System.out.println("\nConcatenated String to Store to DB\n");

        System.out.println("\n" + all_inputs + "\n");

        try {

            File pdfFile = new File(documentsPath + "\\" + formName + ".pdf");
            if (pdfFile.exists()) {
                if (pdfFile.delete()) {
                    //Desktop.getDesktop().open(pdfFile);
                    System.out.println("Form in Documents Deleted");
                }
            } else {
                System.out.println("File to delete in My Documents does not exists!");
            }

        } catch (Exception ex) {
        }

        b.setVisible(false);
        c.setText("Done");
        j.navigate(dirPrintables.getAbsolutePath() + "\\" + formName + ".pdf");
        System.out.println(dirPrintables.getAbsolutePath() + "\\" + formName + ".pdf");

    } catch (IOException | DocumentException ex) {
        Logger.getLogger(Browser.class.getName()).log(Level.SEVERE, null, ex);
    }

    return all_inputs;
}

From source file:ExternalForms.Browser.java

public void setDataToPdf(String fName, String formEntryID) {
    try {//from  ww w  .j a v a 2s.  c om

        String all_inputs = connect.getFormEntryFormData(formEntryID); //assuming na gusto ka magbutang ug tulo ka value sa first 3 fields

        final String DELIMITER = "~";

        System.out.println("\nSplit Concatenated String and Display\n");
        String split_inputs[] = all_inputs.split(DELIMITER);

        PdfReader pdfTemplate = new PdfReader(
                dirTemplates.getAbsolutePath() + "\\" + (formName = fName) + ".pdf");

        //navigate("temp", "x");
        postFix = checkIfSameNameFileExists(this.dirPrintables, formName + ".pdf");
        System.out.println("FILENAME TO FETCH: " + formName + postFix + "|");

        FileOutputStream fileOutputStream = new FileOutputStream(
                dirPrintables.getAbsolutePath() + "\\" + formName + postFix + ".pdf");
        PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
        stamper.setFormFlattening(true);

        //change textFields--------------------------------------------------------------------
        for (int var = 1; var < split_inputs.length; var++) {
            stamper.getAcroFields().setField("" + var, split_inputs[var]); //get field input using variable
            System.out.println("Input #" + var + " = " + split_inputs[var]); //display
        }
        //--------------------------------------------------------------------------------------

        stamper.close();
        pdfTemplate.close();

        b.setVisible(false);
        c.setText("Done");
        j.navigate(dirPrintables.getAbsolutePath() + "\\" + formName + postFix + ".pdf");
        this.setVisible(true);
        System.out.println(dirPrintables.getAbsolutePath() + "\\" + formName + postFix + ".pdf");

    } catch (IOException | DocumentException ex) {
        Logger.getLogger(Browser.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ExternalNonFormClasses.RequestFormBrowser.java

public void disableFormOnly(boolean choice) { //save data
    try {/*w w w .  j  av a2s  .c  om*/
        PdfReader pdfTemplate = new PdfReader(
                "C:\\Users\\mrRNBean\\Documents\\NetBeansProjects\\BRMS_V2\\build\\templates\\" + form_name
                        + ".pdf");
        FileOutputStream fileOutputStream = new FileOutputStream(
                "C:\\Users\\mrRNBean\\Documents\\NetBeansProjects\\BRMS_V2\\build\\printables\\" + form_name
                        + ".pdf");
        PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);
        stamper.setFormFlattening(true);

        if (choice) { //post-request
            //manipiulate form fields--------------------------------------------------------------------
            stamper.getAcroFields().setField("12", "CHORVES");
            //String x = stamper.getAcroFields().getField("province");
            //-------------------------------------------------------------------------------------------

            //get field form_vars from form tb
            //slice data with delimiter and store to array
            //fetch array
            //use as basis for loop
            //get field using variable name in each array entry
            //every field entry should be added to a string concatenation
            //save string concatenation and form in "printables/" to FormRequest.tb
        }

        stamper.close();
        pdfTemplate.close();
    } catch (IOException | DocumentException ex) {
        Logger.getLogger(RequestFormBrowser.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:eyeofthetiger.utils.PDFDossardGenerator.java

public void createPdf(List<Participant> participants, OutputStream out) throws IOException, DocumentException {
    sortParticipants(participants);//from w w w.j ava 2  s .c o m

    Document document = new Document(PageSize.A4.rotate());
    float margin = CentimeterToUserSpace(marginCm);
    document.setMargins(margin, margin, margin, margin);
    PdfWriter writer = PdfWriter.getInstance(document, out);
    document.open();
    PdfContentByte cb = writer.getDirectContent();

    PdfReader pdfBackgroundReader = null;
    PdfImportedPage backgroundPage = null;
    if (pdfBackground != null && (new File(pdfBackground)).exists() && (new File(pdfBackground)).isFile()) {
        pdfBackgroundReader = new PdfReader(pdfBackground);
        backgroundPage = writer.getImportedPage(pdfBackgroundReader, 1);
    }

    float documentTop = document.top();
    float documentBottom = document.bottom();
    float documentHeight = documentTop - documentBottom;
    float left = document.left();
    float right = document.right();
    float width = right - left;
    float height = documentTop - documentBottom;

    //cb.rectangle(left, documentBottom, width, documentHeight);
    //cb.stroke();

    boolean logoLeftExist = (new File(logoLeft)).exists() && (new File(logoLeft)).isFile();
    boolean logoRightExist = (new File(logoRight)).exists() && (new File(logoRight)).isFile();

    float imgLeftRight = left;
    float imgLeftBottom = documentTop;
    float imgRightLeft = right;
    float imgRighBottom = documentTop;
    Image imgLeft = null;
    Image imgRight = null;
    if (exportLogos) {
        if (logoLeftExist) {
            imgLeft = Image.getInstance(logoLeft);
            float h = imgLeft.getHeight();
            float w = imgLeft.getWidth();
            float nw = width * logoLeftWidth;
            float nh = (h / w) * nw;
            imgLeft.scaleAbsolute(nw, nh);
            //img.scaleAbsoluteHeight(img.getScaledWidth() / xyRatio);
            imgLeft.setAbsolutePosition(left, documentTop - imgLeft.getScaledHeight());
            //cb.addImage(img);   

            imgLeftRight = imgLeft.getAbsoluteX() + imgLeft.getScaledWidth();
            imgLeftBottom = imgLeft.getAbsoluteY();
        }

        if (logoRightExist) {
            imgRight = Image.getInstance(logoRight);
            float h = imgRight.getHeight();
            float w = imgRight.getWidth();
            float nw = width * logoRightWidth;
            float nh = (h / w) * nw;
            imgRight.scaleAbsolute(nw, nh);
            imgRight.setAbsolutePosition(right - imgRight.getScaledWidth(),
                    documentTop - imgRight.getScaledHeight());
            //cb.addImage(imgRight);
            imgRightLeft = imgRight.getAbsoluteX();
            imgRighBottom = imgRight.getAbsoluteY();
        }

    }

    float nameHeightPercent = 0.35f;
    float groupHeightPercent = 0.25f;

    float nameTop = documentTop;
    float nameBottom = nameTop;
    if (exportName) {
        nameBottom = nameTop - (documentHeight * nameHeightPercent);
    }
    float groupeTop = nameBottom;
    float groupeBottom = nameBottom;
    if (exportGroup) {
        groupeBottom = groupeTop - (documentHeight * groupHeightPercent);
    }
    float barcodeTop = groupeBottom;
    float barcodeBottom = documentBottom;

    ColumnText columnText;

    for (Participant participant : participants) {

        if (backgroundPage != null) {
            //cb.addTemplate(backgroundPage, 1f, 0, 0, 1, 0, 0); //TODO
            cb.addTemplate(backgroundPage, 0, 0);
        }

        float nameFontSize = 65f;
        float groupFontSize = 45f;
        float renseignementFontSize = 35f;

        if (imgLeft != null) {
            cb.addImage(imgLeft);
        }
        if (imgRight != null) {
            cb.addImage(imgRight);
        }

        if (exportName) {
            columnText = new ColumnText(cb);
            columnText.setAlignment(Rectangle.ALIGN_CENTER);

            if (imgLeftRight != -1 && imgLeftBottom != -1) {
                float[] leftBorder = null;
                if (imgLeftBottom < nameBottom) {
                    leftBorder = new float[] { imgLeftRight, nameTop, imgLeftRight, nameBottom, left,
                            nameBottom };
                } else {
                    leftBorder = new float[] { imgLeftRight, nameTop, imgLeftRight, imgLeftBottom, left,
                            imgLeftBottom, left, nameBottom };
                }

                float[] rightBorder = null;
                if (imgRighBottom < nameBottom) {
                    rightBorder = new float[] { imgRightLeft, nameTop, imgRightLeft, nameBottom, right,
                            nameBottom };
                } else {
                    rightBorder = new float[] { imgRightLeft, nameTop, imgRightLeft, imgRighBottom, right,
                            imgRighBottom, right, nameBottom };
                }

                columnText.setColumns(leftBorder, rightBorder);
            } else {
                columnText.setSimpleColumn(left, nameTop, right, nameBottom);
            }
            //cb.rectangle(left, nameBottom, width, (nameTop - nameBottom));
            //cb.stroke();

            columnText.setExtraParagraphSpace(0f);
            columnText.setAdjustFirstLine(false);
            columnText.setIndent(0);

            String txt = participant.getNom().toUpperCase() + " " + participant.getPrenom();

            float previousPos = columnText.getYLine();
            columnText.setLeading(nameFontSize);
            columnText.setText(createCleanPhrase(txt, nameFontSize, true));
            while (nameFontSize > 1 && ColumnText.hasMoreText(columnText.go(true))) {
                nameFontSize = nameFontSize - 0.5f;
                columnText.setLeading(nameFontSize);
                columnText.setText(createCleanPhrase(txt, nameFontSize, true));
                columnText.setYLine(previousPos);
            }

            columnText.setLeading(nameFontSize);
            columnText.setText(createCleanPhrase(txt, nameFontSize, true));
            columnText.setYLine(previousPos);
            columnText.go(false);

        }

        if (exportGroup) {
            columnText = new ColumnText(cb);
            columnText.setAlignment(Rectangle.ALIGN_CENTER);

            columnText.setSimpleColumn(document.left(), groupeTop, document.right(), groupeBottom);
            float groupeHeight = groupeTop - groupeBottom;
            //cb.rectangle(document.left(), groupeTop - groupeHeight, document.right() - document.left(), groupeHeight);
            //cb.stroke();

            columnText.setExtraParagraphSpace(0f);
            columnText.setAdjustFirstLine(false);
            columnText.setIndent(0);
            columnText.setFollowingIndent(0);

            String txt1 = participant.getGroupe();
            String txt2 = exportRenseignement ? "\n" + participant.getRenseignements() : null;

            float previousPos = columnText.getYLine();
            columnText.setText(null);
            columnText.setLeading(groupFontSize);
            columnText.addText(createCleanPhrase(txt1, groupFontSize, true));
            columnText.addText(createCleanPhrase(txt2, renseignementFontSize, false));
            while (groupFontSize > 1 && ColumnText.hasMoreText(columnText.go(true))) {
                groupFontSize = groupFontSize - 0.5f;
                renseignementFontSize = renseignementFontSize - 0.5f;
                columnText.setText(null);
                columnText.setLeading(groupFontSize);
                columnText.addText(createCleanPhrase(txt1, groupFontSize, true));
                columnText.addText(createCleanPhrase(txt2, renseignementFontSize, false));
                columnText.setYLine(previousPos);
            }

            columnText.setText(null);
            columnText.setLeading(groupFontSize);
            columnText.addText(createCleanPhrase(txt1, groupFontSize, true));
            columnText.addText(createCleanPhrase(txt2, renseignementFontSize, false));
            columnText.setYLine(previousPos);
            columnText.go(false);
        }

        {
            columnText = new ColumnText(cb);

            float topMargin = 12f;
            columnText.setSimpleColumn(left, barcodeTop - topMargin, right, barcodeBottom);
            float barcodeHeight = (barcodeTop - topMargin) - barcodeBottom;
            //cb.rectangle(left, barcodeTop - barcodeHeight, width, barcodeHeight);
            //cb.stroke();

            columnText.setExtraParagraphSpace(0f);
            columnText.setAdjustFirstLine(false);
            columnText.setIndent(0);

            float previousPos = columnText.getYLine();
            columnText.setText(null);
            columnText.addElement(createCleanBarcode(cb, participant.getNumero(), width, barcodeHeight));
            columnText.go(false);
        }

        document.newPage();

    }

    document.close();

    if (pdfBackgroundReader != null) {
        pdfBackgroundReader.close();
    }
}

From source file:fenix.planner.pdf.PDFGenerator.java

License:Open Source License

public void generate(OutputStream output) {
    final Rectangle pageSize = PageSize.A4;
    final ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();

    document = new Document(pageSize, LEFT_MARGIN, RIGHT_MARGIN, TOP_MARGIN, BOTTOM_MARGIN);
    try {/*  w w  w .  j a  v  a2s . c  om*/
        final PdfWriter writer = PdfWriter.getInstance(document, outputBuffer);
        writer.setBoxSize("art", new Rectangle(ART_BOX_LEFT_MARGIN, ART_BOX_BOTTOM_MARGIN,
                pageSize.getRight() - ART_BOX_RIGHT_MARGIN, pageSize.getTop() - ART_BOX_TOP_MARGIN));
        writer.setPageEvent(new HeaderFooter());
        document.open();
        createAndAddForeword();
        createAndAddEventTable();
        createAndAddAfterword();
        createAndAddOrganizerTable();
        document.close();
        writer.close();

        // Loop through the document again to add the missing page numbers
        document = new Document();
        final PdfCopy copy = new PdfCopy(document, output);
        document.open();
        final PdfReader reader = new PdfReader(outputBuffer.toByteArray());
        addPageNumbers(reader, copy);
        document.close();
        reader.close();
    } catch (DocumentException | IOException ex) {
        throw new PDFGenerationException("Error generating PDF", ex);
    }
}

From source file:fll.web.playoff.ScoresheetGenerator.java

License:Open Source License

/**
 * Guess the orientation that the document should be.
 * /*from w  w w  .j  a v a  2s  . co m*/
 * @return true if it should be portrait
 * @throws DocumentException
 * @throws IOException
 */
public static boolean guessOrientation(final ChallengeDescription description)
        throws DocumentException, IOException {
    final ScoresheetGenerator gen = new ScoresheetGenerator(1, description);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    gen.writeFile(out, false);
    final ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    final PdfReader reader = new PdfReader(in);
    if (reader.getNumberOfPages() > 1) {
        // doesn't fit landscape
        return true;
    } else {
        return false;
    }
}

From source file:freemind.modes.ControllerAdapter.java

License:Open Source License

public void pdf2img(String filePath, String fileName) throws IOException {
    PdfReader reader = new PdfReader(filePath);
    int page = reader.getNumberOfPages();
    String tmp[];//from w ww .ja  v  a2s . c  o m
    String temp[];
    ArrayList<SlideData> slideList;
    String newLine[];
    slideList = getController().getSlideList();
    SlideData sData = null;
    String tmpStr = "";
    String data = "";
    String oldStr = "";
    String mkDirPath;
    int noTitle = 0;
    int imgNum = 0;
    int tmpNum = 0;
    boolean dupChk;
    boolean noTitleChk;
    SlideData prev = null;

    mkDirPath = filePath.substring(0, filePath.indexOf(fileName.toString()));
    mkDirPath = mkDirPath + fileName.substring(0, fileName.indexOf(".pdf"));
    File mkDirFile = new File(mkDirPath);

    if (!mkDirFile.exists())
        mkDirFile.mkdir();

    mkDirPath += "\\";

    File file = new File(filePath);

    RandomAccessFile raf = new RandomAccessFile(file, "r");
    FileChannel channel = raf.getChannel();
    ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

    for (int i = 1; i <= page; i++) {
        String str = PdfTextExtractor.getTextFromPage(reader, i);
        System.out.flush();

        if (i == 1) {
            newLine = str.split("\n");
            sData = new SlideData();

            sData.setNodeName(newLine[0]);
            sData.setImgPath(mkDirPath);
            slideList.add(sData);
            prev = sData;
        }

        if (str.indexOf("<<table of contents>>") >= 0) {
            templateChk = true;

            newLine = str.split("\n");
            for (int j = 1; j < newLine.length - 1; j++) {
                data = "";
                sData = new SlideData();

                tmp = newLine[j].split(" ");
                temp = tmp[0].split("\\.");

                for (int l = 0; l < temp.length; l++) // idx  = depth 
                    sData.getIdxList().add(Integer.parseInt(temp[l]));

                for (int k = 1; k < tmp.length; k++) {
                    data += tmp[k]; // 1 1.   // ,   
                    if (k != tmp.length - 1 && !tmp[k].equals(""))
                        data += " ";
                }
                sData.setImgPath(prev.getImgPath());
                sData.setNodeName(data);
                sData.setPrev(prev);
                prev.setNext(sData);
                prev = prev.getNext();
                slideList.add(sData);
            }
            break;
        }
    }

    //    sList 
    if (!templateChk) {
        slideList.clear(); // template  
        for (int i = 1; i <= page; i++) {
            String str = PdfTextExtractor.getTextFromPage(reader, i);
            System.out.flush();

            if (i == 1) {
                newLine = str.split("\n");
                sData = new SlideData();

                sData.setNodeName(newLine[0]);
                sData.setImgPath(mkDirPath);
                slideList.add(sData);
            } else {
                newLine = str.split("\n");
                dupChk = false;
                for (int j = 0; j < slideList.size(); j++) {
                    sData = slideList.get(j);
                    if (newLine[0].equals(sData.getNodeName())) { //     
                        dupChk = true;
                        break;
                    }
                }
                if (!dupChk) {
                    sData = new SlideData(); //   
                    sData.setNodeName(newLine[0]);
                    slideList.add(sData);
                }
            }
        }

        //  
        for (int i = 1; i <= page; i++) {
            String str = PdfTextExtractor.getTextFromPage(reader, i);
            System.out.flush();
            data = "";
            newLine = str.split("\n");

            data = newLine[0].replace(" ", "");

            for (int j = 0; j < slideList.size(); j++) {
                sData = slideList.get(j);
                tmpStr = sData.getNodeName().replace(" ", "");
                if (data.equals(tmpStr)) {
                    sData.setImgCnt(sData.getImgCnt() + 1);
                    break;
                }
            }
        }
    } else { // template 

        for (int i = 1; i <= page; i++) {
            String str = PdfTextExtractor.getTextFromPage(reader, i);
            System.out.flush();
            data = "";
            newLine = str.split("\n");

            tmp = newLine[0].split(" ");

            for (int k = 0; k < tmp.length; k++)
                data += tmp[k];

            data = data.replace(" ", "");

            for (int j = 0; j < slideList.size(); j++) {
                sData = slideList.get(j);
                tmpStr = sData.getNodeName().replace(" ", "");
                if (data.equals(tmpStr)) {
                    sData.setImgCnt(sData.getImgCnt() + 1);
                    break;
                }
            }
        }
    }

    for (int i = 1; i <= page; i++) {
        data = "";
        noTitleChk = false;
        PDFFile pdffile = new PDFFile(buf);
        String str = PdfTextExtractor.getTextFromPage(reader, i);
        System.out.flush();

        newLine = str.split("\n");
        if (newLine[0].equals("<<table of contents>>"))
            continue;

        if (newLine[0].equals("")) {
            data += "undefined" + noTitle;
            imgNum = 1;
            noTitle++;
            noTitleChk = true;
        } else {

            data = newLine[0].replace(" ", "");

            for (int j = 0; j < slideList.size(); j++) {
                sData = slideList.get(j);

                tmpStr = sData.getNodeName().replace(" ", "");
                if (data.equals(tmpStr)) {
                    if (oldStr.equals(tmpStr))
                        break;
                    oldStr = data;
                    tmpNum = imgNum = sData.getImgCnt();
                    break;
                }
            }
        }

        // draw the first page to an image
        PDFPage pdfPage = pdffile.getPage(i);

        // get the width and height for the doc at the default zoom
        Rectangle rect = new Rectangle(0, 0, (int) pdfPage.getBBox().getWidth(),
                (int) pdfPage.getBBox().getHeight());

        // generate the image

        Image image = pdfPage.getImage(rect.width, rect.height, // width
                // &
                // height
                rect, // clip rect
                null, // null for the ImageObserver
                true, // fill background with white
                true // block until drawing is done
        );

        int w = image.getWidth(null);
        int h = image.getHeight(null);
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(image, 0, 0, null);
        g2.dispose();
        try {
            if (imgNum == 1) {
                if (noTitleChk)
                    ImageIO.write(bi, "jpg", new File(mkDirPath + data + ".jpg"));
                else
                    ImageIO.write(bi, "jpg", new File(mkDirPath + sData.getNodeName() + ".jpg"));

            } else {
                ImageIO.write(bi, "jpg",
                        new File(mkDirPath + sData.getNodeName() + (imgNum - tmpNum) + ".jpg"));
                tmpNum--;
            }
        } catch (IOException ioe) {
            System.out.println("write: " + ioe.getMessage());
        }
        data = "";
    }
    sData = slideList.get(0);
    sData.setsCnt(page);
    reader.close();
}

From source file:freemind.modes.ControllerAdapter.java

License:Open Source License

public void pdf2mm(String filePath, String fileName) throws IOException {
    int depth = 0;
    String tmp[];/*from   w  w  w . ja  v  a2s . c o m*/
    String newLine[];
    String direction = "left";
    ArrayList<TableData> root = new ArrayList<TableData>();
    TableData oldTableData = new TableData();
    String mmFilePath = filePath.substring(0, filePath.length() - 4);
    fileName = fileName.substring(0, fileName.length() - 4);
    mmFilePath += ".mm";
    File mmFile = new File(mmFilePath);
    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(mmFile), "UTF-8");
    ArrayList<SlideData> slideList;
    slideList = getController().getSlideList();
    String imgPath = slideList.get(0).getImgPath();
    try {
        PdfReader reader = new PdfReader(filePath);
        int page = reader.getNumberOfPages();

        for (int i = 1; i <= page; i++) {
            String str = PdfTextExtractor.getTextFromPage(reader, i);
            System.out.flush();

            if (str.indexOf("<<table of contents>>") >= 0) {
                out.write("<map version=\"0.9.0\">\n");

                newLine = str.split("\n");
                for (int j = 1; j < newLine.length - 1; j++) {
                    String data = "";
                    String hData = "";
                    TableData childTable = new TableData();

                    if (j > (newLine.length / 2))
                        direction = "right";

                    tmp = newLine[j].split("\\.");

                    if (tmp[1].substring(0, 1).equals(" ")) {
                        depth = 0;
                        data = tmp[1].substring(tmp[1].indexOf(" "), tmp[1].length());
                        childTable.setDirection(direction);
                        childTable.setHeadline(tmp[0]);
                        childTable.setDepth(depth);
                    } else {
                        depth = tmp.length - 1;
                        childTable.setDepth(depth);

                        tmp = newLine[j].split(" ");
                        hData = tmp[0];
                        for (int k = 1; k < tmp.length; k++)
                            data += tmp[k] + " ";
                        childTable.setHeadline(hData);
                        data = data.substring(0, data.length() - 1);
                    }
                    childTable.setData(data);

                    String tmpStr = childTable.getHeadline().toString();
                    if (tmpStr.length() > 2) {
                        if (tmpStr.substring(0, tmpStr.length() - 2).equals(oldTableData.getHeadline()))
                            oldTableData.setHaveChild(true);
                    }

                    if (j > 1)
                        root.add(oldTableData);

                    oldTableData = childTable;

                    if (j == newLine.length - 2) { //    
                        childTable.setHaveChild(false);
                        root.add(childTable);
                    }
                }
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    out.write("<node CREATED=\"1365038113483\" ID=\"ID_1002961678\" " + "MODIFIED=\"1365038132371\" "
            + "TEXT=\"" + fileName + "\">\n");
    TableData showTable;
    int dif;
    for (int i = 0; i < root.size(); i++) {
        out.write("<node CREATED=\"1365038113483\" ID=\"ID_1002961678\" MODIFIED=\"1365038132371\" ");
        showTable = root.get(i);
        if (!showTable.getDirection().equals(""))
            out.write("POSITION=\"" + showTable.getDirection() + "\" ");
        out.write("TEXT=\"" + showTable.getData().trim() + "\"");
        if (showTable.isHaveChild())
            out.write(">\n");
        else
            out.write("/>\n");
        if (i == root.size() - 1)
            dif = showTable.getDepth();
        else
            dif = showTable.getDepth() - root.get(i + 1).getDepth();
        for (int j = 0; j < dif; j++)
            out.write("</node>\n");
    }
    out.write("</node>\n</map>\n");
    out.close();
}

From source file:fyp.JavaWritePDF.java

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src); // read source file
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest)); // create destination file
    stamper.insertPage(reader.getNumberOfPages() + 1, reader.getPageSizeWithRotation(1)); // insert new page 
    Image img = Image.getInstance(IMG); // get instance of image file 
    img.setAbsolutePosition(0, 350);/*  w ww.j  av  a 2s .  c o m*/
    stamper.getOverContent(2).addImage(img); // insert image to new page
    stamper.close(); // close stamper
    File delfile = new File(SRC);
    delfile.delete(); // delete source file 
    respiratorytest.success();
}