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

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

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes the reader, and any underlying stream or data source used to create the reader

Usage

From source file:eu.mrbussy.pdfsplitter.Application.java

License:Open Source License

/**
 * Split the given PDF file into multiple files using pages.
 * //from w w  w.j a  v a2s  . c om
 * @param filename
 *            - Name of the PDF to split
 * @param useSubFolder
 *            - Use a separate folder to place the files in.
 */
public static void SplitFile(File file, boolean useSubFolder) {
    PdfReader reader = null;
    String format = null;

    if (useSubFolder)
        format = "%1$s%2$s%4$s%2$s_%%03d.%3$s";
    else
        format = "%1$s%2$s_%%03d.%3$s";

    String splitFile = String.format(format, FilenameUtils.getFullPath(file.getAbsolutePath()),
            FilenameUtils.getBaseName(file.getAbsolutePath()),
            FilenameUtils.getExtension(file.getAbsolutePath()), IOUtils.DIR_SEPARATOR);

    try {
        reader = new PdfReader(new FileInputStream(file));

        if (reader.getNumberOfPages() > 0) {
            for (int pageNum = 1; pageNum <= reader.getNumberOfPages(); pageNum++) {
                System.out.println(String.format(splitFile, pageNum));
                String filename = String.format(splitFile, pageNum);
                Document document = new Document(reader.getPageSizeWithRotation(1));
                PdfCopy writer = new PdfCopy(document, new FileOutputStream(filename));
                document.open();
                // Copy the page from the original
                PdfImportedPage page = writer.getImportedPage(reader, pageNum);
                writer.addPage(page);
                document.close();
                writer.close();
            }
        }
    } catch (Exception ex) {
        // TODO Implement exception handling
        ex.printStackTrace(System.err);
    } finally {
        if (reader != null)
            // Always close the stream
            reader.close();
    }
}

From source file:eu.mrbussy.pdfsplitter.Splitter.java

License:Open Source License

/**
 * Split the given PDF file into multiple files using pages.
 * //  ww  w. ja  v  a 2  s.c o  m
 * @param filename
 *            - Name of the PDF to split
 * @param useSubFolder
 *            - Use a separate folder to place the files in.
 */
public static void Run(File file, boolean useSubFolder) {
    PdfReader reader = null;
    String format = null;

    if (useSubFolder) {
        format = "%1$s%2$s%4$s"; // Directory format
        try {
            FileUtils.forceMkdir(
                    new File(String.format(format, FilenameUtils.getFullPath(file.getAbsolutePath()),
                            FilenameUtils.getBaseName(file.getAbsolutePath()),
                            FilenameUtils.getExtension(file.getAbsolutePath()), IOUtils.DIR_SEPARATOR)));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        format = "%1$s%2$s%4$s%2$s_%%03d.%3$s"; // Directory format + filename
    } else
        format = "%1$s%2$s_%%03d.%3$s";

    String splitFile = String.format(format, FilenameUtils.getFullPath(file.getAbsolutePath()),
            FilenameUtils.getBaseName(file.getAbsolutePath()),
            FilenameUtils.getExtension(file.getAbsolutePath()), IOUtils.DIR_SEPARATOR);

    try {
        reader = new PdfReader(new FileInputStream(file));

        if (reader.getNumberOfPages() > 0) {
            for (int pageNum = 1; pageNum <= reader.getNumberOfPages(); pageNum++) {
                System.out.println(String.format(splitFile, pageNum));
                String filename = String.format(splitFile, pageNum);
                Document document = new Document(reader.getPageSizeWithRotation(1));
                PdfCopy writer = new PdfCopy(document, new FileOutputStream(filename));
                document.open();
                // Copy the page from the original
                PdfImportedPage page = writer.getImportedPage(reader, pageNum);
                writer.addPage(page);
                document.close();
                writer.close();
            }
        }
    } catch (Exception ex) {
        // TODO Implement exception handling
        ex.printStackTrace(System.err);
    } finally {
        if (reader != null)
            // Always close the stream
            reader.close();
    }
}

From source file:ExternalForms.Browser.java

public String getDataFromPDF() {
    String all_inputs = ""; //concatenated string of inputs in order
    try {/* w w w. j  av  a  2s  .  c  o m*/

        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  . ja va  2 s  .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 {//  ww w.  j  a va 2  s.  c o  m
        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  www  .  ja v  a 2s  .co  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 ww .j a v  a2s .  co m
        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: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[];/*  w ww. j av  a  2s .  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:gov.nih.nci.firebird.service.pdf.PdfProcessor.java

License:Open Source License

final void process() throws IOException {
    PdfReader reader = new PdfReader(srcPdfInputStream);
    PdfStamper stamper = null;/*ww  w .ja va  2 s .c  o m*/
    try {
        stamper = new PdfStamper(reader, destPdfOutputStream);
        handleProcessing(reader, stamper);
    } catch (DocumentException e) {
        throw new IllegalStateException("Unexpected problem processing PDF", e);
    } finally {
        reader.close();
        close(stamper);
    }

}

From source file:gravabncertificado.GerandoArquivoCarimbado_1.java

public static void GerandoArquivoCarimbadoPDF(String caminhoarquivo, String BN) throws InvalidPdfException {
    //Copiando arquivo informado.
    try {/* w w w.j av a2  s  .  co  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) {
    }

}