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

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

Introduction

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

Prototype

public Rectangle getPageSizeWithRotation(final PdfDictionary page) 

Source Link

Document

Gets the rotated page from a page dictionary.

Usage

From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java

License:Apache License

/**
 * Applies an image watermark/*from w  w w  .  java 2s  . co m*/
 * 
 * @param reader
 * @param writer
 * @param options
 * @throws Exception
 */
private void imageAction(Action ruleAction, NodeRef actionedUponNodeRef, NodeRef watermarkNodeRef,
        ContentReader actionedUponContentReader, ContentReader watermarkContentReader,
        Map<String, Object> options) {

    PdfStamper stamp = null;
    File tempDir = null;
    ContentWriter writer = null;

    try {
        // get a temp file to stash the watermarked PDF in before moving to
        // repo
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());

        // get the PDF input stream and create a reader for iText
        PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream());
        stamp = new PdfStamper(reader, new FileOutputStream(file));
        PdfContentByte pcb;

        // get a com.itextpdf.text.Image object via java.imageio.ImageIO
        Image img = Image.getInstance(ImageIO.read(watermarkContentReader.getContentInputStream()), null);

        // get the PDF pages and position
        String pages = (String) options.get(PARAM_PAGE);
        String position = (String) options.get(PARAM_POSITION);
        String depth = (String) options.get(PARAM_WATERMARK_DEPTH);

        // image requires absolute positioning or an exception will be
        // thrown
        // set image position according to parameter. Use
        // PdfReader.getPageSizeWithRotation
        // to get the canvas size for alignment.
        img.setAbsolutePosition(100f, 100f);

        // stamp each page
        int numpages = reader.getNumberOfPages();
        for (int i = 1; i <= numpages; i++) {
            Rectangle r = reader.getPageSizeWithRotation(i);
            // set stamp position
            if (position.equals(POSITION_BOTTOMLEFT)) {
                img.setAbsolutePosition(0, 0);
            } else if (position.equals(POSITION_BOTTOMRIGHT)) {
                img.setAbsolutePosition(r.getWidth() - img.getWidth(), 0);
            } else if (position.equals(POSITION_TOPLEFT)) {
                img.setAbsolutePosition(0, r.getHeight() - img.getHeight());
            } else if (position.equals(POSITION_TOPRIGHT)) {
                img.setAbsolutePosition(r.getWidth() - img.getWidth(), r.getHeight() - img.getHeight());
            } else if (position.equals(POSITION_CENTER)) {
                img.setAbsolutePosition(getCenterX(r, img), getCenterY(r, img));
            }

            // if this is an under-text stamp, use getUnderContent.
            // if this is an over-text stamp, usse getOverContent.
            if (depth.equals(DEPTH_OVER)) {
                pcb = stamp.getOverContent(i);
            } else {
                pcb = stamp.getUnderContent(i);
            }

            // only apply stamp to requested pages
            if (checkPage(pages, i, numpages)) {
                pcb.addImage(img);
            }
        }

        stamp.close();

        // Get a writer and prep it for putting it back into the repo
        //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination
        NodeRef destinationNode = createDestinationNode(file.getName(),
                (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef);
        writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT,
                true);

        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);

        // Put it in the repo
        writer.putContent(file);

        // delete the temp file
        file.delete();
    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }

        if (stamp != null) {
            try {
                stamp.close();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java

License:Apache License

/**
 * Applies a text watermark (current date, user name, etc, depending on
 * options)/*from w w w.j  av a 2s. co m*/
 * 
 * @param reader
 * @param writer
 * @param options
 */
private void textAction(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader,
        Map<String, Object> options) {

    PdfStamper stamp = null;
    File tempDir = null;
    ContentWriter writer = null;
    String watermarkText;
    StringTokenizer st;
    Vector<String> tokens = new Vector<String>();

    try {
        // get a temp file to stash the watermarked PDF in before moving to
        // repo
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());

        // get the PDF input stream and create a reader for iText
        PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream());
        stamp = new PdfStamper(reader, new FileOutputStream(file));
        PdfContentByte pcb;

        // get the PDF pages and position
        String pages = (String) options.get(PARAM_PAGE);
        String position = (String) options.get(PARAM_POSITION);
        String depth = (String) options.get(PARAM_WATERMARK_DEPTH);

        // create the base font for the text stamp
        BaseFont bf = BaseFont.createFont((String) options.get(PARAM_WATERMARK_FONT), BaseFont.CP1250,
                BaseFont.EMBEDDED);

        // get watermark text and process template with model
        String templateText = (String) options.get(PARAM_WATERMARK_TEXT);
        Map<String, Object> model = buildWatermarkTemplateModel(actionedUponNodeRef);
        StringWriter watermarkWriter = new StringWriter();
        freemarkerProcessor.processString(templateText, model, watermarkWriter);
        watermarkText = watermarkWriter.getBuffer().toString();

        // tokenize watermark text to support multiple lines and copy tokens
        // to vector for re-use
        st = new StringTokenizer(watermarkText, "\r\n", false);
        while (st.hasMoreTokens()) {
            tokens.add(st.nextToken());
        }

        // stamp each page
        int numpages = reader.getNumberOfPages();
        for (int i = 1; i <= numpages; i++) {
            Rectangle r = reader.getPageSizeWithRotation(i);

            // if this is an under-text stamp, use getUnderContent.
            // if this is an over-text stamp, use getOverContent.
            if (depth.equals(DEPTH_OVER)) {
                pcb = stamp.getOverContent(i);
            } else {
                pcb = stamp.getUnderContent(i);
            }

            // set the font and size
            float size = Float.parseFloat((String) options.get(PARAM_WATERMARK_SIZE));
            pcb.setFontAndSize(bf, size);

            // only apply stamp to requested pages
            if (checkPage(pages, i, numpages)) {
                writeAlignedText(pcb, r, tokens, size, position);
            }
        }

        stamp.close();

        // Get a writer and prep it for putting it back into the repo
        //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination
        NodeRef destinationNode = createDestinationNode(file.getName(),
                (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef);
        writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT,
                true);
        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);

        // Put it in the repo
        writer.putContent(file);

        // delete the temp file
        file.delete();
    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }

        if (stamp != null) {
            try {
                stamp.close();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.ednovo.gooru.domain.service.resource.ResourceServiceImpl.java

License:Open Source License

/**
 * @param mainFileUrl/*from www .j  ava 2 s  .  com*/
 *            : PDF file that has to be splitted
 * @param splittedPageSize
 *            : Page size of each splitted files
 */
private static String splitAndSaveChapter(String mainFileUrl, int pageBeginNum, int pageEndNum, String name) {
    try {
        PdfReader reader = new PdfReader(mainFileUrl);

        int splittedPageSize = pageEndNum - pageBeginNum + 1;
        int pageNum = pageBeginNum;

        String chapterUrl = mainFileUrl.substring(0, mainFileUrl.indexOf(DOT_PDF)) + "-" + name + DOT_PDF;

        Document document = new Document(reader.getPageSizeWithRotation(1));

        FileOutputStream fos = new FileOutputStream(chapterUrl);
        PdfCopy writer = new PdfCopy(document, fos);
        Map<String, String> info = reader.getInfo();

        document.open();
        if ((info != null) && (info.get(_AUTHOR) != null)) {
            document.addAuthor(info.get(_AUTHOR));
        }

        document.addTitle(name);

        for (int offset = 0; offset < splittedPageSize && (pageNum + offset) < pageEndNum; offset++) {
            PdfImportedPage page = writer.getImportedPage(reader, pageNum + offset);
            writer.addPage(page);
        }

        document.close();
        writer.close();
        return chapterUrl;

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.gmdev.pdftrick.engine.MergeFiles.java

License:Open Source License

/**
 * Materially multiple pdf files are written merged file on a disk 
 * @param list//w  w  w.j  av a2s .c o m
 * @param outputStream
 * @throws DocumentException
 * @throws IOException
 */
private void doMerge(List<StreamPwdContainer> list, OutputStream outputStream)
        throws DocumentException, IOException {
    HashMap<Integer, String> rotationFromPages = factory.getRotationFromPages();
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();
    PdfContentByte cb = writer.getDirectContent();

    int z = 0;
    for (StreamPwdContainer boom : list) {

        InputStream in = boom.getIn();
        PdfReader reader = null;
        if (!boom.getPwd().equalsIgnoreCase("")) {
            reader = new PdfReader(in, boom.getPwd().getBytes());
        } else {
            reader = new PdfReader(in);
        }

        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            z++;
            int rotation = reader.getPageRotation(i);

            //set size
            Rectangle pageSize_ = reader.getPageSize(i);
            Rectangle pageSize = null;
            if (rotation == 270 || rotation == 90) {
                pageSize = new Rectangle(pageSize_.getHeight(), pageSize_.getWidth());
            } else {
                pageSize = pageSize_;
            }

            document.setPageSize(pageSize);
            writer.setCropBoxSize(pageSize);

            document.newPage();

            // import the page from source pdf
            PdfImportedPage page = writer.getImportedPage(reader, i);

            // add the page to the destination pdf
            if (rotation == 270) {
                cb.addTemplate(page, 0, 1.0f, -1.0f, 0, reader.getPageSizeWithRotation(i).getWidth(), 0);
                rotationFromPages.put(z, "" + rotation);
            } else if (rotation == 180) {
                cb.addTemplate(page, -1f, 0, 0, -1f, 0, 0);
                rotationFromPages.put(z, "" + rotation);
            } else if (rotation == 90) {
                cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
                rotationFromPages.put(z, "" + rotation);
            } else {
                cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
            }
        }
        in.close();
    }
    outputStream.flush();
    document.close();
    outputStream.close();
}

From source file:org.h819.commons.file.MyPDFUtils.java

/**
 * ??//from   w w w.ja  va  2  s. c  o  m
 *
 * @param srcPdf         ?
 * @param destPdf        
 * @param waterMarkText  ?
 * @param waterMarkImage ?
 */
public static void addWaterMarkFile(File srcPdf, File destPdf, String waterMarkText, File waterMarkImage)
        throws IOException, DocumentException {

    if (waterMarkText == null && waterMarkImage == null)
        throw new FileNotFoundException(waterMarkText + " " + waterMarkImage + " all null.");

    if (srcPdf == null || !srcPdf.exists() || !srcPdf.isFile())
        throw new FileNotFoundException("pdf file :  '" + srcPdf + "' does not exsit.");

    if (!FilenameUtils.getExtension(srcPdf.getAbsolutePath()).toLowerCase().equals("pdf"))
        return;

    if (waterMarkImage != null) {
        if (!waterMarkImage.exists() || !waterMarkImage.isFile())
            throw new FileNotFoundException("img file :  '" + srcPdf + "' does not exsit.");

        if (!FilenameUtils.getExtension(waterMarkImage.getAbsolutePath()).toLowerCase().equals("png"))
            throw new FileNotFoundException("image file '" + srcPdf
                    + "'  not png.(???? pdf )");
    }

    PdfReader reader = getPdfReader(srcPdf);

    int n = reader.getNumberOfPages();
    PdfStamper stamper = getPdfStamper(srcPdf, destPdf);

    //
    //        HashMap<String, String> moreInfo = new HashMap<String, String>();
    //        moreInfo.put("Author", "H819 create");
    //        moreInfo.put("Producer", "H819 Producer");
    //        Key = CreationDate, Value = D:20070425182920
    //        Key = Producer, Value = TH-OCR 2000 (C++/Win32)
    //        Key = Author, Value = TH-OCR 2000
    //        Key = Creator, Value = TH-OCR PDF Writer

    // stamp.setMoreInfo(moreInfo);

    // text
    Phrase text = null;
    if (waterMarkText != null) {
        //
        Font bfont = getPdfFont();
        bfont.setSize(35);
        bfont.setColor(new BaseColor(192, 192, 192));
        text = new Phrase(waterMarkText, bfont);
    }
    // image watermark
    Image img = null;
    float w = 0;
    float h = 0;
    if (waterMarkImage != null) {
        img = Image.getInstance(waterMarkImage.getAbsolutePath());
        w = img.getScaledWidth();
        h = img.getScaledHeight();
        //  img.
        img.setRotationDegrees(45);

    }

    // transparency
    PdfGState gs1 = new PdfGState();
    gs1.setFillOpacity(0.5f);
    // properties
    PdfContentByte over;
    Rectangle pageSize;
    float x, y;
    // loop over every page
    for (int i = 1; i <= n; i++) {
        pageSize = reader.getPageSizeWithRotation(i);
        x = (pageSize.getLeft() + pageSize.getRight()) / 2;
        y = (pageSize.getTop() + pageSize.getBottom()) / 2;
        //  pdf pdf ???
        over = stamper.getOverContent(i);
        // ?
        // over = stamp.getUnderContent(i);
        // ?? over.beginText(); over.endText(); ?
        // ,?,:????
        over.saveState(); //??
        over.setGState(gs1);

        if (waterMarkText != null && waterMarkImage != null) { // 
            if (i % 2 == 1) {
                ColumnText.showTextAligned(over, Element.ALIGN_CENTER, text, x, y, 45);
            } else
                over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
        } else if (waterMarkText != null) { //?

            ColumnText.showTextAligned(over, Element.ALIGN_CENTER, text, x, y, 45);
            //?? ,?, :?????
            // ...

        } else { //?
            over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
        }

        over.restoreState();//???
    }

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

}

From source file:org.sejda.impl.itext5.component.AbstractPdfCopier.java

License:Open Source License

/**
 * initialize the copier using the given reader and the given output version.
 * //  www .j  a  v a2s  .c o m
 * @param reader
 * @param outputStream
 *            the output stream to write to.
 * @param version
 *            version for the created pdf copy, if null the version number is taken from the input {@link PdfReader}
 */
void init(PdfReader reader, OutputStream outputStream, PdfVersion version) throws TaskException {
    try {
        pdfDocument = new Document(reader.getPageSizeWithRotation(1));
        pdfCopy = new PdfSmartCopy(pdfDocument, outputStream);
        if (version == null) {
            pdfCopy.setPdfVersion(reader.getPdfVersion());
        } else {
            pdfCopy.setPdfVersion(version.getVersionAsCharacter());
        }
        pdfDocument.addCreator(Sejda.CREATOR);
    } catch (DocumentException e) {
        throw new TaskException("An error occurred opening the PdfSmartCopy.", e);
    }
}

From source file:oscar.dms.IncomingDocUtil.java

License:Open Source License

public static void deletePage(String queueId, String myPdfDir, String myPdfName, String PageNumberToDelete)
        throws Exception {
    long lastModified;
    String filePathName, tempFilePathName;

    tempFilePathName = getIncomingDocumentFilePath(queueId, myPdfDir) + File.separator + "T" + myPdfName;
    filePathName = getIncomingDocumentFilePathName(queueId, myPdfDir, myPdfName);

    File f = new File(filePathName);
    lastModified = f.lastModified();/*from  ww  w.  j a v a2  s  .c  om*/
    f.setReadOnly();

    String deletePath = getIncomingDocumentDeletedFilePath(queueId, myPdfDir) + File.separator;
    String deletePathFileName = "";
    int index = myPdfName.indexOf(".pdf");

    String myPdfNameF = myPdfName.substring(0, index);
    String myPdfNameExt = myPdfName.substring(index, myPdfName.length());

    PdfReader reader = null;
    Document document = null;
    PdfCopy copy = null;
    PdfCopy deleteCopy = null;

    try {
        reader = new PdfReader(filePathName);
        deletePathFileName = deletePath + myPdfNameF + "d" + PageNumberToDelete + "of"
                + Integer.toString(reader.getNumberOfPages()) + myPdfNameExt;

        document = new Document(reader.getPageSizeWithRotation(1));
        copy = new PdfCopy(document, new FileOutputStream(tempFilePathName));
        deleteCopy = new PdfCopy(document, new FileOutputStream(deletePathFileName));
        document.open();

        for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++) {
            if (!(pageNumber == (Integer.parseInt(PageNumberToDelete)))) {
                copy.addPage(copy.getImportedPage(reader, pageNumber));
            } else {
                deleteCopy.addPage(copy.getImportedPage(reader, pageNumber));
            }
        }
    } catch (Exception e) {
        throw (e);
    } finally {
        try {
            if (copy != null) {
                copy.close();
            }
            if (deleteCopy != null) {
                deleteCopy.close();
            }

            if (document != null) {
                document.close();
            }

            if (reader != null) {
                reader.close();
            }

        } catch (Exception e) {
            throw (e);
        }
    }

    boolean success;
    if (!oscar.OscarProperties.getInstance().getBooleanProperty("INCOMINGDOCUMENT_RECYCLEBIN", "true")) {
        File f1 = new File(deletePathFileName);
        success = f1.delete();
        if (!success) {
            throw new Exception("Error in deleting file:" + deletePathFileName);
        }
    }

    success = f.delete();
    if (success) {
        File f1 = new File(tempFilePathName);
        f1.setLastModified(lastModified);
        success = f1.renameTo(new File(filePathName));
        if (!success) {
            throw new Exception("Error in renaming file from:" + tempFilePathName + "to " + filePathName);
        }
    } else {
        throw new Exception("Error in deleting file:" + filePathName);
    }
}

From source file:oscar.dms.IncomingDocUtil.java

License:Open Source License

public static void extractPage(String queueId, String myPdfDir, String myPdfName, String pageNumbersToExtract)
        throws Exception {
    long lastModified;
    String filePathName, tempFilePathName;

    tempFilePathName = getIncomingDocumentFilePath(queueId, myPdfDir) + File.separator + "T" + myPdfName;
    filePathName = getIncomingDocumentFilePathName(queueId, myPdfDir, myPdfName);

    File f = new File(filePathName);
    lastModified = f.lastModified();//  ww w  .j  a v a 2s  . co m
    f.setReadOnly();

    String extractPath = getIncomingDocumentFilePath(queueId, myPdfDir) + File.separator;
    int index = myPdfName.toLowerCase().indexOf(".pdf");
    String myPdfNameF = myPdfName.substring(0, index);
    String myPdfNameExt = myPdfName.substring(index, myPdfName.length());

    ArrayList<String> extractList = new ArrayList<String>();
    int startPage, endPage;
    boolean cancelExtract = false;

    PdfReader reader = null;
    Document document = null;
    PdfCopy copy = null;
    PdfCopy extractCopy = null;

    try {
        reader = new PdfReader(filePathName);
        extractPath = extractPath + myPdfNameF + "E" + Integer.toString(reader.getNumberOfPages())
                + myPdfNameExt;

        for (int pgIndex = 0; pgIndex <= reader.getNumberOfPages(); pgIndex++) {
            extractList.add(pgIndex, "0");
        }

        String tmpPageNumbersToExtract = pageNumbersToExtract;
        String[] pageList = tmpPageNumbersToExtract.split(",");
        for (int i = 0; i < pageList.length; i++) {
            if (!pageList[i].isEmpty()) {
                String[] rangeList = pageList[i].split("-");
                if (rangeList.length > 2) {
                    cancelExtract = true;
                }
                for (int j = 0; j < rangeList.length; j++) {
                    if (!rangeList[j].matches("^[0-9]+$")) {
                        cancelExtract = true;
                    }
                }
                if (!cancelExtract) {
                    if (rangeList.length == 1) {
                        startPage = Integer.parseInt(rangeList[0], 10);
                        if (startPage > extractList.size() || startPage == 0) {
                            cancelExtract = true;
                        } else {
                            extractList.set(startPage, "1");
                        }
                    } else if (rangeList.length == 2) {
                        startPage = Integer.parseInt(rangeList[0], 10);
                        endPage = Integer.parseInt(rangeList[1], 10);

                        for (int k = startPage; k <= endPage; k++) {

                            if (k > extractList.size() || k == 0) {
                                cancelExtract = true;
                            } else {
                                extractList.set(k, "1");
                            }
                        }
                    }
                }
            }
        }
        if (!cancelExtract) {
            cancelExtract = true;
            for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++) {
                if (!(extractList.get(pageNumber).equals("1"))) {
                    cancelExtract = false;
                }
            }
        }
        if (cancelExtract == true) {
            reader.close();
            throw new Exception(myPdfName + " : Invalid Pages to Extract " + pageNumbersToExtract);
        }

        document = new Document(reader.getPageSizeWithRotation(1));
        copy = new PdfCopy(document, new FileOutputStream(tempFilePathName));
        extractCopy = new PdfCopy(document, new FileOutputStream(extractPath));
        document.open();
        for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++) {
            if (!(extractList.get(pageNumber).equals("1"))) {
                copy.addPage(copy.getImportedPage(reader, pageNumber));
            } else {
                extractCopy.addPage(copy.getImportedPage(reader, pageNumber));
            }
        }

    } catch (Exception e) {
        throw (e);
    } finally {
        try {
            if (copy != null) {
                copy.close();
            }
            if (extractCopy != null) {
                extractCopy.close();
            }

            if (document != null) {
                document.close();
            }

            if (reader != null) {
                reader.close();
            }

        } catch (Exception e) {
            throw (e);
        }
    }

    boolean success = f.delete();

    if (success) {
        File f1 = new File(tempFilePathName);
        f1.setLastModified(lastModified);
        success = f1.renameTo(new File(filePathName));
        if (!success) {
            throw new Exception("Error in renaming file from:" + tempFilePathName + "to " + filePathName);
        }

        File f2 = new File(extractPath);
        f2.setLastModified(lastModified);
    } else {
        throw new Exception("Error in deleting file:" + filePathName);
    }
}

