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

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

Introduction

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

Prototype

@Deprecated
public RandomAccessFileOrArray(byte arrayIn[]) 

Source Link

Usage

From source file:com.betel.flowers.pdf.util.RemoveBlankPageFromPDF.java

public static void removeBlankPdfPages(String source, String destination)
        throws IOException, DocumentException {
    PdfReader r = null;//  w  w  w . j  a v a  2 s  .  c  om
    RandomAccessSourceFactory rasf = null;
    RandomAccessFileOrArray raf = null;
    Document document = null;
    PdfCopy writer = null;

    try {
        r = new PdfReader(source);
        // deprecated
        //    RandomAccessFileOrArray raf
        //           = new RandomAccessFileOrArray(pdfSourceFile);
        // itext 5.4.1
        rasf = new RandomAccessSourceFactory();
        raf = new RandomAccessFileOrArray(rasf.createBestSource(source));
        document = new Document(r.getPageSizeWithRotation(1));
        writer = new PdfCopy(document, new FileOutputStream(destination));
        document.open();
        PdfImportedPage page = null;

        for (int i = 1; i <= r.getNumberOfPages(); i++) {
            // first check, examine the resource dictionary for /Font or
            // /XObject keys.  If either are present -> not blank.
            PdfDictionary pageDict = r.getPageN(i);
            PdfDictionary resDict = (PdfDictionary) pageDict.get(PdfName.RESOURCES);
            boolean noFontsOrImages = true;
            if (resDict != null) {
                noFontsOrImages = resDict.get(PdfName.FONT) == null && resDict.get(PdfName.XOBJECT) == null;
            }

            if (!noFontsOrImages) {
                byte bContent[] = r.getPageContent(i, raf);
                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                bs.write(bContent);

                if (bs.size() > BLANK_THRESHOLD) {
                    page = writer.getImportedPage(r, i);
                    writer.addPage(page);
                }
            }
        }
    } finally {
        if (document != null) {
            document.close();
        }
        if (writer != null) {
            writer.close();
        }
        if (raf != null) {
            raf.close();
        }
        if (r != null) {
            r.close();
        }
    }
}

From source file:com.dev.saurabh.TiffToPdf.java

License:Open Source License

/**
 * @param args//from  ww w.j av  a2 s .c om
 * @throws DocumentException
 * @throws IOException
 */
public static void main(String[] args) throws DocumentException, IOException {

    String imgeFilename = "/home/saurabh/Downloads/image.tif";

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream("/home/saurabh/Desktop/out" + Math.random() + ".pdf"));
    writer.setStrictImageSequence(true);
    document.open();

    document.add(new Paragraph("Multipages tiff file"));
    Image image;
    RandomAccessFileOrArray ra = new RandomAccessFileOrArray(imgeFilename);
    int pages = TiffImage.getNumberOfPages(ra);
    for (int i = 1; i <= pages; i++) {
        image = TiffImage.getTiffImage(ra, i);
        Rectangle pageSize = new Rectangle(image.getWidth(), image.getHeight());
        document.setPageSize(pageSize);
        document.add(image);
        document.newPage();
    }

    document.close();

}

From source file:com.ephesoft.dcma.imagemagick.impl.ITextPDFCreator.java

License:Open Source License

/**
 * Converts specified tiff file into pdf.
 * /*from  w ww.  j av a  2s .  c  o m*/
 * @param tiffFile{@link File} to be converted into pdf.
 * @throws DCMAApplicationException if any error occurs while conversion.
 */
