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.kuali.kfs.sys.PdfFormFillerUtil.java

License:Open Source License

/**
 * This Method creates a custom watermark on the File.
 *
 * @param templateStream/* w w  w.ja v a  2s . co m*/
 * @param watermarkText
 * @return
 * @throws IOException
 * @throws DocumentException
 */
public static byte[] createWatermarkOnFile(byte[] templateStream, String watermarkText)
        throws IOException, DocumentException {
    // Create a PDF reader for the template
    PdfReader pdfReader = new PdfReader(templateStream);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    // Create a PDF writer
    PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
    int n = pdfReader.getNumberOfPages();
    int i = 1;
    PdfContentByte over;
    BaseFont bf;
    try {
        bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);
        PdfGState gstate = new PdfGState();
        gstate.setFillOpacity(0.5f);
        while (i <= n) {
            // Watermark under the existing page
            Rectangle pageSize = pdfReader.getPageSizeWithRotation(i);
            over = pdfStamper.getOverContent(i);
            over.beginText();
            over.setFontAndSize(bf, 200);
            over.setGState(gstate);
            over.setColorFill(Color.LIGHT_GRAY);
            over.showTextAligned(Element.ALIGN_CENTER, watermarkText, (pageSize.width() / 2),
                    (pageSize.height() / 2), 45);
            over.endText();
            i++;
        }
        pdfStamper.close();
    } catch (DocumentException ex) {
        throw new IOException("iText error creating watermark on PDF", ex);
    } catch (IOException ex) {
        throw new IOException("IO error creating watermark on PDF", ex);
    }
    return outputStream.toByteArray();
}

From source file:org.kuali.kra.printing.service.impl.PrintingServiceImpl.java

License:Educational Community License

/**
 * @param pdfBytesList//  ww w  . j  a v a2 s .co m
 *            List containing the PDF data bytes
 * @param bookmarksList
 *            List of bookmarks corresponding to the PDF bytes.
 * @return
 * @throws PrintingException
 */

protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList,
        boolean headerFooterRequired) throws PrintingException {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    int totalNumOfPages = 0;
    PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()];
    int pdfReaderCount = 0;
    for (byte[] fileBytes : pdfBytesList) {
        LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount));
        PdfReader reader = null;
        try {
            reader = new PdfReader(fileBytes);
            pdfReaderArr[pdfReaderCount] = reader;
            pdfReaderCount = pdfReaderCount + 1;
            totalNumOfPages += reader.getNumberOfPages();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    HeaderFooter footer = null;
    if (headerFooterRequired) {
        Calendar calendar = dateTimeService.getCurrentCalendar();
        String dateString = formateCalendar(calendar);
        StringBuilder footerPhStr = new StringBuilder();
        footerPhStr.append(" of ");
        footerPhStr.append(totalNumOfPages);
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60));
        footerPhStr.append(dateString);
        Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK);
        Phrase beforePhrase = new Phrase("Page ", font);
        Phrase afterPhrase = new Phrase(footerPhStr.toString(), font);
        footer = new HeaderFooter(beforePhrase, afterPhrase);
        footer.setAlignment(Element.ALIGN_BASELINE);
        footer.setBorderWidth(0f);
    }
    for (int count = 0; count < pdfReaderArr.length; count++) {
        PdfReader reader = pdfReaderArr[count];
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1))
                    : new com.lowagie.text.Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new PrintingException(e.getMessage(), e);
            }
            if (footer != null) {
                document.setFooter(footer);
            }
            // writer.setPageEvent(new Watermark());  //  add watermark object here
            document.open();
        }

        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            if (footer != null) {
                document.setFooter(footer);
            }
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }
    if (document != null) {
        try {
            document.close();
            return mergedPdfReport.toByteArray();
        } catch (Exception e) {
            LOG.error("Exception occured because the generated PDF document has no pages", e);
        }
    }
    return null;
}

From source file:org.kuali.kra.printing.service.impl.WatermarkServiceImpl.java

License:Educational Community License

