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

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

Introduction

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

Prototype

public int getNumberOfPages() 

Source Link

Document

Gets the number of pages in the document.

Usage

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

License:Open Source License

private void addPageNumbers(PdfReader reader, PdfCopy copy) {
    int pageCount = reader.getNumberOfPages();
    PdfImportedPage page;// w  w  w .jav  a 2s . com
    PdfCopy.PageStamp stamp;

    for (int i = 1; i <= pageCount; ++i) {
        Rectangle rect = reader.getBoxSize(i, "art");
        page = copy.getImportedPage(reader, i);
        stamp = copy.createPageStamp(page);
        // add page numbers
        ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_RIGHT,
                new Phrase(String.format("%d / %d", i, pageCount), footerFont), rect.getRight(),
                rect.getBottom() + 5, 0);
        try {
            stamp.alterContents();
            copy.addPage(page);
        } catch (BadPdfFormatException | IOException ex) {
            throw new PDFGenerationException("Error adding page number to page " + i, ex);
        }
    }
}

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

License:Open Source License

/**
 * Guess the orientation that the document should be.
 * /* w w w. jav a2 s.c o  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[];// ww w .  j  av a  2  s .c om
    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[];/* w w  w .  j  a va  2s. co  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);/*from   www  .j  a  va2  s .  co  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();
}

From source file:fyp.JavaWritePDF.java

public void manipulatePdf2(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    stamper.insertPage(reader.getNumberOfPages() + 1, reader.getPageSizeWithRotation(1));
    stamper.insertPage(reader.getNumberOfPages() + 1, reader.getPageSizeWithRotation(1));// create a second new page
    Image img = Image.getInstance(IMG);
    Image img2 = Image.getInstance(IMG2);
    img.setAbsolutePosition(0, 350);/*from  w  w  w .  j  a  v  a  2 s.  co m*/
    img2.setAbsolutePosition(0, 350);
    stamper.getOverContent(2).addImage(img);
    stamper.getOverContent(3).addImage(img2); // add the second sessions image to the new page
    stamper.close();
    File delfile = new File(SRC);
    delfile.delete();
    respiratorytest.success();
}

From source file:gov.nih.nci.firebird.service.pdf.AdditionalContent.java

License:Open Source License

private void addText(PdfReader reader, PdfStamper stamper, ColumnText text) throws DocumentException {
    Rectangle pageSize = reader.getPageSize(1);
    int newPageNumber = reader.getNumberOfPages() + 1;
    do {/*from   www  . java 2  s . com*/
        stamper.insertPage(newPageNumber, pageSize);
        PdfContentByte newContent = stamper.getOverContent(newPageNumber);
        text.setCanvas(newContent);
        text.setSimpleColumn(pageSize.getLeft(MARGIN_SIZE), pageSize.getTop(MARGIN_SIZE),
                pageSize.getRight(MARGIN_SIZE), pageSize.getBottom(MARGIN_SIZE));
        newPageNumber++;
    } while (ColumnText.hasMoreText(text.go()));
}

From source file:gov.utah.dts.det.ccl.actions.facility.information.license.reports.LicenseCertificate.java

