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.lucee.extension.pdf.util.PDFUtil.java

License:Open Source License

public static void encrypt(PDFStruct doc, OutputStream os, String newUserPassword, String newOwnerPassword,
        int permissions, int encryption) throws PageException, DocumentException, IOException {
    byte[] user = newUserPassword == null ? null : newUserPassword.getBytes();
    byte[] owner = newOwnerPassword == null ? null : newOwnerPassword.getBytes();

    PdfReader pr = doc.getPdfReader();
    List bookmarks = SimpleBookmark.getBookmark(pr);
    int n = pr.getNumberOfPages();

    Document document = new Document(pr.getPageSizeWithRotation(1));
    PdfCopy writer = new PdfCopy(document, os);
    if (encryption != ENCRYPT_NONE)
        writer.setEncryption(user, owner, permissions, encryption);
    document.open();//from  ww w. j a  va  2s .c om

    PdfImportedPage page;
    for (int i = 1; i <= n; i++) {
        page = writer.getImportedPage(pr, i);
        writer.addPage(page);
    }
    PRAcroForm form = pr.getAcroForm();
    if (form != null)
        writer.copyAcroForm(pr);
    if (bookmarks != null)
        writer.setOutlines(bookmarks);
    document.close();
}

From source file:org.meveo.admin.action.billing.BillingAccountBean.java

License:Open Source License

public void generatePDF(long invoiceId) {
    Invoice invoice = invoiceService.findById(invoiceId);
    byte[] invoicePdf = invoice.getPdf();
    FacesContext context = FacesContext.getCurrentInstance();
    String invoiceFilename = null;
    BillingRun billingRun = invoice.getBillingRun();
    invoiceFilename = invoice.getInvoiceNumber() + ".pdf";
    if (billingRun != null && billingRun.getStatus() != BillingRunStatusEnum.VALIDATED) {
        invoiceFilename = "unvalidated-invoice.pdf";
    }//from w w  w . ja v  a  2  s  .c  o  m

    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    response.setContentType("application/pdf"); // fill in
    response.setHeader("Content-disposition", "attachment; filename=" + invoiceFilename);

    try {
        OutputStream os = response.getOutputStream();
        Document document = new Document(PageSize.A4);
        if (billingRun != null && invoice.getBillingRun().getStatus() != BillingRunStatusEnum.VALIDATED) {
            // Add watemark image
            PdfReader reader = new PdfReader(invoicePdf);
            int n = reader.getNumberOfPages();
            PdfStamper stamp = new PdfStamper(reader, os);
            PdfContentByte over = null;
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.5f);
            int i = 1;
            while (i <= n) {
                over = stamp.getOverContent(i);
                over.setGState(gs);
                over.beginText();
                System.out.println("top=" + document.top() + ",bottom=" + document.bottom());
                over.setTextMatrix(document.top(), document.bottom());
                over.setFontAndSize(bf, 150);
                over.setColorFill(Color.GRAY);
                over.showTextAligned(Element.ALIGN_CENTER, "TEST", document.getPageSize().getWidth() / 2,
                        document.getPageSize().getHeight() / 2, 45);
                over.endText();
                i++;
            }

            stamp.close();
        } else {
            os.write(invoicePdf); // fill in PDF with bytes
        }

        // contentType
        os.flush();
        os.close();
        context.responseComplete();
    } catch (IOException e) {
        log.error("failed to generate PDF ", e);
    } catch (DocumentException e) {
        log.error("error in generation PDF ", e);
    }
}

From source file:org.mnsoft.pdfocr.CreatorSetter.java

License:Open Source License

/**
 * @param args//from w  w w.ja  va  2s. co m
 * @throws DocumentException
 * @throws IOException
 * @throws IOException
 * @throws BadPdfFormatException
 */