/**
 * //from  w  ww. j  a  v  a 2s .c o  m
 * This method for Decorating the PDF with watermark.
 * 
 * @param pdfStamper - wrapper for pdf content byte and assists in decorating PDF LOg the exception if cannot open/read the file
 *        for decoration
 */
private void decorateWatermark(PdfStamper watermarkPdfStamper, WatermarkBean watermarkBean) {
    PdfReader pdfReader = watermarkPdfStamper.getReader();
    int pageCount = pdfReader.getNumberOfPages();
    int pdfPageNumber = 0;

    PdfContentByte pdfContents;
    Rectangle rectangle;
    while (pdfPageNumber < pageCount) {
        pdfPageNumber++;
        // pdfContents = watermarkPdfStamper.getOverContent(pdfPageNumber);
        rectangle = pdfReader.getPageSizeWithRotation(pdfPageNumber);
        pdfContents = watermarkPdfStamper.getUnderContent(pdfPageNumber);
        if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_IMAGE)) {
            decoratePdfWatermarkImage(pdfContents, (int) rectangle.getHeight(), (int) rectangle.getHeight(),
                    watermarkBean);
        }
        if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) {
            decoratePdfWatermarkText(pdfContents, (int) rectangle.getHeight(), (int) rectangle.getHeight(),
                    watermarkBean);
        }

    }
    try {
        watermarkPdfStamper.close();
    } catch (IOException decorateWatermark) {
        LOG.error("Exception occured in WatermarkServiceImpl. decorateWatermark Exception: "
                + decorateWatermark.getMessage());
    } catch (DocumentException documentException) {
        LOG.error("Exception occured in WatermarkServiceImpl. decorateWatermark Exception: "
                + documentException.getMessage());
    }

}

From source file:org.kuali.kra.s2s.service.impl.S2SUserAttachedFormServiceImpl.java

License:Educational Community License

private Map extractAttachments(PdfReader reader) throws IOException {
    Map fileMap = new HashMap();

    PdfDictionary catalog = reader.getCatalog();
    PdfDictionary names = (PdfDictionary) PdfReader.getPdfObject(catalog.get(PdfName.NAMES));
    if (names != null) {
        PdfDictionary embFiles = (PdfDictionary) PdfReader
                .getPdfObject(names.get(new PdfName("EmbeddedFiles")));
        if (embFiles != null) {
            HashMap embMap = PdfNameTree.readTree(embFiles);

            for (Iterator i = embMap.values().iterator(); i.hasNext();) {
                PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject((PdfObject) i.next());
                Object[] fileInfo = unpackFile(reader, filespec);
                if (!fileMap.containsKey(fileInfo[0])) {
                    fileMap.put(fileInfo[0], fileInfo[1]);
                }//from  ww w  .jav a  2  s .  c  o m
            }
        }
    }
    for (int k = 1; k <= reader.getNumberOfPages(); ++k) {
        PdfArray annots = (PdfArray) PdfReader.getPdfObject(reader.getPageN(k).get(PdfName.ANNOTS));
        if (annots == null)
            continue;
        for (Iterator i = annots.listIterator(); i.hasNext();) {
            PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject((PdfObject) i.next());
            PdfName subType = (PdfName) PdfReader.getPdfObject(annot.get(PdfName.SUBTYPE));
            if (!PdfName.FILEATTACHMENT.equals(subType))
                continue;
            PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(annot.get(PdfName.FS));
            Object[] fileInfo = unpackFile(reader, filespec);
            if (fileMap.containsKey(fileInfo[0])) {
                throw new RuntimeException(DUPLICATE_FILE_NAMES);
            }
            fileMap.put(fileInfo[0], fileInfo[1]);
        }
    }

    return fileMap;
}

From source file:org.lucee.extension.pdf.PDFStruct.java

License:Open Source License

