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:com.github.ukase.service.PdfRenderer.java

License:Open Source License

private void addSampleWatermark(ByteArrayOutputStream baos, char pdfVersion)
        throws IOException, DocumentException {
    PdfReader reader = new PdfReader(baos.toByteArray());
    baos.reset();//w  w w . j  a v  a 2 s . c o m
    Phrase phrase = new Phrase(waterMark.getText(), font);
    PdfStamper stamper = new PdfStamper(reader, baos, pdfVersion);
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        PdfContentByte canvas = stamper.getUnderContent(i);
        ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase, waterMark.getX(), waterMark.getY(),
                waterMark.getDegree());
    }
    stamper.close();
    reader.close();
}

From source file:com.joanzapata.PDFViewActivity.java

License:Open Source License

public void parsePdf(String pdf2, String txt) throws IOException {
    // String/*from   w  w  w  .j  a v  a 2s . c  o m*/
    // pdf1=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+
    // File.separator + "about.pdf";
    PdfReader reader = new PdfReader(pdf2);
    PdfReaderContentParser parser = new PdfReaderContentParser(reader);

    File file = getFileStreamPath("test.txt");

    if (!file.exists()) {
        file.createNewFile();
    }

    FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE);

    // PrintWriter out = new PrintWriter(new FileOutputStream(txt));
    TextExtractionStrategy strategy;
    for (int i = 1; i <= pageNumber; i++) {
        strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
        writer.write(strategy.getResultantText().getBytes());
        writer.flush();
    }
    writer.close();
    reader.close();
    String totalString = readFromFile();
    System.out.println(totalString);
    totalContent = totalString;
    String word = "Number of words  " + wordCount(totalString) + "\n";
    String averageWords = "Average length of words  " + " " + averageWords(totalString) + "\n";
    String sentenseCount = "Number of sentences  " + sentenseCount(totalString) + "\n";
    String averageSentenses = "Average length of sentences  " + averageSentense(totalString) + "\n";
    // String complexity=
    String readability = " Readability Index  " + getReadability(totalString) + "\n";

    String subject = "Subject Area  " + etSubject.getText().toString() + "\n";
    String article = "Type of the Article : " + etArticle.getText().toString() + "\n";
    String pages = " Pages  " + startPage + " to " + pageNumber + "\n";
    String book = "book name  " + etBookName.getText().toString() + "\n";
    String readername = "reader name  " + etReaderName.getText().toString() + "\n";
    totalInfo = readername + book + subject + "\n" + article + pages + word + averageWords + sentenseCount
            + averageSentenses + readability;
    displayMessage(totalInfo);

}

From source file:com.ots.jsp1.itext.ADAStamper.java

License:Open Source License

public void addADAAsWatermark(InputStream inStream, OutputStream outputStream, String ADA)
        throws DocumentException, IOException {
    PdfStamper stamper = null;//from w w  w .j a va2  s . c o  m
    PdfReader reader = null;
    try {

        reader = new PdfReader(inStream);
        //The zero byte means we dont want to change the version number of the PDF file.
        //true->not to change any of the original bytes
        stamper = new PdfStamper(reader, outputStream, '\0', true);
        int numberOfPages = reader.getNumberOfPages();

        for (int currentPage = 1; currentPage <= numberOfPages; currentPage++) {

            PdfAppearance canvas = PdfAppearance.createAppearance(stamper.getWriter(), 100, 30);
            canvas.setFontAndSize(
                    BaseFont.createFont(fontFilePath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED, true), 11);
            Rectangle pageSize = reader.getPageSizeWithRotation(currentPage);
            Rectangle watermarkPosition = new Rectangle(pageSize.getRight() - 150, pageSize.getTop() - 30,
                    pageSize.getRight() - 50, pageSize.getTop() - 10, 0);
            PdfAnnotation annotation = PdfAnnotation.createFreeText(stamper.getWriter(), watermarkPosition, ADA,
                    canvas);
            annotation.put(PdfName.F, new PdfNumber(PdfAnnotation.FLAGS_READONLY));

            //  annotation.put(PdfName.FONT, canvas);
            //  PdfAnnotation annotation = PdfAnnotation.createText(stamper.getWriter(), watermarkPosition, "", ADA, true, "Key");
            // 

            PdfBorderDictionary borderDictionary = new PdfBorderDictionary(0, PdfBorderDictionary.STYLE_SOLID);

            annotation.setBorderStyle(borderDictionary);
            stamper.addAnnotation(annotation, currentPage);
        }
    } finally {
        stamper.close();
        reader.close();
    }

}