@SuppressWarnings("rawtypes")
public static void main(String[] args) throws DocumentException, IOException {
    /*
     * Verify arguments
     */
    if ((args == null) || (args.length < 2)) {
        System.err.println("Usage: first parameter: Creator to set, following parameters: Files to work on.");
        System.exit(1);
    }

    final String creator = args[0];

    for (int i = 1; i < args.length; i++) {
        final File f = new File(args[i]);

        if ((f == null) || !f.exists() || !f.isFile() || !f.getName().endsWith(".pdf")) {
            System.err.println("! ERROR: Could not read " + args[i] + " or this is not a .pdf");

            continue;
        }

        final String p = f.getAbsolutePath();

        /*
         * Open the reader
         */
        PdfReader reader;

        try {
            reader = new PdfReader(p);
        } catch (Exception e) {
            System.err.println("! ERROR: " + e.getMessage() + " File: " + p);

            continue;
        }

        /*
         * Get the document information
         */
        Map info = reader.getInfo();

        /*
         * Get the document creator. If the document
         * has already been worked on, continue with
         * the next document.
         */
        String doc_creator = (String) info.get("Creator");

        if (creator.equals(doc_creator)) {
            System.out.println("+ INFO: File " + p + " had already the right creator.");

            continue;
        }

        /*
         * Get the document time stamp so that we can set it later.
         */
        final Date doc_timestamp = new Date(f.lastModified());

        /*
         * Get the number of pages in the original file
         */
        int nOri = reader.getNumberOfPages();

        System.out.print("+ INFO: Working on: " + p + " (" + nOri + " pages) ... ");

        /*
         * Get the remaining meta data
         */
        String doc_title = ((String) info.get("Title") == null) ? "" : (String) info.get("Title");
        String doc_subject = ((String) info.get("Subject") == null) ? "" : (String) info.get("Subject");
        String doc_keywords = ((String) info.get("Keywords") == null) ? "" : (String) info.get("Keywords");
        String doc_author = ((String) info.get("Author") == null) ? "" : (String) info.get("Author");

        reader.close();

        /*
         * Set the creator to our marker
         */
        doc_creator = creator;

        /*
         * Merge the new document with the meta
         * data from the original document
         */
        try {
            reader = new PdfReader(p);
        } catch (Exception e) {
            System.err.println("! ERROR: " + e.getMessage() + " File: " + p);

            continue;
        }

        /*
         * Get the document information
         */
        info = reader.getInfo();

        /*
         * Get the document creator. If the document
         * has already been worked on, we assume we
         * have had a successful output from the OCR
         * engine
         */
        String doc_creator_copy = (String) info.get("Creator");

        if (creator.equals(doc_creator_copy)) {
            System.out.println();

            continue;
        }

        /*
         * Step 1: creation of a document object
         */
        final Document document = new Document(reader.getPageSizeWithRotation(1));

        /*
         * Step 2: we create a writer that listens to the document
         */
        PdfCopy writer = new PdfCopy(document, new FileOutputStream(p + ".tmp"));

        /*
         * Step 3: we add the meta data
         */
        document.addTitle(doc_title);
        document.addSubject(doc_subject);
        document.addKeywords(doc_keywords);
        document.addCreator(creator);
        document.addAuthor(doc_author);

        /*
         * Step 4: we open the document
         */
        document.open();

        PdfImportedPage page;

        int j = 0;

        /*
         * Step 5: we add content
         */
        while (j < nOri) {
            j++;
            page = writer.getImportedPage(reader, j);
            writer.addPage(page);

            System.out.print("[" + j + "] ");
        }

        PRAcroForm form = reader.getAcroForm();
        if (form != null) {
            writer.copyAcroForm(reader);
        }

        System.out.println();

        /*
         * Step 6: we close the document
         */
        document.close();
        reader.close();

        /*
         * Set the file access time and
         * rename the file.
         */
        File file = new File(p + ".tmp");

        if (file.exists()) {
            deleteFile(p);
            file.setLastModified(doc_timestamp.getTime());
            file.renameTo(new File(p));
        }
    }
}

From source file:org.mnsoft.pdfocr.PDFTrans.java

License:Open Source License

/**
 * @param args the command line arguments
 *//*  ww w .j av  a 2 s.c  o m*/