public Struct getInfo() {

    PdfReader pr = null;
    try {/*from  w  w  w  . j  av  a 2 s  .  c  o m*/
        pr = getPdfReader();
        // PdfDictionary catalog = pr.getCatalog();
        int permissions = pr.getPermissions();
        boolean encrypted = pr.isEncrypted();

        Struct info = CFMLEngineFactory.getInstance().getCreationUtil().createStruct();
        info.setEL("FilePath", getFilePath());

        // access
        info.setEL("ChangingDocument", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_CONTENTS));
        info.setEL("Commenting", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_ANNOTATIONS));
        info.setEL("ContentExtraction", allowed(encrypted, permissions, PdfWriter.ALLOW_SCREENREADERS));
        info.setEL("CopyContent", allowed(encrypted, permissions, PdfWriter.ALLOW_COPY));
        info.setEL("DocumentAssembly",
                allowed(encrypted, permissions, PdfWriter.ALLOW_ASSEMBLY + PdfWriter.ALLOW_MODIFY_CONTENTS));
        info.setEL("FillingForm",
                allowed(encrypted, permissions, PdfWriter.ALLOW_FILL_IN + PdfWriter.ALLOW_MODIFY_ANNOTATIONS));
        info.setEL("Printing", allowed(encrypted, permissions, PdfWriter.ALLOW_PRINTING));
        info.setEL("Secure", "");
        info.setEL("Signing", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_ANNOTATIONS
                + PdfWriter.ALLOW_MODIFY_CONTENTS + PdfWriter.ALLOW_FILL_IN));

        info.setEL("Encryption", encrypted ? "Password Security" : "No Security");// MUST
        info.setEL("TotalPages", CFMLEngineFactory.getInstance().getCastUtil().toDouble(pr.getNumberOfPages()));
        info.setEL("Version", "1." + pr.getPdfVersion());
        info.setEL("permissions", "" + permissions);
        info.setEL("permiss", "" + PdfWriter.ALLOW_FILL_IN);

        info.setEL("Application", "");
        info.setEL("Author", "");
        info.setEL("CenterWindowOnScreen", "");
        info.setEL("Created", "");
        info.setEL("FitToWindow", "");
        info.setEL("HideMenubar", "");
        info.setEL("HideToolbar", "");
        info.setEL("HideWindowUI", "");
        info.setEL("Keywords", "");
        info.setEL("Language", "");
        info.setEL("Modified", "");
        info.setEL("PageLayout", "");
        info.setEL("Producer", "");
        info.setEL("Properties", "");
        info.setEL("ShowDocumentsOption", "");
        info.setEL("ShowWindowsOption", "");
        info.setEL("Subject", "");
        info.setEL("Title", "");
        info.setEL("Trapped", "");

        // info
        HashMap imap = pr.getInfo();
        Iterator it = imap.entrySet().iterator();
        Map.Entry entry;
        while (it.hasNext()) {
            entry = (Entry) it.next();
            info.setEL(CFMLEngineFactory.getInstance().getCastUtil().toString(entry.getKey(), null),
                    entry.getValue());
        }
        return info;
    } catch (PageException pe) {
        throw CFMLEngineFactory.getInstance().getExceptionUtil().createPageRuntimeException(pe);
    } finally {
        if (pr != null)
            pr.close();
    }
}

From source file:org.lucee.extension.pdf.tag.Document.java

License:Open Source License