private static void writePdf(License license, ByteArrayOutputStream ba, HttpServletRequest request)
        throws DocumentException, BadElementException {
    SimpleDateFormat df = new SimpleDateFormat("MMMM d, yyyy");
    StringBuilder sb;//from   ww  w . j  a  v  a 2s .c om

    // Retrieve the certificate template to use as watermark
    ServletContext context = request.getSession().getServletContext();
    String templatefile = context.getRealPath("/resources") + "/LicenseCertificateTemplate.pdf";
    PdfReader reader = getTemplateReader(templatefile);
    if (reader != null && reader.getNumberOfPages() > 0) {
        Phrase phrase;

        // Create new document using the page size of the certificate template document
        Document document = new Document(reader.getPageSizeWithRotation(1), 0, 0, 0, 0);
        PdfWriter writer = PdfWriter.getInstance(document, ba);
        document.open();

        // Get the writer under content byte for placing of watermark
        PdfContentByte under = writer.getDirectContentUnder();
        PdfContentByte over = writer.getDirectContent();

        // Retrieve the first page of the template document and wrap as an Image to use as new document watermark
        PdfImportedPage page = writer.getImportedPage(reader, 1);
        Image img = Image.getInstance(page);
        // Make sure the image has an absolute page position
        if (!img.hasAbsoluteX() || !img.hasAbsoluteY()) {
            img.setAbsolutePosition(0, 0);
        }

        under.addImage(img);

        /*
         * THE FOLLOWING TWO FUNCTION CALLS DISPLAY THE PAGE MARGINS AND TEXT COLUMN BORDERS FOR DEBUGGING TEXT PLACEMENT.
         * UNCOMMENT EACH FUNCTION CALL TO HAVE BORDERS DISPLAYED ON THE OUTPUT DOCUMENT.  THIS WILL HELP WHEN YOU NEED
         * TO SEE WHERE TEXT WILL BE PLACED ON THE CERTIFICATE FORM.
         */
        // Show the page margins
        //showPageMarginBorders(over);

        // Show the text column borders
        //showColumnBorders(over);

        ColumnText ct = new ColumnText(over);
        ct.setLeading(fixedLeading);

        // Add Facility Name to column
        String text = license.getFacility().getName();
        if (text != null) {
            phrase = new Phrase(text.toUpperCase(), mediumfontB);
            phrase.setLeading(noLeading);
            ct.addText(phrase);
            ct.addText(Chunk.NEWLINE);
        }
        // Add Facility Site to column
        text = license.getFacility().getSiteName();
        if (text != null) {
            phrase = new Phrase(text.toUpperCase(), mediumfontB);
            phrase.setLeading(noLeading);
            ct.addText(phrase);
            ct.addText(Chunk.NEWLINE);
        }
        // Add Facility Address to column
        text = license.getFacility().getLocationAddress().getAddressOne();
        if (text != null) {
            phrase = new Phrase(text.toUpperCase(), mediumfontB);
            phrase.setLeading(noLeading);
            ct.addText(phrase);
            ct.addText(Chunk.NEWLINE);
        }
        text = license.getFacility().getLocationAddress().getCityStateZip();
        if (text != null) {
            phrase = new Phrase(text.toUpperCase(), mediumfontB);
            phrase.setLeading(noLeading);
            ct.addText(phrase);
            ct.addText(Chunk.NEWLINE);
        }
        // Write column to document
        ct.setAlignment(Element.ALIGN_CENTER);
        ct.setSimpleColumn(COLUMNS[0][0], COLUMNS[0][1], COLUMNS[0][2], COLUMNS[0][3]);
        ct.go();

        // Add Certification Service Code to column
        ct = new ColumnText(over);
        ct.setLeading(fixedLeading);
        String service = "";
        if (license.getSpecificServiceCode() != null
                && StringUtils.isNotBlank(license.getSpecificServiceCode().getValue())
                && DV_TREATMENT.equalsIgnoreCase(license.getSpecificServiceCode().getValue())) {
            service += DOMESTIC_VIOLENCE;
        }
        if (!license.getProgramCodeIds().isEmpty()) { // redmine 25410
            mentalHealthLoop: for (PickListValue pkv : license.getProgramCodeIds()) {
                String program = pkv.getValue();
                int idx = program.indexOf(" -");
                if (idx >= 0) {
                    String code = program.substring(0, idx);
                    if (MENTAL_HEALTH_CODES.indexOf(code + ":") >= 0) {
                        if (service.length() > 0) {
                            service += " / ";
                        }
                        service += MENTAL_HEALTH;
                        break mentalHealthLoop;
                    }
                }
            }
            substanceAbuseLoop: for (PickListValue pkv : license.getProgramCodeIds()) {
                String program = pkv.getValue();
                int idx = program.indexOf(" -");
                if (idx >= 0) {
                    String code = program.substring(0, idx);
                    if (SUBSTANCE_ABUSE_CODES.indexOf(code + ":") >= 0) {
                        if (service.length() > 0) {
                            service += " / ";
                        }
                        service += SUBSTANCE_ABUSE;
                        break substanceAbuseLoop;
                    }
                }
            }
        }
        if (StringUtils.isNotBlank(license.getServiceCodeDesc())) {
            if (service.length() > 0) {
                service += " / ";
            }
            service += license.getServiceCodeDesc();
        }
        if (StringUtils.isNotEmpty(service)) {
            phrase = new Phrase(service.toUpperCase(), mediumfont);
            phrase.setLeading(noLeading);
            ct.addText(phrase);
            ct.addText(Chunk.NEWLINE);
        }

        // Add CLIENTS Info to column
        sb = new StringBuilder("FOR ");
        if (license.getAgeGroup() == null
                || license.getAgeGroup().getValue().equalsIgnoreCase("Adult & Youth")) {
            // Adult & Youth
            if (license.getAdultTotalSlots() != null) {
                sb.append(license.getAdultTotalSlots().toString());
            }
            sb.append(" ADULT AND YOUTH CLIENTS");
        } else if (license.getAgeGroup().getValue().equalsIgnoreCase("Adult")) {
            // Adult
            if (license.getAdultTotalSlots() != null) {
                // Are male or female counts specified?
                sb.append(license.getAdultTotalSlots().toString());
                sb.append(" ADULT");
                if (license.getAdultFemaleCount() != null || license.getAdultMaleCount() != null) {
                    // Does either the male or female count equal the total slot count?
                    if ((license.getAdultFemaleCount() != null
                            && license.getAdultFemaleCount().equals(license.getAdultTotalSlots()))) {
                        sb.append(" FEMALE CLIENTS");
                    } else if (license.getAdultMaleCount() != null
                            && license.getAdultMaleCount().equals(license.getAdultTotalSlots())) {
                        sb.append(" MALE CLIENTS");
                    } else {
                        sb.append(" CLIENTS, ");
                        if (license.getAdultMaleCount() != null) {
                            sb.append(license.getAdultMaleCount().toString() + " MALE");
                        }
                        if (license.getAdultFemaleCount() != null) {
                            if (license.getAdultMaleCount() != null) {
                                sb.append(" AND ");
                            }
                            sb.append(license.getAdultFemaleCount().toString() + " FEMALE");
                        }
                        if (license.getFromAge() != null || license.getToAge() != null) {
                            sb.append(",");
                        }
                    }
                } else {
                    sb.append(" CLIENTS");
                }
            } else {
                sb.append(" ADULT CLIENTS");
            }
        } else {
            // Youth
            if (license.getYouthTotalSlots() != null) {
                // Are male or female counts specified?
                sb.append(license.getYouthTotalSlots().toString());
                sb.append(" YOUTH");
                if (license.getYouthFemaleCount() != null || license.getYouthMaleCount() != null) {
                    // Does either the male or female count equal the total slot count?
                    if ((license.getYouthFemaleCount() != null
                            && license.getYouthFemaleCount().equals(license.getYouthTotalSlots()))) {
                        sb.append(" FEMALE CLIENTS");
                    } else if (license.getYouthMaleCount() != null
                            && license.getYouthMaleCount().equals(license.getYouthTotalSlots())) {
                        sb.append(" MALE CLIENTS");
                    } else {
                        sb.append(" CLIENTS, ");
                        if (license.getYouthMaleCount() != null) {
                            sb.append(license.getYouthMaleCount().toString() + " MALE");
                        }
                        if (license.getYouthFemaleCount() != null) {
                            if (license.getYouthMaleCount() != null) {
                                sb.append(" AND ");
                            }
                            sb.append(license.getYouthFemaleCount().toString() + " FEMALE");
                        }
                        if (license.getFromAge() != null || license.getToAge() != null) {
                            sb.append(",");
                        }
                    }
                } else {
                    sb.append(" CLIENTS");
                }
            } else {
                sb.append(" YOUTH CLIENTS");
            }
        }
        if (license.getFromAge() != null || license.getToAge() != null) {
            sb.append(" AGES ");
            if (license.getFromAge() != null) {
                sb.append(license.getFromAge().toString());
                if (license.getToAge() != null) {
                    sb.append(" TO " + license.getToAge().toString());
                } else {
                    sb.append(" AND OLDER");
                }
            } else {
                sb.append("TO " + license.getToAge().toString());
            }
        }
        phrase = new Phrase(sb.toString(), mediumfont);
        phrase.setLeading(noLeading);
        ct.addText(phrase);
        ct.addText(Chunk.NEWLINE);

        // Add Certificate Comments
        if (StringUtils.isNotBlank(license.getCertificateComment())) {
            phrase = new Phrase(license.getCertificateComment().toUpperCase(), mediumfont);
            phrase.setLeading(noLeading);
            ct.addText(phrase);
        }

        // Write column to document
        ct.setAlignment(Element.ALIGN_CENTER);
        ct.setSimpleColumn(COLUMNS[1][0], COLUMNS[1][1], COLUMNS[1][2], COLUMNS[1][3]);
        ct.go();

        // Add Certificate Start Date
        if (license.getStartDate() != null) {
            phrase = new Phrase(df.format(license.getStartDate()), mediumfont);
            phrase.setLeading(noLeading);
            ct = new ColumnText(over);
            ct.setSimpleColumn(phrase, COLUMNS[2][0], COLUMNS[2][1], COLUMNS[2][2], COLUMNS[2][3], fixedLeading,
                    Element.ALIGN_RIGHT);
            ct.go();
        }

        // Add Certificate End Date
        if (license.getEndDate() != null) {
            phrase = new Phrase(df.format(license.getEndDate()), mediumfont);
            phrase.setLeading(noLeading);
            ct = new ColumnText(over);
            ct.setSimpleColumn(phrase, COLUMNS[3][0], COLUMNS[3][1], COLUMNS[3][2], COLUMNS[3][3], fixedLeading,
                    Element.ALIGN_LEFT);
            ct.go();
        }

        // Add License Number
        if (license.getLicenseNumber() != null) {
            phrase = new Phrase(license.getLicenseNumber().toString(), largefontB);
            phrase.setLeading(noLeading);
            ct = new ColumnText(over);
            ct.setSimpleColumn(phrase, COLUMNS[4][0], COLUMNS[4][1], COLUMNS[4][2], COLUMNS[4][3],
                    numberLeading, Element.ALIGN_CENTER);
            ct.go();
        }
        document.close();
    }
}