From source file:com.poet.ar.remover.AnnotationRemover.java

/**
 * @param fileIn  pdf filename you want to remove annotation
 * @param fileOut removed annotation pdf save path
 * @throws IOException//from   ww  w.  j a  v a  2s .c  o m
 * @throws DocumentException
 */
public static void doRemove(String fileIn, String fileOut) throws IOException, DocumentException {

    logger.debug("starting process file: " + fileIn);

    PdfReader reader = new PdfReader(fileIn);

    FileOutputStream fos = new FileOutputStream(fileOut);
    PdfStamper stamper = new PdfStamper(reader, fos);

    removeInfo(reader, stamper);

    int pageNums = reader.getNumberOfPages();

    int totalAnnoCount = 0;
    int totalContentCount = 0;
    for (int i = 1; i <= pageNums; i++) {

        PdfDictionary page = reader.getPageNRelease(i);

        int annoCount = doRemoveAnnotation(page);
        int contentCount = doRemoveContent(page);

        totalAnnoCount += annoCount;
        totalContentCount += contentCount;

        logger.debug("removed " + annoCount + " annotation(s) in page " + i + " ,in file: " + fileIn);
        logger.debug("removed " + contentCount + " content(s) in page " + i + " ,in file: " + fileIn);
    }

    stamper.close();
    fos.close();
    reader.close();

    logger.debug("success removed " + totalAnnoCount + " annotation(s), " + totalContentCount
            + " content(s), with output file: " + fileOut);
}

From source file:com.preselect.pdfservice.tasks.PdfConversionTask.java

License:Open Source License

public static void splitIText(OutlineItems outline, String inputFile, String outputPath)
        throws IOException, BadPdfFormatException, DocumentException {
    List<OutlineItem> outlineItems = filter(having(on(OutlineItem.class).getLevel(), equalTo(1)),
            outline.getItems());//  ww  w . ja  va 2s . c om
    PdfReader reader = new PdfReader(inputFile);
    reader.consolidateNamedDestinations();
    int numberOfPages = reader.getNumberOfPages();

    // Check if there are outline items
    if (outlineItems.size() <= 0) {
        throw new IllegalArgumentException("No outline items found!");
    }
    // Find start and end of each chapter
    for (int i = 0; i < outlineItems.size(); i++) {
        OutlineItem outlineItem = outlineItems.get(i);
        // fix for first chapter start at zero
        int chapterStart = outlineItem.getPage() < 1 ? 1 : outlineItem.getPage();
        int chapterEnd;
        // if last chapter is not reached yet ...
        if (outlineItems.size() > i + 1) {
            // ... get first page of next chapter and ...
            chapterEnd = outlineItems.get(i + 1).getPage();
            // ... reduce it for one page, if it's not a one page chapter
            if (chapterEnd != chapterStart) {
                chapterEnd--;
            }
        } else {
            // Otherwise set the end of last chapter to the end of the document
            chapterEnd = numberOfPages;
        }
        File file = new File(outputPath);
        file.mkdirs();
        String path = outputPath + File.separator + outlineItem.getId() + ".pdf";
        copyDocument(reader, chapterStart, chapterEnd, path, outline);

        Logger.getLogger(Task.class.getName()).log(Level.INFO, "Chapter: {0} - Start:{1} <-> End: {2}",
                new Object[] { outlineItem.getTitle(), chapterStart, chapterEnd });
    }
    reader.close();
}

From source file:com.sustainalytics.crawlerfilter.PDFTitleGeneration.java

License:Apache License