private void render(OutputStream os, boolean doBookmarks, boolean doHtmlBookmarks)
        throws IOException, PageException, DocumentException {
    byte[] pdf = null;
    // merge multiple docs to 1
    if (documents.size() > 1) {
        PDFDocument[] pdfDocs = new PDFDocument[documents.size()];
        PdfReader[] pdfReaders = new PdfReader[pdfDocs.length];
        Iterator<PDFDocument> it = documents.iterator();
        int index = 0;
        // generate pdf with pd4ml
        while (it.hasNext()) {
            pdfDocs[index] = it.next();//from   ww  w .  j  ava  2  s  .  c  om
            pdfReaders[index] = new PdfReader(
                    pdfDocs[index].render(getDimension(), unitFactor, pageContext, doHtmlBookmarks));
            index++;
        }

        // collect together
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        com.lowagie.text.Document document = new com.lowagie.text.Document(
                pdfReaders[0].getPageSizeWithRotation(1));
        PdfCopy copy = new PdfCopy(document, baos);
        document.open();
        String name;
        ArrayList bookmarks = doBookmarks ? new ArrayList() : null;
        try {
            int size, totalPage = 0;
            Map parent;
            for (int doc = 0; doc < pdfReaders.length; doc++) {
                size = pdfReaders[doc].getNumberOfPages();

                PdfImportedPage ip;

                // bookmarks
                if (doBookmarks) {
                    name = pdfDocs[doc].getName();
                    if (!Util.isEmpty(name)) {
                        // TODO bookmarks.add(parent=PDFUtil.generateGoToBookMark(name, totalPage+1));
                    } else
                        parent = null;

                    if (doHtmlBookmarks) {
                        java.util.List pageBM = SimpleBookmark.getBookmark(pdfReaders[doc]);
                        if (pageBM != null) {
                            if (totalPage > 0)
                                SimpleBookmark.shiftPageNumbers(pageBM, totalPage, null);
                            // TODO if(parent!=null)PDFUtil.setChildBookmarks(parent,pageBM);
                            // TODO else bookmarks.addAll(pageBM);
                        }
                    }
                }

                totalPage++;
                for (int page = 1; page <= size; page++) {
                    if (page > 1)
                        totalPage++;
                    ip = copy.getImportedPage(pdfReaders[doc], page);

                    // ip.getPdfDocument().setHeader(arg0);
                    // ip.getPdfDocument().setFooter(arg0);
                    copy.addPage(ip);
                }
            }
            if (doBookmarks && !bookmarks.isEmpty())
                copy.setOutlines(bookmarks);
        } finally {
            document.close();
        }
        pdf = baos.toByteArray();
    } else if (documents.size() == 1) {
        pdf = (documents.get(0)).render(getDimension(), unitFactor, pageContext, doHtmlBookmarks);
    } else {
        pdf = getDocument().render(getDimension(), unitFactor, pageContext, doHtmlBookmarks);
    }

    // permission/encryption
    if (PDFDocument.ENC_NONE != encryption) {
        PdfReader reader = new PdfReader(pdf);
        com.lowagie.text.Document document = new com.lowagie.text.Document(reader.getPageSize(1));
        Info info = CFMLEngineFactory.getInstance().getInfo();
        document.addCreator("Lucee PDF Extension");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfCopy copy = new PdfCopy(document, baos);
        // PdfWriter writer = PdfWriter.getInstance(document, pdfOut);
        copy.setEncryption(PDFDocument.ENC_128BIT == encryption, userpassword, ownerpassword, permissions);
        document.open();
        int size = reader.getNumberOfPages();
        for (int page = 1; page <= size; page++) {
            copy.addPage(copy.getImportedPage(reader, page));
        }
        document.close();
        pdf = baos.toByteArray();
    }

    // write out
    if (os != null)
        Util.copy(new ByteArrayInputStream(pdf), os, true, false);
    if (!Util.isEmpty(name)) {
        pageContext.setVariable(name, pdf);
    }
}