public static void convertTiffIntoPdf(final File tiffFile) throws DCMAApplicationException {
    if (null == tiffFile) {
        LOGGER.error("Unable to convert tiff file as specified file is null.");
    } else {
        com.itextpdf.text.Document document = null;
        RandomAccessFile randomAccessFile = null;
        RandomAccessFileOrArray randomAccessFileOrArray = null;
        FileChannelRandomAccessSource fileChannelRandomAccessSource = null;
        try {
            final String tiffFilePath = tiffFile.getAbsolutePath();
            if (tiffFilePath.endsWith(FileType.TIF.getExtensionWithDot())
                    || tiffFilePath.endsWith(FileType.TIFF.getExtensionWithDot())) {
                randomAccessFile = new RandomAccessFile(tiffFile, ICommonConstants.READ_MODE);
                fileChannelRandomAccessSource = new FileChannelRandomAccessSource(
                        randomAccessFile.getChannel());
                document = new com.itextpdf.text.Document();
                final int lastIndexofTiffExtension = tiffFilePath.toLowerCase()
                        .lastIndexOf(FileType.TIF.getExtensionWithDot());
                PdfWriter.getInstance(document,
                        new FileOutputStream(EphesoftStringUtil.concatenate(
                                tiffFilePath.substring(0, lastIndexofTiffExtension),
                                FileType.PDF.getExtensionWithDot())));
                document.open();
                randomAccessFileOrArray = new RandomAccessFileOrArray(fileChannelRandomAccessSource);
                final int pageCount = TiffImage.getNumberOfPages(randomAccessFileOrArray);
                Image image;
                for (int index = 1; index <= pageCount; index++) {
                    image = TiffImage.getTiffImage(randomAccessFileOrArray, index);
                    final Rectangle pageSize = new Rectangle(image.getWidth(), image.getHeight());
                    document.setPageSize(pageSize);
                    document.newPage();
                    document.add(image);
                }
                LOGGER.info(EphesoftStringUtil.concatenate(tiffFilePath, " successfully converted into PDF."));
            } else {
                LOGGER.error("Unable to convert as specified file is not a valid tiff file.");
            }
        } catch (final DocumentException e) {
            LOGGER.error("DocumentException is occurred while processing specified tiff file for conversion.");
            throw new DCMAApplicationException(EphesoftStringUtil
                    .concatenate("DocumentException occured while generating PDF", e.getMessage()), e);
        } catch (final IOException e) {
            LOGGER.error("IOException is occurred while processing specified tiff file for conversion.");
            throw new DCMAApplicationException(
                    EphesoftStringUtil.concatenate("IOException occured while generating PDF", e.getMessage()),
                    e);
        } finally {
            FileUtils.closeStream(randomAccessFileOrArray);
            FileUtils.closeFileChannelRandomAccessSource(fileChannelRandomAccessSource);
            FileUtils.closeResource(randomAccessFile);
            document.close();
        }

    }
}

From source file:com.ephesoft.dcma.imagemagick.MultiPageExecutor.java

License:Open Source License

/**
 * This method creates multi page pdf using IText.
 * /*ww w . ja  va 2  s  .c o  m*/
 * @param batchInstanceThread {@link BatchInstanceThread}
 * @param pages11 {@link String}
 * @param widthOfPdfPage int
 * @param heightOfPdfPage int
 */
public MultiPageExecutor(BatchInstanceThread batchInstanceThread, final String[] pages11,
        final int widthOfPdfPage, final int heightOfPdfPage) {
    if (pages11 != null && pages11.length > 0) {
        this.pages = new String[pages11.length];
        this.pages = pages11.clone();
        batchInstanceThread.add(new AbstractRunnable() {

            @Override
            public void run() {
                String pdf = pages[pages.length - 1];
                Document document = null;
                PdfWriter writer = null;
                RandomAccessFileOrArray randomAccessArray = null;
                try {
                    document = new Document(PageSize.LETTER, 0, 0, 0, 0);
                    writer = PdfWriter.getInstance(document, new FileOutputStream(pdf));
                    document.open();
                    int comps = 1;
                    int totalTiffImages = pages.length - 1;
                    int index = 0;
                    while (index < totalTiffImages) {
                        randomAccessArray = new RandomAccessFileOrArray(pages[index]);
                        comps = TiffImage.getNumberOfPages(randomAccessArray);
                        // Conversion statement
                        for (int tiffPageNumber = 0; tiffPageNumber < comps; ++tiffPageNumber) {
                            Image img = TiffImage.getTiffImage(randomAccessArray, tiffPageNumber + 1);
                            img.scaleToFit(widthOfPdfPage, heightOfPdfPage);
                            document.add(img);
                            document.newPage();
                        }
                        index++;
                    }
                } catch (Exception e) {
                    LOGGER.error("Error while creating pdf using iText" + e.getMessage(), e);
                    //pdf = null;
                } finally {
                    try {
                        if (document != null) {
                            document.close();
                        }
                        if (writer != null) {
                            writer.close();
                        }
                        if (randomAccessArray != null) {
                            randomAccessArray.close();
                        }
                    } catch (Exception e) {
                        LOGGER.error("Error while closing I/O streams for write PDF. " + e.getMessage());
                    }
                }
            }
        });
    }
}

