Example usage for com.lowagie.text.pdf PdfReader getNumberOfPages

List of usage examples for com.lowagie.text.pdf PdfReader getNumberOfPages

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfReader getNumberOfPages.

Prototype

public int getNumberOfPages() 

Source Link

Document

Gets the number of pages in the document.

Usage

From source file:org.adempiere.webui.apps.ProcessDialog.java

License:Open Source License

public void onPrintInvoices() {
    //   Loop through all items
    List<File> pdfList = new ArrayList<File>();
    for (int i = 0; i < m_ids.length; i++) {
        int C_Invoice_ID = m_ids[i];
        ReportEngine re = ReportEngine.get(Env.getCtx(), ReportEngine.INVOICE, C_Invoice_ID);
        pdfList.add(re.getPDF());/* w  ww.ja  v  a  2 s. co  m*/
    }

    if (pdfList.size() > 1) {
        try {
            File outFile = File.createTempFile("PrintInvoices", ".pdf");
            Document document = null;
            PdfWriter copy = null;
            for (File f : pdfList) {
                PdfReader reader = new PdfReader(f.getAbsolutePath());
                if (document == null) {
                    document = new Document(reader.getPageSizeWithRotation(1));
                    copy = PdfWriter.getInstance(document, new FileOutputStream(outFile));
                    document.open();
                }
                PdfContentByte cb = copy.getDirectContent(); // Holds the PDF
                int pages = reader.getNumberOfPages();
                for (int i = 1; i <= pages; i++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, i);
                    cb.addTemplate(page, 0, 0);
                }
            }
            document.close();

            hideBusyDialog();
            Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(outFile));
            SessionManager.getAppDesktop().showWindow(win, "center");
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    } else if (pdfList.size() > 0) {
        try {
            Window win = new SimplePDFViewer(this.getTitle(), new FileInputStream(pdfList.get(0)));
            SessionManager.getAppDesktop().showWindow(win, "center");
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }
}

From source file:org.alchemy.core.AlcSession.java

License:Open Source License

/** Adds a pdfReadPage to an existing pdf file
 * //from  w  w w  .  ja  v  a2s . c  om
 * @param mainPdf   The main pdf with multiple pages.
 *                  Also used as the destination file.
 * @param tempPdf   The 'new' pdf with one pdfReadPage to be added to the main pdf
 * @return
 */