From source file:pdfmt.pdf2image.java

License:Open Source License

/** 
 * Convert a PDF document to a TIF file 
 *///from w w w  . jav  a  2  s  .c om
protected static void convert(String pdf, String tif, String destPdf) throws IOException {

    org.icepdf.core.pobjects.Document pdffile = new org.icepdf.core.pobjects.Document();

    try {
        pdffile.setFile(pdf);

    } catch (PDFException ex) {
        //  System.out.println("Error parsing PDF document " + ex); 
    } catch (PDFSecurityException ex) {
        //  System.out.println("Error encryption not supported " + ex); 
    } catch (FileNotFoundException ex) {
        // System.out.println("Error file not found " + ex); 
    } catch (IOException ex) {
        //  System.out.println("Error handling PDF document " + ex); 
    }

    int numPgs = pdffile.getNumberOfPages();

    try {
        // step 1: create new reader
        PdfReader r = new PdfReader(pdf);
        //  System.out.println("File Lenght:"  + r.getFileLength());
        RandomAccessFileOrArray raf = new RandomAccessFileOrArray(pdf);
        // System.out.println("Raf:" + raf);
        Document document = new Document(r.getPageSizeWithRotation(1));
        //           // step 2: create a writer that listens to the document
        PdfCopy writer = new PdfCopy(document, new FileOutputStream(destPdf));
        //           
        //           // step 3: we open the document
        document.open();
        //           // step 4: we add content
        PdfImportedPage page = null;
        //        
        //loop through each page and if the bs is larger than 20 than we know it is not blank.
        //if it is less than 20 than we don't include that blank page.

        float scale = 2.084f;
        float rotation = 0f;

        BufferedImage image[] = new BufferedImage[numPgs];

        for (int i = 0; i < numPgs; i++) {

            byte bContent[] = r.getPageContent(i + 1, raf);
            // System.out.println(bContent.toString());

            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            //write the content to an output stream
            bs.write(bContent);

            //System.out.println("page content length of page " + i+1 + " = "
            //      + bs.size());

            /* 
             * Generate the image: 
             * Notes: 1275x1650 = 8.5 x 11 @ 150dpi ??? 
             */
            image[i] = (BufferedImage) pdffile.getPageImage(i, GraphicsRenderingHints.SCREEN,
                    Page.BOUNDARY_CROPBOX, rotation, scale);
            Iterator writers = ImageIO.getImageWritersByFormatName("TIFF");
            if (writers == null || !writers.hasNext()) {
                throw new RuntimeException("No writers for available.");

            }
            ImageWriter myWriter = (ImageWriter) writers.next();
            myWriter.setOutput(new FileImageOutputStream(new File(tif)));
            myWriter.prepareWriteSequence(null);
            ImageTypeSpecifier imageType = ImageTypeSpecifier.createFromRenderedImage(image[i]);
            IIOMetadata imageMetadata = myWriter.getDefaultImageMetadata(imageType, null);
            imageMetadata = createImageMetadata(imageMetadata);
            myWriter.writeToSequence(new IIOImage(image[i], null, imageMetadata), null);

            myWriter.dispose();
            image[i] = null;
            myWriter = null;

            FileInputStream in = new FileInputStream(tif);
            FileChannel channel = in.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
            channel.read(buffer);
            Image imageBlank;

            imageBlank = load(buffer.array());

            BufferedImage bufferedImage = imageToBufferedImage(imageBlank);
            boolean isBlank;
            isBlank = isBlank(bufferedImage);
            // System.out.println("isblank "+ isBlank);

            if (isBlank == false) {

                page = writer.getImportedPage(r, i + 1);
                writer.addPage(page);

            }
            bs.close();

            System.gc();
        }

        document.close();
        writer.close();
        raf.close();
        r.close();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:pdfmt.RemoveBlankPdf.java

License:Open Source License

/**
 * Convert a PDF document to a TIF file.
 * //from w  ww. j  a  va 2s. com
 * @param pdf
 *            the pdf
 * @param tif
 *            the tif
 * @param destPdf
 *            the dest pdf
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
protected void convert(String pdf, String tif, String destPdf) throws IOException {

    startTime = System.currentTimeMillis();
    logger.info("In the boolean convert(String pdf, String tif, String destPdf)");
    org.icepdf.core.pobjects.Document pdffile = new org.icepdf.core.pobjects.Document();

    try {

        pdffile.setFile(pdf);

    } catch (PDFException ex) {
        // System.out.println("Error parsing PDF document " + ex);
    } catch (PDFSecurityException ex) {
        // System.out.println("Error encryption not supported " + ex);
    } catch (FileNotFoundException ex) {
        // System.out.println("Error file not found " + ex);
    } catch (IOException ex) {
        // System.out.println("Error handling PDF document " + ex);
    }

    int numPgs = pdffile.getNumberOfPages();
    msg.setText(".....::::: Converting pages please wait :::::.....");
    addComponent(contentPane, msg, 10, 110, 200, 18);

    try {
        // step 1: create new reader
        PdfReader r = new PdfReader(pdf);
        // System.out.println("File Lenght:" + r.getFileLength());
        RandomAccessFileOrArray raf = new RandomAccessFileOrArray(pdf);
        // System.out.println("Raf:" + raf);
        Document document = new Document(r.getPageSizeWithRotation(1));
        // // step 2: create a writer that listens to the document
        PdfCopy writer = new PdfCopy(document, new FileOutputStream(destPdf));
        //           
        // // step 3: we open the document
        document.open();
        // // step 4: we add content
        PdfImportedPage page = null;

        float scale = 2.084f;
        float rotation = 0f;

        BufferedImage image[] = new BufferedImage[numPgs];

        // -------- CHANGE
        jprogress.setMaximum(numPgs);
        // -------- CHANGE

        for (int i = 0; i < numPgs; i++) {

            // -------- CHANGE
            jprogress.setValue(i + 1);
            // -------- CHANGE

            byte bContent[] = r.getPageContent(i + 1, raf);
            // System.out.println(bContent.toString());

            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            // write the content to an output stream
            bs.write(bContent);

            // System.out.println("page content length of page " + i+1 +
            // " = "
            // + bs.size());

            /*
             * Generate the image: Notes: 1275x1650 = 8.5 x 11 @ 150dpi ???
             */
            image[i] = (BufferedImage) pdffile.getPageImage(i, GraphicsRenderingHints.SCREEN,
                    Page.BOUNDARY_CROPBOX, rotation, scale);
            Iterator writers = ImageIO.getImageWritersByFormatName("TIFF");
            if (writers == null || !writers.hasNext()) {
                throw new RuntimeException("No writers for available.");

            }
            ImageWriter myWriter = (ImageWriter) writers.next();
            myWriter.setOutput(new FileImageOutputStream(new File(tif)));
            myWriter.prepareWriteSequence(null);
            ImageTypeSpecifier imageType = ImageTypeSpecifier.createFromRenderedImage(image[i]);
            IIOMetadata imageMetadata = myWriter.getDefaultImageMetadata(imageType, null);
            imageMetadata = createImageMetadata(imageMetadata);
            myWriter.writeToSequence(new IIOImage(image[i], null, imageMetadata), null);

            myWriter.dispose();
            image[i] = null;
            myWriter = null;

            FileInputStream in = new FileInputStream(tif);
            FileChannel channel = in.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
            channel.read(buffer);
            Image imageBlank;

            imageBlank = load(buffer.array());

            BufferedImage bufferedImage = imageToBufferedImage(imageBlank);
            boolean isBlank;
            isBlank = isBlank(bufferedImage);
            // System.out.println("isblank "+ isBlank);
            boolean hasContent = false;
            File file = new File(TEMP_DIR + TEMP_EXTR_TEXT);

            try {
                FileWriter fileWriter = new FileWriter(file);

                PageText pageText = pdffile.getPageText(i);
                if (pageText != null && pageText.getPageLines() != null) {
                    fileWriter.write(pageText.toString());
                }

                // close the writer
                fileWriter.close();
                System.out.println(file.length());
                if (file.length() > 20) {
                    hasContent = true;

                }
                file.delete();

                System.out.println(TEMP_TIFF + " deleted");
            } catch (IOException e) {

                e.printStackTrace();
            }

            if (isBlank == false && hasContent == true) {

                page = writer.getImportedPage(r, i + 1);
                writer.addPage(page);

            }
            bs.close();
            in.close();
            File ft = new File(TEMP_DIR + TEMP_TIFF);
            boolean check = ft.delete();
            if (check == true) {
                System.out.println("Deleted");
            } else {
                System.out.println("Stuck");
            }
            System.gc();

        }

        document.close();
        writer.close();
        raf.close();
        r.close();
        stopTime = System.currentTimeMillis();
        logger.info("Exit boolean convert(String pdf, String tif, String destPdf) with time:    "
                + ((stopTime - startTime) / 1000));

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}