From source file:com.ephesoft.dcma.util.PDFUtil.java

License:Open Source License

/**
 * API for getting the number of pages in the pdf file.
 * /*w w w .j  a va2s .co  m*/
 * @param filePath file path {@link String}
 * @return numberOfPage
 */
public static int getPDFPageCount(String filePath) {
    int numberOfPage = 0;
    PdfReader pdfReader = null;
    try {
        pdfReader = new PdfReader(new RandomAccessFileOrArray(filePath), null);
        numberOfPage = pdfReader.getNumberOfPages();
    } catch (IOException e) {
        LOG.error("Error in reading the file:" + filePath + UtilConstants.SPACE + e.getMessage(), e);
    } finally {
        if (pdfReader != null) {
            pdfReader.close();
        }
    }
    return numberOfPage;
}

From source file:com.ephesoft.dcma.util.TIFFUtil.java

License:Open Source License

/**
 * API for getting the number of pages in a tiff file.
 * /*from  ww  w  .j a v a 2s. c om*/
 * @param filePath file path {@link String}
 * @return numberOfPage
 */
public static int getTIFFPageCount(String filePath) {
    LOG.info("Counting number of pages in a tiff file = " + filePath);
    int numberOfPages = 0;
    RandomAccessFileOrArray randomAccessFile = null;
    String filePathLowerCase = filePath.toLowerCase(Locale.getDefault());
    if (!filePathLowerCase.endsWith(IUtilCommonConstants.EXTENSION_TIFF)
            && !filePathLowerCase.endsWith(IUtilCommonConstants.EXTENSION_TIF)) {
        LOG.info("File not a tiff file." + filePath);
    } else {
        try {
            randomAccessFile = new RandomAccessFileOrArray(filePath);
            numberOfPages = TiffImage.getNumberOfPages(randomAccessFile);
            LOG.info("Number of pages found = " + numberOfPages);
        } catch (IOException ioe) {
            LOG.error("IIO exception while reading the tiff file = " + filePath);
        } finally {
            if (null != randomAccessFile) {
                try {
                    randomAccessFile.close();
                } catch (IOException ioe) {
                    LOG.error("Error while closing the RandomAccessFileOrArray for file  = " + filePath);
                }
            }
        }
    }
    return numberOfPages;

}

From source file:com.github.albfernandez.joinpdf.JoinPdf.java

License:Open Source License

private void addTiff(final File file, final Document document, final PdfWriter writer) throws Exception {
    RandomAccessSource source = createRamdomAccessSource(file);
    RandomAccessFileOrArray ramdomAccess = new RandomAccessFileOrArray(source);
    int pages = getPageCount(file);
    for (int i = 1; i <= pages; i++) {
        Image image = TiffImage.getTiffImage(ramdomAccess, i);
        addImage(image, document, writer);
    }//w w  w .j  av a 2  s .c o m

}

From source file:com.github.albfernandez.joinpdf.JoinPdf.java

License:Open Source License