public static String extractITextText(String pdf) {
    PdfReader reader = null;
    try {// w  w  w . j  a  v a  2  s  . c om
        reader = new PdfReader(pdf);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    PdfReaderContentParser parser = new PdfReaderContentParser(reader);
    TextExtractionStrategy strategy;
    String text = "";
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        try {
            strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
            text += strategy.getResultantText();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    reader.close();

    return text;
}

From source file:com.sustainalytics.crawlerfilter.PDFtoText.java

License:Apache License

public static String extractITextText(String pdf) {
    PdfReader reader = null;
    try {//from w  w  w.j a v a 2s  . c om
        reader = new PdfReader(pdf);
    } catch (IOException e) {
        logger.info("Error in reading file with iText parser\n");
    }
    PdfReaderContentParser parser = new PdfReaderContentParser(reader);
    TextExtractionStrategy strategy;
    String text = "";
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        try {
            strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
            text += strategy.getResultantText();
        } catch (IOException e) {
            logger.info("Error in parsing with iText parser\n");
        }
        logger.info("PDF text extracted from " + pdf + "\n");
    }
    reader.close();

    return text;
}

From source file:com.swisscom.ais.itext.PDF.java

License:Open Source License

/** 
 * Add external revocation information to DSS Dictionary, to enable Long Term Validation (LTV) in Adobe Reader
 * //from  w w  w. j  a  v  a2s.  c  o m
 * @param ocspArr List of OCSP Responses as base64 encoded String
 * @param crlArr  List of CRLs as base64 encoded String
 * @throws Exception 
 */
public void addValidationInformation(ArrayList<String> ocspArr, ArrayList<String> crlArr) throws Exception {
    if (ocspArr == null && crlArr == null)
        return;

    PdfReader reader = new PdfReader(outputFilePath);

    // Check if source pdf is not protected by a certification
    if (reader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED)
        throw new Exception(
                "Could not apply revocation information (LTV) to the DSS Dictionary. Document contains a certification that does not allow any changes.");

    Collection<byte[]> ocspColl = new ArrayList<byte[]>();
    Collection<byte[]> crlColl = new ArrayList<byte[]>();

    // Decode each OCSP Response (String of base64 encoded form) and add it to the Collection (byte[])
    if (ocspArr != null) {
        for (String ocspBase64 : ocspArr) {
            OCSPResp ocspResp = new OCSPResp(new ByteArrayInputStream(Base64.decode(ocspBase64)));
            BasicOCSPResp basicResp = (BasicOCSPResp) ocspResp.getResponseObject();

            if (Soap._debugMode) {
                System.out.println("\nEmbedding OCSP Response...");
                System.out.println("Status                : " + ((ocspResp.getStatus() == 0) ? "GOOD" : "BAD"));
                System.out.println("Produced at           : " + basicResp.getProducedAt());
                System.out.println("This Update           : " + basicResp.getResponses()[0].getThisUpdate());
                System.out.println("Next Update           : " + basicResp.getResponses()[0].getNextUpdate());
                System.out.println("X509 Cert Issuer      : " + basicResp.getCerts()[0].getIssuer());
                System.out.println("X509 Cert Subject     : " + basicResp.getCerts()[0].getSubject());
                System.out.println(
                        "Responder ID X500Name : " + basicResp.getResponderId().toASN1Object().getName());
                System.out.println("Certificate ID        : "
                        + basicResp.getResponses()[0].getCertID().getSerialNumber().toString() + " ("
                        + basicResp.getResponses()[0].getCertID().getSerialNumber().toString(16).toUpperCase()
                        + ")");
            }

            ocspColl.add(basicResp.getEncoded()); // Add Basic OCSP Response to Collection (ASN.1 encoded representation of this object)
        }
    }

    // Decode each CRL (String of base64 encoded form) and add it to the Collection (byte[])
    if (crlArr != null) {
        for (String crlBase64 : crlArr) {
            X509CRL x509crl = (X509CRL) CertificateFactory.getInstance("X.509")
                    .generateCRL(new ByteArrayInputStream(Base64.decode(crlBase64)));

            if (Soap._debugMode) {
                System.out.println("\nEmbedding CRL...");
                System.out.println("IssuerDN                    : " + x509crl.getIssuerDN());
                System.out.println("This Update                 : " + x509crl.getThisUpdate());
                System.out.println("Next Update                 : " + x509crl.getNextUpdate());
                System.out.println(
                        "No. of Revoked Certificates : " + ((x509crl.getRevokedCertificates() == null) ? "0"
                                : x509crl.getRevokedCertificates().size()));
            }

            crlColl.add(x509crl.getEncoded()); // Add CRL to Collection (ASN.1 DER-encoded form of this CRL)
        }
    }

    byteArrayOutputStream = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(reader, byteArrayOutputStream, '\0', true);
    LtvVerification validation = stamper.getLtvVerification();

    // Add the CRL/OCSP validation information to the DSS Dictionary
    boolean addVerification = false;
    for (String sigName : stamper.getAcroFields().getSignatureNames()) {
        addVerification = validation.addVerification(sigName, // Signature Name
                ocspColl, // OCSP
                crlColl, // CRL
                null // certs
        );
    }

    validation.merge(); // Merges the validation with any validation already in the document or creates a new one.

    stamper.close();
    reader.close();

    // Save to (same) file
    OutputStream outputStream = new FileOutputStream(outputFilePath);
    byteArrayOutputStream.writeTo(outputStream);

    if (Soap._debugMode) {
        if (addVerification)
            System.out.println("\nOK merging LTV validation information to " + outputFilePath);
        else
            System.out.println("\nFAILED merging LTV validation information to " + outputFilePath);
    }

    byteArrayOutputStream.close();
    outputStream.close();
}

From source file:com.test.itext.Renderer.java

private byte[] populateXFA(byte[] templateBytes, byte[] xfaDataBytes) throws RuntimeException {

    // Create an output stream for the rendered doc
    ByteArrayOutputStream rendered = new ByteArrayOutputStream();

    try {//ww  w.  ja va2s  . c o m
        PdfReader reader = new PdfReader(templateBytes);
        PdfStamper stamper = new PdfStamper(reader, rendered);
        AcroFields form = stamper.getAcroFields();
        XfaForm xfa = form.getXfa();
        xfa.fillXfaForm(new ByteArrayInputStream(xfaDataBytes));
        stamper.close();
        reader.close();
    } catch (IOException e) {
        String msg = "An IOException was thrown while trying to populate the XFA form. Msg=" + e.getMessage();
        e.printStackTrace();
        throw new RuntimeException(msg);
    } catch (DocumentException e) {
        String msg = "A DocumentException was thrown while trying to populate the XFA form. Msg="
                + e.getMessage();
        e.printStackTrace();
        throw new RuntimeException(msg);
    }

    return rendered.toByteArray();
}

From source file:com.tommontom.pdfsplitter.PdfSplit.java

public void pdfSplit(String path) throws IOException, DocumentException, InterruptedException {
    // TODO Instead of hard code path, pass in as argument
    File folder = new File(path);
    FileNameFilter FileFilter = new FileNameFilter();
    File[] listOfFiles = folder.listFiles(FileFilter); /* Stores the listing of the files */

    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }/*from   ww  w  . j  a  v a  2  s.c  o m*/
        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        Document document = new Document(PageSize.LETTER, 0, 0, 0,
                0); /* instantiates a new document to be made */

        int k = 0;
        int numPages = pdfFileReader.getNumberOfPages();
        // Split on a space '\s'
        // Determine number of pages by difference of lot numbers
        // Read in the source document
        // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf
        // Create a copy of the orignal source file. We will pick specific pages out below
        for (int j = 1; j < numPages + 1; j++) {
            String FileName = (fileNameWithoutExt); /* Dynamic file name */

            PdfCopy copy = new PdfCopy(document,
                    new FileOutputStream(path + "\\" + FileName + "(" + j + ")" + ".pdf"));
            document.open();
            copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */

            deleteFile[k] = path + "\\" + FileName + "(" + j + 1 + ")" + ".pdf";
            k++;
            if (j == 1) {
                newFileListing = ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            } else if (j > 1) {
                newFileListing += ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            }
            document.close();

        }

        System.out.println("Number of Documents Created:" + numPages);
        pdfFileReader.close();
    }
}