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:edu.clemson.lph.pdfgen.PDFUtils.java

License:Open Source License

public static Node getXFADataNode(byte[] pdfDataIn) {
    Node nData = null;/*from   w w w  .jav  a2  s  . c  o m*/
    try {
        PdfReader reader = new PdfReader(pdfDataIn);
        XfaForm form = new XfaForm(reader);
        Node xmlNode = form.getDatasetsNode();
        if ("xfa:datasets".equals(xmlNode.getNodeName())) {
            nData = xmlNode.getFirstChild();
            if (!"xfa:data".equals(nData.getNodeName())) {
                System.err.println(nData.getNodeName());
                nData = null;
            }
        } else
            System.err.println(xmlNode.getNodeName());
    } catch (IOException e) {
        logger.error(e);
    } catch (ParserConfigurationException e) {
        logger.error(e);
    } catch (SAXException e) {
        logger.error(e);
    }

    return nData;
}

From source file:englishrusbook.Reader.java

public boolean isCanParsing(String file) {
    debugOut("function:isCanParsingPDF");
    boolean isCanParsingPDF = true;

    try {//from www  .  j a  va2 s. com
        reader = new PdfReader(file);
    } catch (IOException e) {
        printOut("ERROR : Maybe file not exist");
        isCanParsingPDF = false;
    }

    return isCanParsingPDF;
}

From source file:EplanPrinter.PDFPrint.java

License:Open Source License

public String createPDF(String input, String output)
        throws FileNotFoundException, DocumentException, IOException {
    heightScalar = 0;/*from w w  w .ja  v a  2  s .co m*/
    //Addition. linh 07.21.2016 bypass owner password
    PdfReader.unethicalreading = true;
    PdfReader reader = new PdfReader(input);

    //Sets up the stamper, which is what adds all the content to the page.
    pds = new PdfStamper(reader, new FileOutputStream(output));
    PdfImportedPage page;
    page = pds.getImportedPage(reader, 1);
    PdfContentByte bg;
    totalPages = reader.getNumberOfPages();

    r = new Rectangle[totalPages];
    rotation = new int[totalPages];
    for (int x = 0; x < totalPages; x++) {
        r[x] = reader.getPageSizeWithRotation(x + 1);
        rotation[x] = reader.getPageRotation(x + 1);
    }

    mediabox = getDocumentMediaBox(reader, totalPages);

    //r = reader.getPageSizeWithRotation(1);
    //setRatio();
    bg = pds.getUnderContent(1);
    heightScalar = 0;
    return "";
}

From source file:EplanPrinter.PDFPrint.java

License:Open Source License

public String insertSignature(String src, String dest, String Keystore, String name, String password,
        int masterHeight, int masterWidth, int pageNum)
        throws GeneralSecurityException, IOException, DocumentException {

    float[] scalar = scale(1, 1, 120, 32, masterHeight, masterWidth, pageNum);
    float[] trans = translate(1, 1, r[pageNum - 1].getHeight(), r[pageNum - 1].getWidth(), masterHeight,
            masterWidth, pageNum);//  w  ww . ja va2 s. c om
    float[] f = commentTrans(1, 1, masterHeight, masterWidth, pageNum);

    float shift = 0;

    float pageChunk = r[pageNum - 1].getHeight() / 10;
    shift = r[pageNum - 1].getHeight() / 100;
    scalar[1] = (int) (pageChunk);
    scalar[0] = (int) (120 * pageChunk) / 32;
    trans[0] = (int) (0 + (pageChunk * widthScalar));
    trans[1] = (int) (r[pageNum - 1].getHeight() - (pageChunk * heightScalar) - (shift * (heightScalar + 2)));
    heightScalar = heightScalar + 1;
    if (heightScalar == 8) {
        heightScalar = 0;
        widthScalar = widthScalar + 2;
    }

    /* Addition. ftorres - 7/22/2015 - Added to account for rotated pages 
     *   with the origin (0,0) not set to the bottom-left of the page. [1400] */
    trans = translateRotation(trans[0], trans[1], pageNum);

    Rectangle cropBox = pds.getReader().getCropBox(1);
    Rectangle rectangle = new Rectangle(trans[0] + shift, trans[1] - scalar[1], trans[0] + shift + 120,
            trans[1] - scalar[1] + 32);
    BouncyCastleProvider provider = new BouncyCastleProvider();
    Security.addProvider(provider);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(Keystore), password.toCharArray());
    String alias = (String) ks.aliases().nextElement();
    PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
    Certificate[] chain = ks.getCertificateChain(alias);
    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(src);
    FileOutputStream os = new FileOutputStream(dest);
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setVisibleSignature(rectangle, 1, name);
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk, "SHA-256", "BC");
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, CryptoStandard.CMS);

    return "";
}