From source file:org.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionAddHeaderFooter(boolean isHeader) throws PageException, IOException, DocumentException {
    required("pdf", "write", "source", source);
    // required("pdf", "write", "destination", destination);

    /*/*from   w ww. j a  va 2  s  .co  m*/
     * optinal - pages
     */
    /*
     * isBase64 = "yes|no" showonprint = "yes|no"> opacity = "header opacity" image = "image file name to be used as the header"
     * 
     */
    PDFStruct doc = toPDFDocument(source, password, null);
    PdfReader reader = doc.getPdfReader();
    BIF bif = null;
    if (NUMBERFORMAT_NUMERIC != numberformat) {
        ClassUtil classUtil = engine.getClassUtil();
        try {
            bif = classUtil.loadBIF(pageContext, "lucee.runtime.functions.displayFormatting.NumberFormat");
        } catch (Exception e) {
            e.printStackTrace();
            throw engine.getCastUtil().toPageException(e);
        }
    }
    // output stream
    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    OutputStream os = null;
    if (!Util.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }
    PdfStamper stamper = null;
    try {
        if (destination != null && destination.exists() && !overwrite)
            throw engine.getExceptionUtil()
                    .createApplicationException("destination file [" + destination + "] already exists");

        int len = reader.getNumberOfPages();
        Set<Integer> pageSet = PDFUtil.parsePageDefinition(pages, len);
        stamper = new PdfStamper(reader, destination.getOutputStream());
        if (font == null)
            font = getDefaultFont();
        // , new Font(FontFamily.HELVETICA, 14)
        for (int p = 1; p <= len; p++) {
            if (pageSet != null && !pageSet.contains(p))
                continue;

            Phrase header = text(text, p, len, numberformat, bif, font);
            // vertical orientation
            float y;

            if (isHeader) {
                y = reader.getPageSize(p).getTop(header.getFont().getCalculatedSize() + (topmargin - 3));
            } else {
                y = reader.getPageSize(p).getBottom((bottommargin + 2));
                /*
                 * System.out.println("y:"+y); System.out.println("bottom:"+reader.getPageSize(p).getBottom()); System.out.println("margin:"+bottommargin);
                 * System.out.println("font:"+header.getFont().getSize()); System.out.println("CalculatedStyle:"+header.getFont().getCalculatedStyle());
                 * System.out.println("CalculatedSize:"+header.getFont().getCalculatedSize());
                 */
            }
            // float yh = reader.getPageSize(p).getTop(topmargin);
            // float yf = reader.getPageSize(p).getBottom(bottommargin);
            System.out.println("++++++++++++");
            System.out.println(y);
            System.out.println(reader.getPageSize(p).getTop());
            // horizontal orientation

            float x = reader.getPageSize(p).getWidth() / 2;
            if (Element.ALIGN_LEFT == align) {
                x = leftmargin;
            } else if (Element.ALIGN_RIGHT == align) {
                x = reader.getPageSize(p).getWidth() - rightmargin;
            } else {
                x = reader.getPageSize(p).getWidth() / 2;
            }
            ColumnText.showTextAligned(stamper.getOverContent(p), align, header, x, y, 0);

        }
    } finally {
        try {
            if (stamper != null)
                stamper.close();
        } catch (IOException ioe) {
        }
        ;
        Util.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
                        destination, true);// MUST overwrite
            if (!Util.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }

    // PdfReader pr = doc.getPdfReader();
    // output
    /*
     * boolean destIsSource = doc.getResource()!=null && destination.equals(doc.getResource());
     * 
     * OutputStream os=null; if(destIsSource){ os=new ByteArrayOutputStream(); } else if(destination!=null) { os=destination.getOutputStream(); }
     * 
     * try { PDFUtil.concat(new PDFStruct[]{doc}, os, true, true, true,version); } finally { Util.closeEL(os); if(os instanceof ByteArrayOutputStream) {
     * if(destination!=null)engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream)os).toByteArray()), destination,true);// MUST overwrite
     * } }
     */
}