@SuppressWarnings({ "deprecation", "rawtypes" })
public static void main(String[] args) {
    if (args.length < 2) {
        usage();
    }

    String input_file = null, output_file = null, doc_title = null, doc_subject = null, doc_keywords = null,
            doc_creator = null, doc_author = null, user_passwd = null, owner_passwd = null;

    boolean encrypt = false;
    boolean encryption_bits = PdfWriter.STRENGTH128BITS;
    int permissions = 0;
    boolean print_info = false;
    boolean print_keywords = false;

    /*
     *  parse options
     */
    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("--title")) {
            doc_title = args[++i];
        } else if (args[i].equals("--subject")) {
            doc_subject = args[++i];
        } else if (args[i].equals("--keywords")) {
            doc_keywords = args[++i];
        } else if (args[i].equals("--creator")) {
            doc_creator = args[++i];
        } else if (args[i].equals("--author")) {
            doc_author = args[++i];
        } else if (args[i].equals("--print-info")) {
            print_info = true;
        } else if (args[i].equals("--print-keywords")) {
            print_keywords = true;
        } else if (args[i].equals("--user-password")) {
            encrypt = true;
            user_passwd = args[++i];
        } else if (args[i].equals("--master-password")) {
            encrypt = true;
            owner_passwd = args[++i];
        } else if (args[i].equals("--encryption-bits")) {
            i++;
            encrypt = true;

            if (args[i].equals("128")) {
                encryption_bits = PdfWriter.STRENGTH128BITS;
            } else if (args[i].equals("40")) {
                encryption_bits = PdfWriter.STRENGTH40BITS;
            } else {
                usage();
            }

            continue;
        } else if (args[i].equals("--permissions")) {
            i++;

            StringTokenizer st = new StringTokenizer(args[i], ",");
            while (st.hasMoreTokens()) {
                String s = st.nextToken();
                if (s.equals("print")) {
                    permissions |= PdfWriter.AllowPrinting;
                } else if (s.equals("degraded-print")) {
                    permissions |= PdfWriter.AllowDegradedPrinting;
                } else if (s.equals("copy")) {
                    permissions |= PdfWriter.AllowCopy;
                } else if (s.equals("modify-contents")) {
                    permissions |= PdfWriter.AllowModifyContents;
                } else if (s.equals("modify-annotations")) {
                    permissions |= PdfWriter.AllowModifyAnnotations;
                } else if (s.equals("assembly")) {
                    permissions |= PdfWriter.AllowAssembly;
                } else if (s.equals("fill-in")) {
                    permissions |= PdfWriter.AllowFillIn;
                } else if (s.equals("screen-readers")) {
                    permissions |= PdfWriter.AllowScreenReaders;
                } else {
                    warning("Unknown permission '" + s + "' ignored");
                }
            }

            continue;
        } else if (args[i].startsWith("--")) {
            error("Unknown option '" + args[i] + "'");
        } else if (input_file == null) {
            input_file = args[i];
        } else if (output_file == null) {
            output_file = args[i];
        } else {
            usage();
        }
    }

    if (!print_keywords) {
        if ((input_file == null) || (output_file == null)) {
            usage();
        }

        if (input_file.equals(output_file)) {
            error("Input and output files must be different");
        }
    }

    try {
        /*
         *  we create a reader for the input file
         */
        if (!print_keywords) {
            System.out.println("Reading " + input_file + "...");
        }

        PdfReader reader = new PdfReader(input_file);

        /*
         *  we retrieve the total number of pages
         */
        final int n = reader.getNumberOfPages();
        if (!print_keywords) {
            System.out.println("There are " + n + " pages in the original file.");
        }

        /*
         *  get the document information
         */
        final Map info = reader.getInfo();

        /*
         *  print the document information if asked to do so
         */
        if (print_info) {
            System.out.println("Document information:");

            final Iterator it = info.entrySet().iterator();
            while (it.hasNext()) {
                final Map.Entry entry = (Map.Entry) it.next();
                System.out.println(entry.getKey() + " = \"" + entry.getValue() + "\"");
            }
        }

        if (print_keywords) {
            String keywords = "" + info.get("Keywords");
            if ((null == keywords) || "null".equals(keywords)) {
                keywords = "";
            }

            System.out.println(keywords);
            System.exit(0);
        }

        /*
         *  if any meta data field is unspecified,
         *  copy the value from the input document
         */
        if (doc_title == null) {
            doc_title = (String) info.get("Title");
        }

        if (doc_subject == null) {
            doc_subject = (String) info.get("Subject");
        }

        if (doc_keywords == null) {
            doc_keywords = (String) info.get("Keywords");
        }

        if (doc_creator == null) {
            doc_creator = (String) info.get("Creator");
        }

        if (doc_author == null) {
            doc_author = (String) info.get("Author");
        }

        // null metadata field are simply set to the empty string
        if (doc_title == null) {
            doc_title = "";
        }

        if (doc_subject == null) {
            doc_subject = "";
        }

        if (doc_keywords == null) {
            doc_keywords = "";
        }

        if (doc_creator == null) {
            doc_creator = "";
        }

        if (doc_author == null) {
            doc_author = "";
        }

        /*
         *  step 1: creation of a document-object
         */
        final Document document = new Document(reader.getPageSizeWithRotation(1));

        /*
         *  step 2: we create a writer that listens to the document
         */
        final PdfCopy writer = new PdfCopy(document, new FileOutputStream(output_file));

        /*
         *  step 3.1: we add the meta data
         */
        document.addTitle(doc_title);
        document.addSubject(doc_subject);
        document.addKeywords(doc_keywords);
        document.addCreator(doc_creator);
        document.addAuthor(doc_author);

        /*
         *  step 3.2: we set up the protection and encryption parameters
         */
        if (encrypt) {
            writer.setEncryption(encryption_bits, user_passwd, owner_passwd, permissions);
        }

        /*
         *  step 4: we open the document
         */
        System.out.print("Writing " + output_file + "... ");
        document.open();

        PdfImportedPage page;

        int i = 0;

        // step 5: we add content
        while (i < n) {
            i++;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);

            System.out.print("[" + i + "] ");
        }

        final PRAcroForm form = reader.getAcroForm();
        if (form != null) {
            writer.copyAcroForm(reader);
        }

        System.out.println();

        // step 6: we close the document
        document.close();
    } catch (Exception e) {
        error(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:org.mnsoft.pdfocr.Wrapper.java

License:Open Source License

/**
 * Run the Wrapper./*from w w  w  .ja  v a2  s  . c o  m*/
 *
 * @throws IOException
 * @throws InterruptedException
 * @throws DocumentException
 */
@SuppressWarnings("rawtypes")
public void run() throws IOException, InterruptedException, DocumentException {
    RecursiveFileListIterator it = new RecursiveFileListIterator(new File(wd), new FileFilter(".pdf"));

    while (it.hasNext()) {
        final File originalFile = it.next();
        final String originalFilePath = originalFile.getAbsolutePath();

        /*
         * Open the reader on the original File
         */
        PdfReader readerOnOriginalFile;

        try {
            readerOnOriginalFile = new PdfReader(originalFilePath);
        } catch (Exception e) {
            log.error("! ERROR: " + e.getMessage() + " File: " + originalFilePath);

            continue;
        }

        /*
         * Get the document information
         */
        Map info = readerOnOriginalFile.getInfo();

        /*
         * Get the document creator. If the document
         * has already been worked on, continue with
         * the next document.
         */
        String doc_creator = (String) info.get("Creator");

        if (this.OCR_CREATOR.equals(doc_creator)) {
            log.debug(
                    "+ INFO: File " + originalFilePath + " had already been run trough OCR engine. Skipping.");

            continue;
        }

        /*
         * Get the document time stamp so that we can set it later.
         */
        final Date doc_timestamp = new Date(originalFile.lastModified());

        /*
         * Get the number of pages in the original file
         */
        int nOri = readerOnOriginalFile.getNumberOfPages();

        log.debug("+ Working on: " + originalFilePath + " (" + nOri + " pages).");

        final StringBuffer sb = new StringBuffer();

        sb.append(originalFilePath + " ... ");

        /*
         * Get the remaining meta data
         */
        String doc_title = ((String) info.get("Title") == null) ? "" : (String) info.get("Title");
        String doc_subject = ((String) info.get("Subject") == null) ? "" : (String) info.get("Subject");
        String doc_keywords = ((String) info.get("Keywords") == null) ? "" : (String) info.get("Keywords");
        String doc_author = ((String) info.get("Author") == null) ? "" : (String) info.get("Author");

        readerOnOriginalFile.close();

        /*
         * Set the creator to our marker
         */
        doc_creator = this.OCR_CREATOR;

        /*
         * Run the OCR Engine
         */
        File outputFileFromOCR = null;
        try {
            outputFileFromOCR = ocr(originalFile);
        } catch (Exception e) {
            log.error("! ERROR: " + e.getMessage());

            continue;
        }

        /*
         * Check for the result of the OCR Engine
         */
        if ((outputFileFromOCR == null) || !outputFileFromOCR.exists()) {
            continue;
        }

        log.debug("+ " + outputFileFromOCR.getAbsolutePath() + " has come out of the OCR engine.");

        /*
         * Create final output
         */

        /*
         * Create a temporary file and copy the source
         * file to it, to avoid UTF-8 encoding problems
         * on the filename confusing the OCR engine
         */
        final File temp = File.createTempFile("ocr", ".pdf", new File(this.TMP_DIR));
        temp.deleteOnExit();

        mergePDFs(originalFile, outputFileFromOCR, temp, doc_title, doc_subject, doc_keywords, doc_author,
                doc_creator);

        FileUtils.deleteQuietly(originalFile);

        FileUtils.moveFile(temp, new File(originalFilePath));

        /*
         * Set the file access time
         */
        if ("true".equals(getAttribute("KEEPTS"))) {
            if (originalFile.exists()) {
                originalFile.setLastModified(doc_timestamp.getTime() + 1000);
            }
        }

        /*
         * Finally, remove the temporary document
         */
        FileUtils.deleteQuietly(temp);
        FileUtils.deleteQuietly(outputFileFromOCR);
    }
}

From source file:org.mnsoft.pdfocr.Wrapper.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
private void mergePDFs(File foreground, File background, File newFile, String title, String subject,
        String keywords, String author, String creator) {
    log.debug("Merge " + foreground + " (FG) and " + background + " (BG) to " + newFile);

    final double threshold = ((Integer) StringUtility.StringToInteger(getAttribute("THRESHOLD"), 2))
            .doubleValue();/* w  w w  . ja v a 2s .c  o  m*/

    try {
        /*
         * Foreground: Original Image.
         * Background: OCR'd Text
         */
        final PdfReader fg = new PdfReader(foreground.getAbsolutePath());
        final PdfReader bg = new PdfReader(background.getAbsolutePath());

        /*
         * Count pages for foreground and background
         */
        final int fg_num_pages = fg.getNumberOfPages();
        final int bg_num_pages = bg.getNumberOfPages();

        if (fg_num_pages != bg_num_pages) {
            log.error(
                    "! Foreground and background have different number of pages. This should really not happen.");
        }

        /*
         *  The output document
         */
        final PdfStamper fg_writer = new PdfStamper(fg, new FileOutputStream(newFile));

        /*
         * Create a PdfTemplate from the first page of mark
         * (PdfImportedPage is derived from PdfTemplate)
         */
        PdfImportedPage bg_page = null;
        for (int i = 0; i < fg_num_pages;) {
            ++i;
            System.out.print(" [" + i + "]");

            final byte[] fg_page_content = fg.getPageContent(i);
            final byte[] bg_page_content = bg.getPageContent(i);

            final int bg_size = bg_page_content.length;
            final int fg_size = fg_page_content.length;

            /*
             * If we're not explicitly merging, we're merging
             * the document with itself only anyway.
             */
            if (!"true".equals(getAttribute("mergefiles"))) {
                continue;
            }

            /*
             * Modification 20130904
             *
             * We want to scan only what's not been generated by a number of
             * generators. So, until now, the generator of whom we wanted to
             * ignore files was ocr, i.e. the one we set ourselves. Now, we
             * have seen that when we run an OCR on a "pdf+text" file, as we
             * collate in post the file with its image, we get an overlapping
             * text which is not pixel correct, i.e. which makes the PDF appear
             * not nicely.
             *
             * If the background image is not at least threshold times as large as
             * the foreground image, we assume we've been working on a
             * page that was plain text already, and don't add the image
             * to the background.
             */
            if ((bg_size / fg_size) <= threshold) {
                log.debug("! Not adding background for page " + i + " since background size (" + bg_size
                        + ") not different enough from foreground size (" + fg_size + ").");

                continue;
            }

            bg_page = fg_writer.getImportedPage(bg, i);

            final PdfContentByte contentByte = fg_writer.getUnderContent(i);

            contentByte.addTemplate(bg_page, 0, 0);
        }

        HashMap map = fg_writer.getMoreInfo();
        if (map == null) {
            map = new HashMap();
        }

        if (title != null) {
            map.put("Title", title);
        }

        if (subject != null) {
            map.put("Subject", subject);
        }

        if (keywords != null) {
            map.put("Keywords", keywords);
        }

        if (author != null) {
            map.put("Author", author);
        }

        if (creator != null) {
            map.put("Creator", creator);
        }

        fg_writer.setMoreInfo(map);

        fg_writer.close();

        System.out.println("");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.nabucco.framework.template.impl.service.pdf.util.MergePdfUtil.java

License:Open Source License

public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) {

    Document document = new Document();
    try {//from  ww w . ja  v  a 2  s  . c om
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the outputstream
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

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

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

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

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen())
            document.close();
        try {
            if (outputStream != null)
                outputStream.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:org.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");
    String oooHost = (String) context.get("oooHost");
    String oooPort = (String) context.get("oooPort");
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    try {//from   w ww  .ja v  a 2  s . c o m
        List<EntityCondition> exprList = FastList.newInstance();
        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);
        //Rectangle rect = document.getPageSize();
        //PdfWriter writer = PdfWriter.getInstance(document, baos);
        PdfCopy writer = new PdfCopy(document, baos);
        document.open();
        int pgCnt = 0;
        for (GenericValue contentAssocRevisionItemView : compDocParts) {
            //String thisContentId = contentAssocRevisionItemView.getString("contentId");
            //String thisContentRevisionSeqId = contentAssocRevisionItemView.getString("maxRevisionSeqId");
            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 {
                ByteBuffer inByteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator,
                        thisDataResourceId, https, webSiteId, locale, rootDir);

                Map<String, Object> convertInMap = UtilMisc.<String, Object>toMap("userLogin", userLogin,
                        "inByteBuffer", inByteBuffer, "inputMimeType", inputMimeType, "outputMimeType",
                        "application/pdf");
                if (UtilValidate.isNotEmpty(oooHost))
                    convertInMap.put("oooHost", oooHost);
                if (UtilValidate.isNotEmpty(oooPort))
                    convertInMap.put("oooPort", oooPort);

                Map<String, Object> convertResult = dispatcher.runSync("convertDocumentByteBuffer",
                        convertInMap);

                if (ServiceUtil.isError(convertResult)) {
                    return ServiceUtil.returnError(
                            UtilProperties.getMessage(resource, "ContentConvertingDocumentByteBuffer", locale),
                            null, null, convertResult);
                }

                ByteBuffer outByteBuffer = (ByteBuffer) convertResult.get("outByteBuffer");
                inputByteArray = outByteBuffer.array();
                reader = new PdfReader(inputByteArray);
            }
            if (reader != null) {
                int n = reader.getNumberOfPages();
                for (int i = 0; i < n; i++) {
                    PdfImportedPage pg = writer.getImportedPage(reader, i + 1);
                    //cb.addTemplate(pg, left, height * pgCnt);
                    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.openbravo.erpCommon.utility.reporting.printing.PrintController.java

License:Open Source License

private void concatReport(Report[] reports, HttpServletResponse response) {
    try {/*from   ww  w.  j  a  v  a2 s. co m*/
        int pageOffset = 0;
        // ArrayList master = new ArrayList();
        int f = 0;
        String filename = "";
        Report outFile = null;
        if (reports.length == 1)
            filename = reports[0].getFilename();
        Document document = null;
        PdfCopy writer = null;
        while (f < reports.length) {
            if (filename == null || filename.equals("")) {
                outFile = reports[f];
                if (multiReports) {
                    filename = outFile.getTemplateInfo().getReportFilename();
                    filename = filename.replaceAll("@our_ref@", "");
                    filename = filename.replaceAll("@cus_ref@", "");
                    filename = filename.replaceAll(" ", "_");
                    filename = filename.replaceAll("-", "");
                    filename = filename + ".pdf";
                } else {
                    filename = outFile.getFilename();
                }
            }
            response.setHeader("Content-disposition", "attachment" + "; filename=" + filename);
            // we create a reader for a certain document
            PdfReader reader = new PdfReader(reports[f].getTargetLocation());
            reader.consolidateNamedDestinations();
            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
            pageOffset += n;

            if (f == 0) {
                // step 1: creation of a document-object
                document = new Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, response.getOutputStream());
                // step 3: we open the document
                document.open();
            }
            // step 4: we add content
            PdfImportedPage page;
            for (int i = 0; i < n;) {
                ++i;
                page = writer.getImportedPage(reader, i);
                writer.addPage(page);
            }
            if (reports[f].isDeleteable()) {
                File file = new File(reports[f].getTargetLocation());
                if (file.exists() && !file.isDirectory()) {
                    file.delete();
                }
            }
            f++;
        }
        document.close();
    } catch (Exception e) {
        log4j.error(e);
    }
}

From source file:org.openconcerto.erp.core.finance.accounting.report.PdfGenerator.java

License:Open Source License

private void init() throws FileNotFoundException {

    // we create a reader for a certain document
    PdfReader reader = null;
    PdfWriter writer = null;/*from   w w  w .j  a  va 2s. c  o  m*/
    try {
        reader = new PdfReader(getStreamStatic(this.fileNameIn));

        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // we retrieve the size of the first page
        Rectangle psize = reader.getPageSize(1);

        psize.setRight(psize.getRight() - this.templateOffsetX);
        psize.setTop(psize.getTop() - this.templateOffsetY);

        this.width = (int) psize.getWidth();
        float height = psize.getHeight();

        // step 1: creation of a document-object
        int MARGIN = 32;
        this.document = new Document(psize, MARGIN, MARGIN, MARGIN, MARGIN);
        // step 2: we create a writer that listens to the document
        if (!this.directoryOut.exists()) {
            this.directoryOut.mkdirs();
        }
        System.err.println("Directory out " + this.directoryOut.getAbsolutePath());
        File f = new File(this.directoryOut, this.fileNameOut);
        if (f.exists()) {
            f.renameTo(new File(this.directoryOut, "Old" + this.fileNameOut));
            f = new File(this.directoryOut, this.fileNameOut);
        }

        System.err.println("Creation du fichier " + f.getAbsolutePath());

        writer = PdfWriter.getInstance(this.document, new FileOutputStream(f));

        this.document.open();
        // step 4: we add content
        this.cb = writer.getDirectContent();

        System.out.println("There are " + n + " pages in the document.");

        this.document.newPage();

        PdfImportedPage page1 = writer.getImportedPage(reader, 1);

        this.cb.addTemplate(page1, -this.templateOffsetX, -this.templateOffsetY);

        this.bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.EMBEDDED);
        this.bfb = BaseFont.createFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, BaseFont.EMBEDDED);

    } catch (FileNotFoundException fE) {
        throw fE;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}