boolean addPageToPdf(File mainPdf, File tempPdf) {
    try {
        // Destination file created in the temp dir then we will move it
        File dest = new File(DIR_TEMP, "Alchemy.pdf");
        OutputStream output = new FileOutputStream(dest);

        PdfReader reader = new PdfReader(mainPdf.getPath());
        PdfReader newPdf = new PdfReader(tempPdf.getPath());

        // See if the size of the canvas has increased
        // Size of the most recent temp PDF
        com.lowagie.text.Rectangle currentSize = newPdf.getPageSizeWithRotation(1);
        // Size of the session pdf at present
        com.lowagie.text.Rectangle oldSize = reader.getPageSizeWithRotation(1);
        // Sizes to be used from now on
        float pdfWidth = oldSize.getWidth();
        float pdfHeight = oldSize.getHeight();
        if (currentSize.getWidth() > pdfWidth) {
            pdfWidth = currentSize.getWidth();
        }
        if (currentSize.getHeight() > pdfHeight) {
            pdfHeight = currentSize.getHeight();
        }

        // Use the new bigger canvas size if required
        com.lowagie.text.Document document = new com.lowagie.text.Document(
                new com.lowagie.text.Rectangle(pdfWidth, pdfHeight), 0, 0, 0, 0);
        PdfCopy copy = new PdfCopy(document, output);

        // Copy the meta data
        document.addTitle("Alchemy Session");
        document.addAuthor(USER_NAME);
        document.addCreator("Alchemy <http://al.chemy.org>");
        copy.setXmpMetadata(reader.getMetadata());
        document.open();

        // Holds the PDF
        PdfContentByte cb = copy.getDirectContent();

        // Add each page from the main PDF
        for (int i = 0; i < reader.getNumberOfPages();) {
            ++i;
            document.newPage();
            cb.setDefaultColorspace(PdfName.CS, PdfName.DEVICERGB);
            PdfImportedPage page = copy.getImportedPage(reader, i);
            copy.addPage(page);
        }
        // Add the last (new) page
        document.newPage();
        PdfImportedPage lastPage = copy.getImportedPage(newPdf, 1);
        copy.addPage(lastPage);
        output.flush();
        document.close();
        output.close();

        if (dest.exists()) {
            // Save the location of the main pdf
            String mainPdfPath = mainPdf.getPath();
            // Delete the old file
            if (mainPdf.exists()) {
                mainPdf.delete();
            }
            // The final joined up pdf file
            File joinPdf = new File(mainPdfPath);
            // Rename the file
            boolean success = dest.renameTo(joinPdf);
            if (!success) {
                System.err.println("Error moving Pdf");
                return false;
            }

        } else {
            System.err.println("File does not exist?!: " + dest.getAbsolutePath());
            return false;
        }
        return true;

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

From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java

License:Open Source License

/**
 * construct a pdf document from pdf parts.
 * /*www  .j av a2s .  c  om*/
 * @param files
 *            list containing the pdf to assemble
 * @param properties
 *            converter properties
 * @param fout
 *            outputstream to write the new pdf
 * @param base_url
 *            base url of the document
 * @param producer
 *            producer of the pdf
 * 
 * @throws CConvertException
 *             if an error occured while reconstruct.
 */
public static void reconstruct(final List files, final Map properties, final OutputStream fout,
        final String base_url, final String producer, final PageSize[] size, final List hf)
        throws CConvertException {
    OutputStream out = fout;
    OutputStream out2 = fout;
    boolean signed = false;
    OutputStream oldOut = null;
    File tmp = null;
    File tmp2 = null;
    try {
        tmp = File.createTempFile("yahp", "pdf");
        tmp2 = File.createTempFile("yahp", "pdf");
        oldOut = out;
        if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) {
            signed = true;
            out2 = new FileOutputStream(tmp2);
        } // end if
        else {
            out2 = oldOut;
        }
        out = new FileOutputStream(tmp);
        com.lowagie.text.Document document = null;
        PdfCopy writer = null;
        boolean first = true;

        Map mapSizeDoc = new HashMap();

        int totalPage = 0;

        for (int i = 0; i < files.size(); i++) {
            final File fPDF = (File) files.get(i);
            final PdfReader reader = new PdfReader(fPDF.getAbsolutePath());
            reader.consolidateNamedDestinations();

            final int n = reader.getNumberOfPages();

            if (first) {
                first = false;
                // step 1: creation of a document-object
                // set title/creator/author
                document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, out);
                // use pdf version 1.5
                writer.setPdfVersion(PdfWriter.VERSION_1_3);
                // compress the pdf
                writer.setFullCompression();

                // check if encryption is needed
                if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                    final String password = (String) properties
                            .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
                    final int securityType = CDocumentReconstructor.getSecurityFlags(properties);
                    writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType);
                } // end if

                final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE);

                if (title != null) {
                    document.addTitle(title);
                } // end if
                else if (base_url != null) {
                    document.addTitle(base_url);
                } // end else if

                final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR);

                if (creator != null) {
                    document.addCreator(creator);
                } // end if
                else {
                    document.addCreator(IHtmlToPdfTransformer.VERSION);
                } // end else

                final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR);

                if (author != null) {
                    document.addAuthor(author);
                } // end if

                final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER);

                if (sproducer != null) {
                    document.add(new Meta("Producer", sproducer));
                } // end if
                else {
                    document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION
                            + " - http://www.allcolor.org/YaHPConverter/ - " + producer)));
                } // end else

                // step 3: we open the document
                document.open();
            } // end if

            PdfImportedPage page;

            for (int j = 0; j < n;) {
                ++j;
                totalPage++;
                mapSizeDoc.put("" + totalPage, "" + i);
                page = writer.getImportedPage(reader, j);
                writer.addPage(page);
            } // end for
        } // end for

        document.close();
        out.flush();
        out.close();
        {
            final PdfReader reader = new PdfReader(tmp.getAbsolutePath());
            ;
            final int n = reader.getNumberOfPages();
            final PdfStamper stp = new PdfStamper(reader, out2);
            int i = 0;
            BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer();
            while (i < n) {
                i++;
                int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i));
                final int[] dsize = size[indexSize].getSize();
                final int[] dmargin = size[indexSize].getMargin();
                for (final Iterator it = hf.iterator(); it.hasNext();) {
                    final CHeaderFooter chf = (CHeaderFooter) it.next();
                    if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) {
                        continue;
                    } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) {
                        continue;
                    }
                    final String text = chf.getContent().replaceAll("<pagenumber>", "" + i)
                            .replaceAll("<pagecount>", "" + n);
                    // text over the existing page
                    final PdfContentByte over = stp.getOverContent(i);
                    final ByteArrayOutputStream bbout = new ByteArrayOutputStream();
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(),
                                properties, bbout);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(),
                                properties, bbout);
                    }
                    final PdfReader readerHF = new PdfReader(bbout.toByteArray());
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0);
                    }
                    readerHF.close();
                }
            }
            stp.close();
        }
        try {
            out2.flush();
        } catch (Exception ignore) {
        } finally {
            try {
                out2.close();
            } catch (Exception ignore) {
            }
        }
        if (signed) {

            final String keypassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD);
            final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
            final String keyStorepassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD);
            final String privateKeyFile = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE);
            final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON);
            final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION);
            final boolean selfSigned = !"false"
                    .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING));
            PdfReader reader = null;

            if (password != null) {
                reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes());
            } // end if
            else {
                reader = new PdfReader(tmp2.getAbsolutePath());
            } // end else

            final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType())
                    : KeyStore.getInstance("pkcs12");
            ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray());

            final String alias = (String) ks.aliases().nextElement();
            final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray());
            final Certificate chain[] = ks.getCertificateChain(alias);
            final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0');

            if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null,
                        CDocumentReconstructor.getSecurityFlags(properties));
            } // end if

            final PdfSignatureAppearance sap = stp.getSignatureAppearance();

            if (selfSigned) {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            } // end if
            else {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            } // end else

            if (reason != null) {
                sap.setReason(reason);
            } // end if

            if (location != null) {
                sap.setLocation(location);
            } // end if

            stp.close();
            oldOut.flush();
        } // end if
    } // end try
    catch (final Exception e) {
        throw new CConvertException(
                "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e);
    } // end catch
    finally {
        try {
            tmp.delete();
        } // end try
        catch (final Exception ignore) {
        }
        try {
            tmp2.delete();
        } // end try
        catch (final Exception ignore) {
        }
    } // end finally
}