From source file:gravabncertificado.GerandoArquivoCarimbado_1.java

public static void GerandoArquivoCarimbadoPDF(String caminhoarquivo, String BN) throws InvalidPdfException {
    //Copiando arquivo informado.
    try {/*from  w  ww  .  j  av  a  2s.c  o m*/

        // Adicionado parametro para nao retornar erro quando o documento for protegido.
        PdfReader.unethicalreading = true;
        //Cria o reader para o primeiro PDF

        PdfReader reader = new PdfReader(caminhoarquivo);

        // n recebe o numero total de paginas
        int n = reader.getNumberOfPages();

        //Tamanho da primeira Pagina
        ;

        //Cria Segundo PDF

        Document document = new Document(PageSize.A4, 36, 36, 36, 36);

        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-C.pdf"));

        document.open();

        // Adiciona conteudo ao PDF Carimbado.
        PdfContentByte cb = writer.getDirectContent();
        int i = 0;
        int p = 0;
        String caminhodestino = (caminhoarquivo.substring(0, caminhoarquivo.length() - BN.length()));

        // DESABILITADO PORQUE O MOVER NAO ESTAVA FUNCIONANDO.
        File destinooriginal = new File(caminhodestino + "ORIGINAL\\");
        if (!destinooriginal.exists()) {
            destinooriginal.mkdir();
        }

        caminhodestino = (caminhodestino + "ORIGINAL\\" + BN);

        //TESTANDO NOVA FORMA DE COPIAR

        File origem = new File(caminhoarquivo);
        File destino = new File(caminhodestino);

        FileInputStream fis = new FileInputStream(origem);
        FileOutputStream fos = new FileOutputStream(destino);

        FileChannel inChannel = fis.getChannel();
        FileChannel outChannel = fos.getChannel();

        long transferFrom = outChannel.transferFrom(inChannel, 0, inChannel.size());

        fis.close();
        fos.close();
        inChannel.close();
        outChannel.close();

        // Thread.sleep(10);

        BN = BN.substring(0, BN.length() - 4);

        while (i < n) {
            document.newPage();
            p++;
            i++;

            PdfContentByte under = writer.getDirectContentUnder();
            PdfImportedPage page1 = writer.getImportedPage(reader, i);
            cb.addTemplate(page1, 0, i * 0.2f);

            // Page 1: a rectangle
            /* RETANGULO DESATIVADO
            drawRectangle(under, 100, 50);
            under.setRGBColorFill(255, 220, 220);
            under.rectangle(width /50, 5, 118, 40);
            under.fill();
            */

            //CARIMBO DA BN

            BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            cb.beginText();
            cb.setFontAndSize(bf, 14);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 44, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 32, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 22, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " NR", width / 6, 28, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + BN, width / 6, 16, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 12, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 14, 0);
            cb.endText();

        }

        document.close();
        writer.close();
        reader.close();
        origem.delete();

        /* PdfContentByte under = writer.getDirectContentUnder();
                 
         // Page 1: a rectangle
             drawRectangle(under, 20, 20);
             under.setRGBColorFill(0xFF, 0xD7, 0x00);
             under.rectangle(5, 5, 15, 15);
             under.fill(); */
        //document.newPage();

        //COPIANDO ARQUIVO CARIMBADO

        /* DESABILITADO PORQUE NAO ESTAVA FUNCIONANDO.
        boolean bool;
                
         //caminhoarquivo = caminhoarquivo.replace("\\", "\\\\");
         //caminhodestino = caminhodestino.replace("\\", "\\\\");
                    
        File origem = new File(caminhoarquivo);
        File destino = new File(caminhodestino);
                
                    
        bool = origem.renameTo(destino);
        System.out.println(origem);
        System.out.println(caminhodestino);
        */

    } catch (IOException | DocumentException ex) {
    }

}