From source file:EplanPrinter.PDFPrint.java

License:Open Source License

public List<BookmarkData> getBookmarks(String filePath) {
    try {/* w ww. java2 s. c o m*/
        PdfReader file = new PdfReader(filePath);
        List<HashMap<String, Object>> bookmarks = SimpleBookmark.getBookmark(file);

        List<BookmarkData> results = new ArrayList<BookmarkData>();
        results = parseBookmark(bookmarks);

        return results;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:es.jscan.Pantallas.PantallaPrincipal.java

License:Apache License

private void crearXmlLote(String lote) {
    Calendar cal = Calendar.getInstance();
    String anio = String.valueOf(cal.get(Calendar.YEAR));
    String mes = String.valueOf((cal.get(Calendar.MONTH) + 1)).length() == 1
            ? "0" + String.valueOf((cal.get(Calendar.MONTH) + 1))
            : String.valueOf((cal.get(Calendar.MONTH) + 1));
    String dia = String.valueOf(cal.get(Calendar.DAY_OF_MONTH)).length() == 1
            ? "0" + String.valueOf(cal.get(Calendar.DAY_OF_MONTH))
            : String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
    String hora = String.valueOf(cal.get(Calendar.HOUR_OF_DAY)).length() == 1
            ? "0" + String.valueOf(cal.get(Calendar.HOUR_OF_DAY))
            : String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
    String minuto = String.valueOf(cal.get(Calendar.MINUTE)).length() == 1
            ? "0" + String.valueOf(cal.get(Calendar.MINUTE))
            : String.valueOf(cal.get(Calendar.MINUTE));
    String segundo = String.valueOf(cal.get(Calendar.SECOND)).length() == 1
            ? "0" + String.valueOf(cal.get(Calendar.SECOND))
            : String.valueOf(cal.get(Calendar.SECOND));

    String dirorigen = rutadigita + separador + "lotes" + separador + lote + separador;
    File dir = new File(dirorigen);

    FilenameFilter filtropdf = new FiltroPdf();
    String ficheros[] = dir.list(filtropdf);

    String ficheroxml = rutadigita + separador + "lotes" + separador + lote + separador + lote + ".xml";

    XmlLote Lote = new XmlLote();
    XmlInfo Info = new XmlInfo();

    String numpaginas = "";
    String tam = "";
    String proceso = "";
    String usuarioldap = "";
    String ip = "";
    String provincia = "";
    String fechadigita = "";
    String fechacreacion = "";
    String expediente = "";
    String cb = "";
    String notificarinstructor = "";
    String tipodocumento = "";
    String fechanotificacion = "";
    String actualizarfase = "";
    String ubicacionfisica = "";

    for (int i = 0; i < ficheros.length; i++) {
        String fich = ficheros[i].toString();
        try {/*from   w  w w .j  a va  2  s .c  o m*/
            PdfReader reader = new PdfReader(dirorigen + fich);
            proceso = (reader.getInfo().get("proceso") == null ? "" : reader.getInfo().get("proceso"));
            usuarioldap = (reader.getInfo().get("usuarioldap") == null ? ""
                    : reader.getInfo().get("usuarioldap"));
            ip = (reader.getInfo().get("IP") == null ? "" : reader.getInfo().get("IP"));
            provincia = (reader.getInfo().get("provincia") == null ? "" : reader.getInfo().get("provincia"));
            fechadigita = (reader.getInfo().get("fechadigita") == null ? ""
                    : reader.getInfo().get("fechadigita"));
            fechacreacion = (reader.getInfo().get("fechacreacion") == null ? ""
                    : reader.getInfo().get("fechacreacion"));
            numpaginas = "" + reader.getNumberOfPages();
            tam = "" + NumberFormat.getInstance().format(reader.getFileLength());
            expediente = (reader.getInfo().get("Expediente") == null ? "" : reader.getInfo().get("Expediente"));
            cb = (reader.getInfo().get("codigobarras") == null ? "" : reader.getInfo().get("codigobarras"));
            notificarinstructor = (reader.getInfo().get("notificarinstructor") == null ? ""
                    : reader.getInfo().get("notificarinstructor"));
            tipodocumento = (reader.getInfo().get("tipodocumento") == null ? ""
                    : reader.getInfo().get("tipodocumento"));
            fechanotificacion = (reader.getInfo().get("fechanotificacion") == null ? ""
                    : reader.getInfo().get("fechanotificacion"));
            actualizarfase = (reader.getInfo().get("actualizarfase") == null ? ""
                    : reader.getInfo().get("actualizarfase"));
            ubicacionfisica = (reader.getInfo().get("ubicacionfisica") == null ? ""
                    : reader.getInfo().get("ubicacionfisica"));

        } catch (IOException ex) {
            Utilidades.escribeLog(
                    "Error -crearXmlLote- al leer el PDF " + dirorigen + fich + "  - Error " + ex.getMessage());
        }

        XmlDocumento doc = new XmlDocumento();
        doc.setExpediente(expediente);
        doc.setFichero(fich);
        doc.setNumPaginas(numpaginas);
        doc.setTam(tam);
        doc.setCb(cb);
        doc.setNotificarinstructor(notificarinstructor);
        doc.setTipodocumento(tipodocumento);
        doc.setFechanotificacion(fechanotificacion);
        doc.setActualizarfase(actualizarfase);
        doc.setUbicacionfisica(ubicacionfisica);
        Lote.add(doc);
    }

    Info.setFechacreacion(fechacreacion);
    Info.setFechadigita(fechadigita);
    Info.setFechaenvio(dia + "/" + mes + "/" + anio + " " + hora + ":" + minuto + ":" + segundo);
    Info.setIp(ip);
    Info.setNumdocumentos("" + ficheros.length);
    Info.setProceso(proceso);
    Info.setProvincia(provincia);
    Info.setUsuarioldap(usuarioldap);

    Lote.setInfo(Info);

    XStream xstream = new XStream();
    xstream.alias("Lote", XmlLote.class);
    xstream.alias("Info", XmlInfo.class);
    xstream.alias("Documento", XmlDocumento.class);

    try {
        xstream.toXML(Lote, new FileOutputStream(ficheroxml));
    } catch (FileNotFoundException ex) {
        Utilidades.escribeLog(
                "Error al escribir el fichero -crearXmlLote- " + ficheroxml + " - Error: " + ex.getMessage());
    }
}

From source file:es.sm2.openppm.front.utils.DocumentUtils.java

License:Open Source License

/**
 * Create PDF for Control Change//from  w  w w .  j  a v  a 2 s. c  om
 * @param idioma
 * @param project
 * @param change
 * @param preparedBy
 * @return
 * @throws DocumentException
 * @throws LogicException
 */
public static byte[] toPdf(ResourceBundle idioma, Project project, Changecontrol change, Employee preparedBy,
        final Image headerImg, final Image footerImg) throws DocumentException, LogicException {

    if (change == null) {
        throw new DocumentException("No change control found.");
    }

    if (preparedBy == null || preparedBy.getContact() == null) {
        throw new UserSendingException();
    }

    Document document = new Document(PageSize.A4);
    document.setMargins(70F, 70F, 38F, 38F); // Total Height: 842pt, Total Width: 595pt
    byte[] file = null;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    @SuppressWarnings("unused")
    PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);

    document.open();

    Font fontHeader = new Font(FontFamily.TIMES_ROMAN, 9, Font.BOLD);
    Font fontCell = new Font(FontFamily.TIMES_ROMAN, 9);
    Font tituloFont = new Font(FontFamily.TIMES_ROMAN, 16, Font.BOLD);

    document.add(new Paragraph(" ", tituloFont));
    document.add(new Paragraph(" ", tituloFont));
    document.add(new Paragraph(" ", fontHeader));
    Paragraph title = new Paragraph(idioma.getString("change_request").toUpperCase(), tituloFont);
    title.setAlignment(Paragraph.ALIGN_CENTER);
    document.add(title);

    // Header Table
    // Project info
    PdfPTable tableHeader = new PdfPTable(3);
    tableHeader.setWidthPercentage(100);
    tableHeader.setSpacingBefore(10);
    tableHeader.setSpacingAfter(15);

    int[] colWidth = new int[3];
    colWidth[0] = 40;
    colWidth[1] = 30;
    colWidth[2] = 30;
    tableHeader.setWidths(colWidth);

    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.project_name"), fontHeader, 1F, 0F, 0F, 1F));
    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.prepared_by"), fontHeader, 1F, 0F, 0F, 1F));
    tableHeader.addCell(prepareHeaderCell(idioma.getString("change_request.date"), fontHeader, 1F, 1F, 0F, 1F));

    tableHeader.addCell(prepareCell(project.getProjectName() + " / " + project.getAccountingCode(), fontCell,
            0F, 0F, 0F, 1F));
    tableHeader.addCell(prepareCell(preparedBy.getContact().getFullName(), fontCell, 0F, 0F, 0F, 1F));
    tableHeader.addCell(prepareCell(DateUtil.format(idioma, new Date()), fontCell, 0F, 1F, 0F, 1F));

    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.customer"), fontHeader, 1F, 0F, 0F, 1F));
    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.contact_name"), fontHeader, 1F, 0F, 0F, 1F));
    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.customer_type"), fontHeader, 1F, 1F, 0F, 1F));

    tableHeader.addCell(prepareCell(project.getCustomer() != null ? project.getCustomer().getName() : "",
            fontCell, 0F, 0F, 0F, 1F));
    tableHeader.addCell(prepareCell((project.getCustomer() != null ? project.getCustomer().getName() : "-"),
            fontCell, 0F, 0F, 0F, 1F));

    Customertype cusType = (project.getCustomer() != null ? project.getCustomer().getCustomertype() : null);
    tableHeader.addCell(prepareCell(cusType == null ? "" : cusType.getName(), fontCell, 0F, 1F, 0F, 1F));

    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.business_manager"), fontHeader, 1F, 0F, 0F, 1F));
    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.project_manager"), fontHeader, 1F, 0F, 0F, 1F));
    tableHeader.addCell(
            prepareHeaderCell(idioma.getString("change_request.originator"), fontHeader, 1F, 1F, 0F, 1F));

    Employee bm = project.getEmployeeByFunctionalManager();
    Employee pm = project.getEmployeeByProjectManager();

    tableHeader.addCell(prepareCell(bm == null ? "" : bm.getContact().getFullName(), fontCell, 0F, 0F, 1F, 1F));
    tableHeader.addCell(prepareCell(pm == null ? "" : pm.getContact().getFullName(), fontCell, 0F, 0F, 1F, 1F));
    tableHeader.addCell(prepareCell(change.getOriginator(), fontCell, 0F, 1F, 1F, 1F));

    document.add(tableHeader);

    // Change Information
    document.add(new Paragraph(idioma.getString("change_information")));

    PdfPTable tableInfo = new PdfPTable(1);
    tableInfo.setWidthPercentage(100);
    tableInfo.setSpacingBefore(10);
    tableInfo.setSpacingAfter(15);

    tableInfo.addCell(prepareHeaderCell(idioma.getString("change.change_type"), fontHeader, 1F, 1F, 0F, 1F));
    tableInfo.addCell(prepareCell(change.getChangetype().getDescription(), fontCell, 0F, 1F, 0F, 1F));

    String priorityDesc = "";
    if (change.getPriority().equals('H'))
        priorityDesc = idioma.getString("change.priority.high");
    if (change.getPriority().equals('N'))
        priorityDesc = idioma.getString("change.priority.normal");
    if (change.getPriority().equals('L'))
        priorityDesc = idioma.getString("change.priority.low");

    tableInfo.addCell(prepareHeaderCell(idioma.getString("change.priority"), fontHeader, 1F, 1F, 0F, 1F));
    tableInfo.addCell(prepareCell(priorityDesc, fontCell, 0F, 1F, 0F, 1F));

    tableInfo.addCell(prepareHeaderCell(idioma.getString("change.desc"), fontHeader, 1F, 1F, 0F, 1F));
    tableInfo.addCell(prepareCell(change.getDescription(), fontCell, 0F, 1F, 0F, 1F));

    tableInfo.addCell(
            prepareHeaderCell(idioma.getString("change.recommended_solution"), fontHeader, 1F, 1F, 0F, 1F));
    tableInfo.addCell(prepareCell(change.getRecommendedSolution(), fontCell, 0F, 1F, 1F, 1F));

    PdfPTable tableSubInfo = new PdfPTable(3);
    tableSubInfo.setWidthPercentage(100);

    //TODO MIGRACION
    tableSubInfo.addCell(prepareSubCell(idioma.getString("change.wbs_node"), fontHeader));
    tableSubInfo.addCell(prepareSubCell(idioma.getString("change.estimated_effort"), fontHeader));
    tableSubInfo.addCell(prepareSubCell(idioma.getString("change.estimated_cost"), fontHeader));

    tableSubInfo.addCell(
            prepareSubCell((change.getWbsnode() != null ? change.getWbsnode().getName() : ""), fontCell));
    tableSubInfo.addCell(prepareSubCell(
            (change.getEstimatedEffort() != null ? String.valueOf(change.getEstimatedEffort()) : ""),
            fontCell));
    tableSubInfo.addCell(prepareSubCell(
            (change.getEstimatedCost() != null ? ValidateUtil.toCurrency(change.getEstimatedCost()) : ""),
            fontCell));

    PdfPCell subTable = new PdfPCell(tableSubInfo);
    subTable.setBorderWidth(1F);

    tableInfo.addCell(subTable);

    tableInfo.addCell(prepareHeaderCell(idioma.getString("change.impact_desc"), fontHeader, 1F, 1F, 0F, 1F));
    tableInfo.addCell(prepareCell(change.getImpactDescription(), fontCell, 0F, 1F, 1F, 1F));

    document.add(tableInfo);

    document.add(new Paragraph(idioma.getString("change.resolution")));

    PdfPTable tableResolution = new PdfPTable(1);
    tableResolution.setWidthPercentage(100);
    tableResolution.setSpacingBefore(10);
    tableResolution.setSpacingAfter(15);

    tableResolution
            .addCell(prepareHeaderCell(idioma.getString("change.resolution"), fontHeader, 1F, 1F, 0F, 1F));
    tableResolution.addCell(
            prepareCell((change.getResolution() != null && change.getResolution() ? idioma.getString("yes")
                    : idioma.getString("no")), fontCell, 0F, 1F, 0F, 1F));

    tableResolution
            .addCell(prepareHeaderCell(idioma.getString("change.resolution_date"), fontHeader, 1F, 1F, 0F, 1F));
    tableResolution.addCell(
            prepareCell(DateUtil.format(idioma, change.getResolutionDate()), fontCell, 0F, 1F, 0F, 1F));

    tableResolution.addCell(
            prepareHeaderCell(idioma.getString("change.resolution_reason"), fontHeader, 1F, 1F, 0F, 1F));
    tableResolution.addCell(prepareCell(change.getResolutionReason(), fontCell, 0F, 1F, 1F, 1F));

    document.add(tableResolution);

    document.close();

    try {

        PdfReader reader = new PdfReader(outputStream.toByteArray());
        PdfStamper stamper = new PdfStamper(reader, outputStream);

        int numPag = reader.getNumberOfPages();

        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            setHeaderFooter(i, numPag, headerImg, footerImg, reader, stamper, idioma);
        }

        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    file = outputStream.toByteArray();

    return file;
}

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

License:Open Source License

/**
 * Split the given PDF file into multiple files using pages.
 * /*  www  .  j  a v a 2  s . 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.
 * //from w w w  . j a v  a 2s  .  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:example.Cap1BackupCode.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_CAP1.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   ww  w . j  a  va 2  s .  c o  m
                    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 == 11) {
                // System.out.println("open rank"+line);
                if (isNumeric(line.split(" ")[0])) {
                    if (line.split(" ")[0].trim().equals(null))
                        line = "0";
                    example.getCastDataObject().setOpen(line.split(" ")[0].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("project");
    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", object.getOpen());
            branch.append("sc", object.getSc());
            branch.append("st", object.getSt());
            branch.append("vj", object.getVj());
            branch.append("nt1", object.getNt1());
            branch.append("nt2", object.getNt2());
            branch.append("nt3", object.getNt3());
            branch.append("obc", 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();
}