From source file:org.apache.ofbiz.content.compdoc.CompDocServices.java

License:Apache License

public static Map<String, Object> renderCompDocPdf(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();

    Locale locale = (Locale) context.get("locale");
    String rootDir = (String) context.get("rootDir");
    String webSiteId = (String) context.get("webSiteId");
    String https = (String) context.get("https");

    Delegator delegator = dctx.getDelegator();

    String contentId = (String) context.get("contentId");
    String contentRevisionSeqId = (String) context.get("contentRevisionSeqId");
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    try {//from   ww  w  . ja v a 2 s . c o m
        List<EntityCondition> exprList = new LinkedList<EntityCondition>();
        exprList.add(EntityCondition.makeCondition("contentIdTo", EntityOperator.EQUALS, contentId));
        exprList.add(
                EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.EQUALS, "COMPDOC_PART"));
        exprList.add(EntityCondition.makeCondition("rootRevisionContentId", EntityOperator.EQUALS, contentId));
        if (UtilValidate.isNotEmpty(contentRevisionSeqId)) {
            exprList.add(EntityCondition.makeCondition("contentRevisionSeqId",
                    EntityOperator.LESS_THAN_EQUAL_TO, contentRevisionSeqId));
        }

        List<GenericValue> compDocParts = EntityQuery.use(delegator)
                .select("rootRevisionContentId", "itemContentId", "maxRevisionSeqId", "contentId",
                        "dataResourceId", "contentIdTo", "contentAssocTypeId", "fromDate", "sequenceNum")
                .from("ContentAssocRevisionItemView").where(exprList).orderBy("sequenceNum").filterByDate()
                .queryList();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Document document = new Document();
        document.setPageSize(PageSize.LETTER);
        PdfCopy writer = new PdfCopy(document, baos);
        document.open();
        int pgCnt = 0;
        for (GenericValue contentAssocRevisionItemView : compDocParts) {
            String thisDataResourceId = contentAssocRevisionItemView.getString("dataResourceId");
            GenericValue dataResource = EntityQuery.use(delegator).from("DataResource")
                    .where("dataResourceId", thisDataResourceId).queryOne();
            String inputMimeType = null;
            if (dataResource != null) {
                inputMimeType = dataResource.getString("mimeTypeId");
            }
            byte[] inputByteArray = null;
            PdfReader reader = null;
            if (inputMimeType != null && inputMimeType.equals("application/pdf")) {
                ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId,
                        https, webSiteId, locale, rootDir);
                inputByteArray = byteBuffer.array();
                reader = new PdfReader(inputByteArray);
            } else if (inputMimeType != null && inputMimeType.equals("text/html")) {
                ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId,
                        https, webSiteId, locale, rootDir);
                inputByteArray = byteBuffer.array();
                String s = new String(inputByteArray);
                Debug.logInfo("text/html string:" + s, module);
                continue;
            } else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) {
                String surveyResponseId = dataResource.getString("relatedDetailId");
                String surveyId = null;
                String acroFormContentId = null;
                GenericValue surveyResponse = null;
                if (UtilValidate.isNotEmpty(surveyResponseId)) {
                    surveyResponse = EntityQuery.use(delegator).from("SurveyResponse")
                            .where("surveyResponseId", surveyResponseId).queryOne();
                    if (surveyResponse != null) {
                        surveyId = surveyResponse.getString("surveyId");
                    }
                }
                if (UtilValidate.isNotEmpty(surveyId)) {
                    GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId)
                            .queryOne();
                    if (survey != null) {
                        acroFormContentId = survey.getString("acroFormContentId");
                        if (UtilValidate.isNotEmpty(acroFormContentId)) {
                            // TODO: is something supposed to be done here?
                        }
                    }
                }
                if (surveyResponse != null) {
                    if (UtilValidate.isEmpty(acroFormContentId)) {
                        // Create AcroForm PDF
                        Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse",
                                UtilMisc.toMap("surveyResponseId", surveyId));
                        if (ServiceUtil.isError(survey2PdfResults)) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                    "ContentSurveyErrorBuildingPDF", locale), null, null, survey2PdfResults);
                        }

                        ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer");
                        inputByteArray = outByteBuffer.array();
                        reader = new PdfReader(inputByteArray);
                    } else {
                        // Fill in acroForm
                        Map<String, Object> survey2AcroFieldResults = dispatcher.runSync(
                                "setAcroFieldsFromSurveyResponse",
                                UtilMisc.toMap("surveyResponseId", surveyResponseId));
                        if (ServiceUtil.isError(survey2AcroFieldResults)) {
                            return ServiceUtil
                                    .returnError(
                                            UtilProperties.getMessage(resource,
                                                    "ContentSurveyErrorSettingAcroFields", locale),
                                            null, null, survey2AcroFieldResults);
                        }

                        ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer");
                        inputByteArray = outByteBuffer.array();
                        reader = new PdfReader(inputByteArray);
                    }
                }
            } else {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "ContentMimeTypeNotSupported", locale));
            }
            if (reader != null) {
                int n = reader.getNumberOfPages();
                for (int i = 0; i < n; i++) {
                    PdfImportedPage pg = writer.getImportedPage(reader, i + 1);
                    writer.addPage(pg);
                    pgCnt++;
                }
            }
        }
        document.close();
        ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());

        Map<String, Object> results = ServiceUtil.returnSuccess();
        results.put("outByteBuffer", outByteBuffer);
        return results;
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(e.toString());
    } catch (IOException e) {
        Debug.logError(e, "Error in CompDoc operation: ", module);
        return ServiceUtil.returnError(e.toString());
    } catch (Exception e) {
        Debug.logError(e, "Error in CompDoc operation: ", module);
        return ServiceUtil.returnError(e.toString());
    }
}