From source file:gravabncertificado007.CarimboCertificado.java

public void aplicaCarimboBin(String BN, String caminhoarquivo)
        throws DocumentException, IOException, RuntimeException {

    PdfReader.unethicalreading = true;//  w w w.j a v  a2s  .co m
    //Cria o reader para o primeiro PDF

    PdfReader reader = new PdfReader(caminhoarquivo);
    Rectangle psize = reader.getPageSize(1);
    float width = psize.getWidth();
    float height = psize.getHeight();

    Document document = new Document(new Rectangle(width, height));

    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(caminhoarquivo.substring(0, caminhoarquivo.length() - 4) + "-C.pdf"));

    document.open();

    int i = 0;
    BN = BN.substring(BN.length() - 13, BN.length() - 4);
    PdfContentByte cb = writer.getDirectContent();
    while (i < reader.getNumberOfPages()) {
        i++;

        document.newPage();

        PdfContentByte under = writer.getDirectContentUnder();
        PdfImportedPage page1 = writer.getImportedPage(reader, i);
        cb.addTemplate(page1, 0, i * 0.2f);

        //CARIMBO DA BN
        BaseFont bf = BaseFont.createFont(BaseFont.COURIER_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
        cb.beginText();
        cb.setFontAndSize(bf, 14);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 44, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 32, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 22, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " NR", width / 6, 28, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + BN, width / 6, 16, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " |               |", width / 6, 12, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " ________________", width / 6, 14, 0);
        cb.endText();

    }

    document.close();
    writer.close();
    reader.close();

}