From source file:org.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
        throw engine.getExceptionUtil().createApplicationException(
                "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
        throw engine.getExceptionUtil()
                .createApplicationException("destination file [" + destination + "] already exists");

    // image/*from  w w  w.  ja  v a  2  s.c o m*/
    Image img = null;
    if (image != null) {
        // TODO lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext,image,false,false,true,null);
        // TODO img=Image.getInstance(ri.getBufferedImage(),null,false);
    }
    // copy From
    else {
        byte[] barr;
        try {
            Resource res = copyFrom instanceof String
                    ? engine.getResourceUtil().toResourceExisting(pageContext, (String) copyFrom)
                    : engine.getCastUtil().toResource(copyFrom);
            barr = PDFUtil.toBytes(res);
        } catch (PageException ee) {
            barr = engine.getCastUtil().toBinary(copyFrom);
        }
        img = Image.getInstance(PDFUtil.toImage(barr, 1), null, false);

    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!Util.isEmpty(position)) {
        int index = position.indexOf(',');
        if (index == -1)
            throw engine.getExceptionUtil()
                    .createApplicationException("attribute [position] has an invalid value [" + position + "],"
                            + "value should follow one of the following pattern [40,50], [40,] or [,50]");
        String strX = position.substring(0, index).trim();
        String strY = position.substring(index + 1).trim();
        if (!Util.isEmpty(strX))
            x = engine.getCastUtil().toIntValue(strX);
        if (!Util.isEmpty(strY))
            y = engine.getCastUtil().toIntValue(strY);

    }

    PDFStruct doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    OutputStream os = null;
    if (!Util.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {

        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        if (len > 0) {
            if (x == UNDEFINED || y == UNDEFINED) {
                PdfImportedPage first = stamp.getImportedPage(reader, 1);
                if (y == UNDEFINED)
                    y = (first.getHeight() - img.getHeight()) / 2;
                if (x == UNDEFINED)
                    x = (first.getWidth() - img.getWidth()) / 2;
            }
            img.setAbsolutePosition(x, y);
            // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

        }

        // rotation
        if (rotation != 0) {
            img.setRotationDegrees(rotation);
        }

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            // print.out("op:"+opacity);
            gs1.setFillOpacity(opacity);
            // gs1.setStrokeOpacity(opacity);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        Util.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
                        destination, true);// MUST overwrite
            if (!Util.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:org.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionRemoveWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "removeWatermark", "source", source);

    if (destination != null && destination.exists() && !overwrite)
        throw engine.getExceptionUtil()
                .createApplicationException("destination file [" + destination + "] already exists");

    BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, 1, 1);/*ww  w  . jav a 2 s . c o  m*/

    Image img = Image.getInstance(bi, null, false);
    img.setAbsolutePosition(1, 1);

    PDFStruct doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();

    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!Util.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {
        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            gs1.setFillOpacity(0);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        Util.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
                        destination, true);// MUST overwrite
            if (!Util.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:org.lucee.extension.pdf.util.PDFUtil.java

License:Open Source License

/**
 * @param docs//from   ww w.  j  a va  2s . c o m
 * @param os
 * @param removePages
 *            if true, pages defined in PDFDocument will be removed, otherwise all other pages will be removed
 * @param version
 * @throws PageException
 * @throws IOException
 * @throws DocumentException
 */
public static void concat(PDFStruct[] docs, OutputStream os, boolean keepBookmark, boolean removePages,
        boolean stopOnError, char version) throws PageException, IOException, DocumentException {
    Document document = null;
    PdfCopy writer = null;
    PdfReader reader;
    Set pages;
    boolean isInit = false;
    PdfImportedPage page;
    try {
        int pageOffset = 0;
        ArrayList master = new ArrayList();

        for (int i = 0; i < docs.length; i++) {
            // we create a reader for a certain document
            pages = docs[i].getPages();
            try {
                reader = docs[i].getPdfReader();
            } catch (Throwable t) {
                if (t instanceof ThreadDeath)
                    throw (ThreadDeath) t;
                if (!stopOnError)
                    continue;
                throw CFMLEngineFactory.getInstance().getCastUtil().toPageException(t);
            }
            reader.consolidateNamedDestinations();

            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
            List bookmarks = keepBookmark ? SimpleBookmark.getBookmark(reader) : null;
            if (bookmarks != null) {
                removeBookmarks(bookmarks, pages, removePages);
                if (pageOffset != 0)
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                master.addAll(bookmarks);
            }

            if (!isInit) {
                isInit = true;
                document = new Document(reader.getPageSizeWithRotation(1));
                writer = new PdfCopy(document, os);

                if (version != 0)
                    writer.setPdfVersion(version);

                document.open();
            }

            for (int y = 1; y <= n; y++) {
                if (pages != null && removePages == pages.contains(Integer.valueOf(y))) {
                    continue;
                }
                pageOffset++;
                page = writer.getImportedPage(reader, y);
                writer.addPage(page);
            }
            PRAcroForm form = reader.getAcroForm();
            if (form != null)
                writer.copyAcroForm(reader);
        }
        if (master.size() > 0)
            writer.setOutlines(master);

    } finally {
        CFMLEngineFactory.getInstance().getIOUtil().closeSilent(document);
    }
}