From source file:org.areasy.common.doclet.utilities.PDFUtility.java

License:Open Source License

/**
    * Inserts a PDF file into the document.
    *//from w w  w . j a  va2s  .c o m
    * @param pdfFile The PDF file object.
    * @throws Exception
    */
public static void insertPdfDocument(File pdfFile) throws Exception {
    PdfWriter writer = Document.getWriter();
    PdfReader reader = new PdfReader(new FileInputStream(pdfFile));

    for (int pageNo = 1; pageNo < reader.getNumberOfPages() + 1; pageNo++) {
        Document.newPage();

        PdfImportedPage page = writer.getImportedPage(reader, pageNo);
        writer.getDirectContent().addTemplate(page, 0.94f, 0, 0, 0.94f, 0, 30.0f);
    }
}

From source file:org.efaps.esjp.common.file.FileUtil_Base.java

License:Apache License

/**
 * @param _files pdfs to be combined into one file
 * @param _fileName name of the file to be generated
 * @param _paginate paginat or not/*from   www. j  av a2  s.co  m*/
 * @return file
 * @throws EFapsException on error
 */
public File combinePdfs(final List<File> _files, final String _fileName, final boolean _paginate)
        throws EFapsException {
    File ret = null;
    if (_files.size() == 1) {
        ret = _files.get(0);
    } else {
        try {
            final List<InputStream> pdfs = new ArrayList<>();
            for (final File file : _files) {
                pdfs.add(new FileInputStream(file));
            }
            ret = getFile(_fileName, "pdf");
            final OutputStream outputStream = new FileOutputStream(ret);
            final Document document = new Document();
            try {
                final List<PdfReader> readers = new ArrayList<>();
                int totalPages = 0;
                final Iterator<InputStream> iteratorPDFs = pdfs.iterator();

                // Create Readers for the pdfs.
                while (iteratorPDFs.hasNext()) {
                    final InputStream pdf = iteratorPDFs.next();
                    final PdfReader pdfReader = new PdfReader(pdf);
                    readers.add(pdfReader);
                    totalPages += pdfReader.getNumberOfPages();
                }
                final PdfSmartCopy copy = new PdfSmartCopy(document, outputStream);
                final Iterator<PdfReader> iteratorPDFReader = readers.iterator();
                document.open();
                while (iteratorPDFReader.hasNext()) {
                    final PdfReader pdfReader = iteratorPDFReader.next();
                    for (int i = 0; i < pdfReader.getNumberOfPages(); i++) {
                        final PdfImportedPage importedPage = copy.getImportedPage(pdfReader, i + 1);
                        copy.addPage(importedPage);

                        if (_paginate) {
                            LOG.debug("Missing page ", totalPages);
                        }
                    }
                }
                outputStream.flush();
                document.close();
                outputStream.close();
                // CHECKSTYLE:OFF
            } catch (final Exception e) {
                // CHECKSTYLE:ON
                e.printStackTrace();
            } finally {
                if (document.isOpen()) {
                    document.close();
                }
                try {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                } catch (final IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        } catch (final FileNotFoundException e) {
            LOG.error("FileNotFoundException", e);
        }
    }
    return ret;
}

From source file:org.efaps.esjp.common.file.FileUtil_Base.java

License:Apache License

/**
 * Resize./*w  ww .  j av a  2 s.  c  o m*/
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _file the file
 * @param _fileName the file name
 * @param _pageSize the page size
 * @return the file
 * @throws EFapsException on error
 */
public File resizePdf(final Parameter _parameter, final File _file, final String _fileName,
        final String _pageSize) throws EFapsException {
    final Document document = new Document();

    final File ret = getFile(_fileName, "pdf");
    try {
        final File destFile = new File(_file.getPath() + ".tmp");
        FileUtils.copyFile(_file, destFile);
        final OutputStream outputStream = new FileOutputStream(ret);
        final PdfReader pdfReader = new PdfReader(new FileInputStream(destFile));

        // Create a writer for the outputstream
        final PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();
        PdfImportedPage page;
        final PdfContentByte cb = writer.getDirectContent();
        int pageOfCurrentReaderPDF = 0;
        // Create a new page in the target for each source page.
        while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
            document.newPage();
            pageOfCurrentReaderPDF++;
            page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
            document.setPageSize(page.getWidth() <= page.getHeight() ? PageSize.getRectangle(_pageSize)
                    : PageSize.getRectangle(_pageSize).rotate());
            final float widthFactor = document.getPageSize().getWidth() / page.getWidth();
            final float heightFactor = document.getPageSize().getHeight() / page.getHeight();
            final float factor = Math.min(widthFactor, heightFactor);
            final float offsetX = (document.getPageSize().getWidth() - page.getWidth() * factor) / 2;
            final float offsetY = (document.getPageSize().getHeight() - page.getHeight() * factor) / 2;
            cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
        }
        pageOfCurrentReaderPDF = 0;
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (final FileNotFoundException e) {
        LOG.error("FileNotFoundException", e);
    } catch (final IOException e) {
        LOG.error("IOException", e);
    } catch (final DocumentException e) {
        LOG.error("DocumentException", e);
    }
    return ret;
}

From source file:org.efaps.esjp.common.file.FileUtil_Base.java

License:Apache License

/**
 * N up./*from ww  w  . j av  a  2  s. c  om*/
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _file the file
 * @param _fileName the file name
 * @return the file
 * @throws EFapsException on error
 */
public File nUpPdf(final Parameter _parameter, final File _file, final String _fileName) throws EFapsException {
    final File ret = getFile(_fileName, "pdf");
    try {
        final int pow = Integer.parseInt(getProperty(_parameter, "NUpPow", "1"));
        final boolean duplicate = "true".equalsIgnoreCase(getProperty(_parameter, "NUpDuplicate", "true"));
        final File destFile = new File(_file.getPath() + ".tmp");
        FileUtils.copyFile(_file, destFile);
        final OutputStream outputStream = new FileOutputStream(ret);
        final PdfReader pdfReader = new PdfReader(new FileInputStream(destFile));

        final Rectangle pageSize = pdfReader.getPageSize(1);

        final Rectangle newSize = pow % 2 == 0 ? new Rectangle(pageSize.getWidth(), pageSize.getHeight())
                : new Rectangle(pageSize.getHeight(), pageSize.getWidth());

        Rectangle unitSize = new Rectangle(pageSize.getWidth(), pageSize.getHeight());

        for (int i = 0; i < pow; i++) {
            unitSize = new Rectangle(unitSize.getHeight() / 2, unitSize.getWidth());
        }

        final int n = (int) Math.pow(2, pow);
        final int r = (int) Math.pow(2, pow / 2);
        final int c = n / r;

        final Document document = new Document(newSize, 0, 0, 0, 0);

        // Create a writer for the outputstream
        final PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();
        PdfImportedPage page;
        final PdfContentByte cb = writer.getDirectContent();
        // Create a new page in the target for each source page.
        Rectangle currentSize;
        float offsetX;
        float offsetY;
        float factor;

        final int total = pdfReader.getNumberOfPages();
        for (int i = 0; i < total;) {
            if (i % n == 0) {
                document.newPage();
            }
            currentSize = pdfReader.getPageSize(++i);

            factor = Math.min(unitSize.getWidth() / currentSize.getWidth(),
                    unitSize.getHeight() / currentSize.getHeight());
            offsetX = unitSize.getWidth() * (i % n % c)
                    + (unitSize.getWidth() - currentSize.getWidth() * factor) / 2f;
            offsetY = newSize.getHeight() - (unitSize.getHeight() * (i % n % c) + 1)
                    + (unitSize.getHeight() - currentSize.getHeight() * factor) / 2f;

            page = writer.getImportedPage(pdfReader, i);

            cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);

            if (duplicate) {
                for (int y = i + 1; y <= pow + 1; y++) {
                    factor = Math.min(unitSize.getWidth() / currentSize.getWidth(),
                            unitSize.getHeight() / currentSize.getHeight());
                    offsetX = unitSize.getWidth() * (y % n % c)
                            + (unitSize.getWidth() - currentSize.getWidth() * factor) / 2f;
                    offsetY = newSize.getHeight() - unitSize.getHeight() * (y % n / c + 1)
                            + (unitSize.getHeight() - currentSize.getHeight() * factor) / 2f;
                    cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
                }
            }
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (final FileNotFoundException e) {
        LOG.error("FileNotFoundException", e);
    } catch (final IOException e) {
        LOG.error("IOException", e);
    } catch (final DocumentException e) {
        LOG.error("DocumentException", e);
    }
    return ret;
}

From source file:org.egov.ptis.actions.reports.SearchNoticesAction.java

License:Open Source License

/**
 * @param streamOfPDFFiles//www.  j a  va2s. com
 * @param outputStream
 * @return
 */
private byte[] concatPDFs(final List<InputStream> streamOfPDFFiles, final ByteArrayOutputStream outputStream) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Entered into concatPDFs method");
    Document document = null;
    try {
        final List<InputStream> pdfs = streamOfPDFFiles;
        final List<PdfReader> readers = new ArrayList<>();
        final Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            final InputStream pdf = iteratorPDFs.next();
            final PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            if (null == document)
                document = new Document(pdfReader.getPageSize(1));
        }
        // Create a writer for the outputstream
        final PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        final PdfContentByte cb = writer.getDirectContent(); // Holds the
                                                             // PDF
                                                             // data

        PdfImportedPage page;
        int pageOfCurrentReaderPDF = 0;
        final Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            final PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();

    } catch (final Exception e) {
        LOGGER.error("Exception in concat PDFs : ", e);

    } finally {
        if (document.isOpen())
            document.close();
        try {
            if (outputStream != null)
                outputStream.close();
        } catch (final IOException ioe) {
            LOGGER.error("Exception in concat PDFs : ", ioe);
        }
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Exit from concatPDFs method");
    return outputStream.toByteArray();
}

From source file:org.egov.wtms.web.controller.reports.GenerateBillForConsumerCodeController.java

License:Open Source License

private byte[] concatPDFs(final List<InputStream> streamOfPDFFiles, final ByteArrayOutputStream outputStream) {

    Document document = null;/*from  ww w .  j  av a 2s .  c o m*/
    try {
        final List<InputStream> pdfs = streamOfPDFFiles;
        final List<PdfReader> readers = new ArrayList<>();
        final Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            final InputStream pdf = iteratorPDFs.next();
            final PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            if (null == document)
                document = new Document(pdfReader.getPageSize(1));
        }
        // Create a writer for the outputstream
        final PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        final PdfContentByte cb = writer.getDirectContent(); // Holds the
        // PDF
        // data

        PdfImportedPage page;
        int pageOfCurrentReaderPDF = 0;
        final Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            final PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();

    } catch (final Exception e) {

        LOGGER.error("Exception in concat PDFs : ", e);
    } finally {
        if (document.isOpen())
            document.close();
        try {
            if (outputStream != null)
                outputStream.close();
        } catch (final IOException ioe) {
            LOGGER.error("Exception in concat PDFs : ", ioe);
        }
    }
    return outputStream.toByteArray();
}