public static int getPageCountTif(final File file) throws IOException {
    RandomAccessSource source = createRamdomAccessSource(file);
    RandomAccessFileOrArray ramdomAccess = new RandomAccessFileOrArray(source);
    return TiffImage.getNumberOfPages(ramdomAccess);
}

From source file:com.pdf.GetPdf.java

public static void addTif(Document document, String path) throws DocumentException, IOException {
    RandomAccessFileOrArray ra = new RandomAccessFileOrArray(new URL(path));
    int n = TiffImage.getNumberOfPages(ra);
    Image img;/*w  w w.j  a v  a  2  s  .  c  om*/
    for (int i = 1; i <= n; i++) {
        img = TiffImage.getTiffImage(ra, i);
        img.scaleToFit(550, 800);
        document.add(img);
    }
}

From source file:com.primeleaf.krystal.util.PDFConverter.java

License:Open Source License

public File getConvertedFile(DocumentRevision documentRevision, Document document, String password)
        throws Exception {
    File tempFile = documentRevision.getDocumentFile();
    if ("TIF".equalsIgnoreCase(document.getExtension()) || "TIFF".equalsIgnoreCase(document.getExtension())) {
        try {/*from  w w  w . j ava2 s.c o m*/
            tempFile = File.createTempFile("temp", ".PDF");
            com.itextpdf.text.Document pdf = new com.itextpdf.text.Document();
            PdfWriter.getInstance(pdf, new FileOutputStream(tempFile));
            pdf.open();
            pdf.setMargins(0, 0, 0, 0);
            FileInputStream fis = new FileInputStream(documentRevision.getDocumentFile());
            RandomAccessFileOrArray file = new RandomAccessFileOrArray(fis);
            int pages = TiffImage.getNumberOfPages(file);
            for (int page = 1; page <= pages; page++) {
                Image img = TiffImage.getTiffImage(file, page);
                img.setAbsolutePosition(0f, 0f);
                img.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
                pdf.setMargins(0, 0, 0, 0);
                pdf.add(img);
                pdf.newPage();
            }
            fis.close();
            pdf.close();
            document.setExtension("PDF");
        } catch (Exception e) {
            tempFile = documentRevision.getDocumentFile();
            throw new Exception("Unable to convert TIFF Document to PDF");
        }
    } else if ("JPG".equalsIgnoreCase(document.getExtension())
            || "JPEG".equalsIgnoreCase(document.getExtension())
            || "PNG".equalsIgnoreCase(document.getExtension())
            || "BMP".equalsIgnoreCase(document.getExtension())
            || "GIF".equalsIgnoreCase(document.getExtension())) {
        try {
            tempFile = File.createTempFile("temp", ".PDF");
            Image img = Image.getInstance(documentRevision.getDocumentFile().getAbsolutePath());
            com.itextpdf.text.Document pdf = new com.itextpdf.text.Document(
                    new Rectangle(img.getWidth(), img.getHeight()), 0, 0, 0, 0);
            img.setAbsolutePosition(0f, 0f);
            PdfWriter.getInstance(pdf, new FileOutputStream(tempFile));
            pdf.open();
            pdf.add(img);
            pdf.close();
            document.setExtension("PDF");
        } catch (Exception e) {
            tempFile = documentRevision.getDocumentFile();
            throw new Exception("Unable to convert Image Document to PDF");
        }
    } else if ("PDF".equalsIgnoreCase(document.getExtension())) {
        tempFile = documentRevision.getDocumentFile();
    } else {
        String tempFilePath = "";
        String KRYSTAL_HOME = System.getProperty("krystal.home");
        if (KRYSTAL_HOME == null) {
            KRYSTAL_HOME = System.getProperty("user.dir");
            System.setProperty("krystal.home", KRYSTAL_HOME);
        }
        tempFilePath = KRYSTAL_HOME + File.separator + "/webapps/DMC/images/unsupport.pdf";
        tempFile = new File(tempFilePath);
    }
    return tempFile;
}