Example usage for com.lowagie.text.pdf PdfStamper close

List of usage examples for com.lowagie.text.pdf PdfStamper close

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfStamper close.

Prototype

public void close() throws DocumentException, IOException 

Source Link

Document

Closes the document.

Usage

From source file:it.jugpadova.blo.ParticipantBadgeBo.java

License:Apache License

/**
 * Build a PDF with the badges of confirmed participants.
 *//*from  w w w.  j a  v  a  2 s. c o  m*/
public byte[] buildPDFBadges(Event event) throws IOException, DocumentException {
    List<Participant> participants = participantDao
            .findConfirmedParticipantsByEventIdOrderByLastNameAndFirstName(event.getId());
    int participantsPerPage = getParticipantsPerPage(event);
    int pages = (participants.size() / participantsPerPage) + 2; // prints a more page with empty badges
    ByteArrayOutputStream pdfMergedBaos = new ByteArrayOutputStream();
    PdfCopyFields pdfMerged = new PdfCopyFields(pdfMergedBaos);
    int newIndex = 1;
    for (int i = 0; i < pages; i++) {
        InputStream templateIs = getBadgePageTemplateInputStream(event);
        RandomAccessFileOrArray rafa = new RandomAccessFileOrArray(templateIs);
        PdfReader template = new PdfReader(rafa, null);
        ByteArrayOutputStream pdfPageBaos = new ByteArrayOutputStream();
        PdfStamper pdfPage = new PdfStamper(template, pdfPageBaos);
        AcroFields pdfPageForm = pdfPage.getAcroFields();
        for (int j = 1; j <= participantsPerPage; j++) {
            pdfPageForm.renameField("title" + j, "title" + newIndex);
            pdfPageForm.renameField("firstName" + j, "firstName" + newIndex);
            pdfPageForm.renameField("lastName" + j, "lastName" + newIndex);
            pdfPageForm.renameField("firm" + j, "firm" + newIndex);
            pdfPageForm.renameField("role" + j, "role" + newIndex);
            newIndex++;
        }
        pdfPage.close();
        template.close();
        pdfMerged.addDocument(new PdfReader(pdfPageBaos.toByteArray()));
    }
    pdfMerged.close();
    ByteArrayOutputStream resultBaos = new ByteArrayOutputStream();
    PdfReader mergedReader = new PdfReader(pdfMergedBaos.toByteArray());
    PdfStamper mergedStamper = new PdfStamper(mergedReader, resultBaos);
    AcroFields mergedForm = mergedStamper.getAcroFields();
    int count = 1;
    for (int i = 0; i < pages; i++) {
        for (int j = 1; j <= participantsPerPage; j++) {
            mergedForm.setField("title" + count, event.getTitle());
            count++;
        }
    }
    count = 1;
    for (Participant participant : participants) {
        mergedForm.setField("firstName" + count, participant.getFirstName());
        mergedForm.setField("lastName" + count, participant.getLastName());
        count++;
    }
    mergedStamper.setFormFlattening(true);
    mergedStamper.close();
    return resultBaos.toByteArray();
}

From source file:it.pdfsam.console.tools.pdf.PdfEncrypt.java

License:Open Source License

/**
 * Execute the encrypt command. On error an exception is thrown.
 * @throws EncryptException/*  w  ww  . j a v  a  2  s .c om*/
 */
public void execute() throws EncryptException {
    try {
        workingIndeterminate();
        out_message = "";
        int f = 0;
        for (Iterator f_list_itr = f_list.iterator(); f_list_itr.hasNext();) {
            String file_name = f_list_itr.next().toString();
            prefixParser = new PrefixParser(prefix_value, new File(file_name).getName());
            File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_dir.getAbsolutePath());
            out_message += LogFormatter.formatMessage("Temporary file created-\n");
            PdfReader pdfReader = new PdfReader(new RandomAccessFileOrArray(file_name), null);
            HashMap meta = pdfReader.getInfo();
            meta.put("Creator", MainConsole.CREATOR);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(tmp_o_file));
            if (compressed_boolean) {
                pdfStamper.setFullCompression();
            }
            pdfStamper.setMoreInfo(meta);
            pdfStamper.setEncryption(etype, u_pwd, a_pwd, user_permissions);
            pdfStamper.close();
            /*PdfEncryptor.encrypt(pdf_reader,new FileOutputStream(tmp_o_file), etype, u_pwd, a_pwd,user_permissions, meta);*/
            File out_file = new File(o_dir, prefixParser.generateFileName());
            renameTemporaryFile(tmp_o_file, out_file, overwrite_boolean);
            f++;
        }
        out_message += LogFormatter.formatMessage("Pdf files encrypted in " + o_dir.getAbsolutePath() + "-\n"
                + PdfEncryptor.getPermissionsVerbose(user_permissions));
    } catch (Exception e) {
        throw new EncryptException(e);
    } finally {
        workCompleted();
    }
}

From source file:lucee.runtime.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 new ApplicationException(
                "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
        throw new ApplicationException("destination file [" + destination + "] already exists");

    // image//from w ww.  j  a  va 2s  .  c om
    Image img = null;
    if (image != null) {
        lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext, image, false, false, true,
                null);
        img = Image.getInstance(ri.getBufferedImage(), null, false);
    }
    // copy From
    else {
        byte[] barr;
        try {
            Resource res = Caster.toResource(pageContext, copyFrom, true);
            barr = IOUtil.toBytes(res);
        } catch (ExpressionException ee) {
            barr = Caster.toBinary(copyFrom);
        }
        img = Image.getInstance(PDFUtil.toImage(barr, 1).getBufferedImage(), null, false);

    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!StringUtil.isEmpty(position)) {
        int index = position.indexOf(',');
        if (index == -1)
            throw new ApplicationException("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 (!StringUtil.isEmpty(strX))
            x = Caster.toIntValue(strX);
        if (!StringUtil.isEmpty(strY))
            y = Caster.toIntValue(strY);

    }

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    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 (!StringUtil.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 {
        IOUtil.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                IOUtil.copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination,
                        true);// MUST overwrite
            if (!StringUtil.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:lucee.runtime.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 new ApplicationException("destination file [" + destination + "] already exists");

    lucee.runtime.img.Image ri = new lucee.runtime.img.Image(1, 1, BufferedImage.TYPE_INT_RGB, Color.BLACK);
    Image img = Image.getInstance(ri.getBufferedImage(), null, false);
    img.setAbsolutePosition(1, 1);/*from ww w .j ava 2  s .c  o m*/

    PDFDocument 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 (!StringUtil.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 {
        IOUtil.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                IOUtil.copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination,
                        true);// MUST overwrite
            if (!StringUtil.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:lucee.runtime.tag.PDF.java

License:Open Source License

private void doActionSetInfo() throws PageException, IOException, DocumentException {
    required("pdf", "setInfo", "info", info);
    required("pdf", "getInfo", "source", source);

    PDFDocument doc = toPDFDocument(source, password, null);
    PdfReader pr = doc.getPdfReader();/*from   w ww  .  j a v a  2s  . co  m*/
    OutputStream os = null;
    try {
        if (destination == null) {
            if (doc.getResource() == null)
                throw new ApplicationException(
                        "source is not based on a resource, destination file is required");
            destination = doc.getResource();
        } else if (destination.exists() && !overwrite)
            throw new ApplicationException("destination file [" + destination + "] already exists");

        PdfStamper stamp = new PdfStamper(pr, os = destination.getOutputStream());
        HashMap moreInfo = new HashMap();

        //Key[] keys = info.keys();
        Iterator<Entry<Key, Object>> it = info.entryIterator();
        Entry<Key, Object> e;
        while (it.hasNext()) {
            e = it.next();
            moreInfo.put(StringUtil.ucFirst(e.getKey().getLowerString()), Caster.toString(e.getValue()));
        }
        // author
        Object value = info.get(KeyConstants._author, null);
        if (value != null)
            moreInfo.put("Author", Caster.toString(value));
        // keywords
        value = info.get("keywords", null);
        if (value != null)
            moreInfo.put("Keywords", Caster.toString(value));
        // title
        value = info.get(KeyConstants._title, null);
        if (value != null)
            moreInfo.put("Title", Caster.toString(value));
        // subject
        value = info.get(KeyConstants._subject, null);
        if (value != null)
            moreInfo.put("Subject", Caster.toString(value));
        // creator
        value = info.get("creator", null);
        if (value != null)
            moreInfo.put("Creator", Caster.toString(value));
        // trapped
        value = info.get("Trapped", null);
        if (value != null)
            moreInfo.put("Trapped", Caster.toString(value));
        // Created
        value = info.get("Created", null);
        if (value != null)
            moreInfo.put("Created", Caster.toString(value));
        // Language
        value = info.get("Language", null);
        if (value != null)
            moreInfo.put("Language", Caster.toString(value));

        stamp.setMoreInfo(moreInfo);
        stamp.close();

    } finally {
        IOUtil.closeEL(os);
        pr.close();
    }
}

From source file:mpv5.utils.export.PDFFile.java

License:Open Source License

@Override
public void run() {

    Log.Debug(this, "All fields:");
    for (Iterator<String> it = getData().keySet().iterator(); it.hasNext();) {
        String k = it.next();/*from  w  w  w . ja  v a 2  s . c o  m*/
        Log.Debug(this, "Key: " + k + " [" + getData().get(k) + "]");
    }
    try {
        Log.Debug(this, "Running export for template file: " + getPath() + "  to file: " + getTarget());
        try {
            template = new PdfReader(getPath());
        } catch (Exception iOException) {
            Log.Debug(iOException);
        }
        Log.Debug(this, "Checking PDF File: " + getPath());
        acroFields = template.getAcroFields();
        Log.Debug(this, "Creating PDF File: " + getTarget().getPath());
        PdfStamper pdfStamper = new PdfStamper(template, new FileOutputStream(getTarget().getPath()));
        pdfStamper.setFormFlattening(true);
        acroFields = pdfStamper.getAcroFields();
        HashMap PDFFields = acroFields.getFields();
        for (Iterator it = PDFFields.keySet().iterator(); it.hasNext();) {
            Object object = it.next();
            String keyt = String.valueOf(object);
            if (getData().get(keyt) != null) {
                Log.Debug(this, "Filling Field: " + object + " [" + getData().get(keyt) + "]");
                if (!keyt.startsWith("image")) {
                    acroFields.setField(keyt, String.valueOf(getData().get(keyt)));
                } else {
                    setImage(pdfStamper, keyt, ((MPIcon) getData().get(keyt)).getImage());
                }
            }
            if (getData().get(keyt.replace("_", ".")) != null) {
                Log.Debug(this, "Filling Field: " + object + " [" + getData().get(keyt) + "]");
                if (!keyt.startsWith("image")) {
                    acroFields.setField(keyt, String.valueOf(getData().get(keyt.replace("_", "."))));
                } else {
                    setImage(pdfStamper, keyt, ((MPIcon) getData().get(keyt)).getImage());
                }
            }
        }

        Log.Debug(this, "Looking for tables in: " + getName());
        for (Iterator<String> it = getData().keySet().iterator(); it.hasNext();) {
            String key = it.next();
            if (key.contains(TableHandler.KEY_TABLE)) {//Table found
                @SuppressWarnings("unchecked")
                List<String[]> value = (List<String[]>) getData().get(key);
                for (int i = 0; i < value.size(); i++) {
                    String[] strings = value.get(i);
                    if (getTemplate() != null) {
                        strings = refactorRow(getTemplate(), strings);
                    }
                    for (int j = 0; j < strings.length; j++) {
                        String cellValue = strings[j];
                        String fieldname = "col" + j + "row" + i;
                        Log.Debug(this, "Filling Field: " + fieldname + " [" + getData().get(cellValue) + "]");
                        acroFields.setField(fieldname, cellValue);
                    }
                }
            }
        }

        pdfStamper.close();
        Log.Debug(this, "Done file: " + getTarget().getPath());
    } catch (Exception ex) {
        Log.Debug(ex);
    }
}

From source file:net.laubenberger.bogatyr.helper.HelperPdf.java

License:Open Source License

/**
 * Modifies the meta data of given PDF and stores it in a new {@link File}.
 * <strong>Meta data example:"</strong> metadata.put("Title", "Example");
 * metadata.put("Author", "Stefan Laubenberger"); metadata.put("Subject",
 * "Example PDF meta data"); metadata.put("Keywords", "Example, PDF");
 * metadata.put("Creator", "http://www.laubenberger.net/");
 * metadata.put("Producer", "Silvan Spross");
 * // www . j  a  va 2s .c om
 * @param source
 *           {@link File}
 * @param dest
 *           {@link File} for the modified PDF
 * @param metadata
 *           list with the new meta data informations
 * @throws DocumentException
 * @throws IOException
 * @since 0.7.0
 */
@SuppressWarnings("unchecked")
public static void setMetaData(final File source, final File dest, final Map<String, String> metadata)
        throws IOException, DocumentException { // $JUnit$
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodStart(source, dest, metadata));
    if (null == source) {
        throw new RuntimeExceptionIsNull("source"); //$NON-NLS-1$
    }
    if (null == dest) {
        throw new RuntimeExceptionIsNull("dest"); //$NON-NLS-1$
    }
    if (HelperObject.isEquals(source, dest)) {
        throw new RuntimeExceptionIsEquals("source", "dest"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    if (null == metadata) {
        throw new RuntimeExceptionIsNull("metadata"); //$NON-NLS-1$
    }

    PdfReader reader = null;
    PdfStamper stamper = null;

    try {
        reader = new PdfReader(source.getAbsolutePath());
        stamper = new PdfStamper(reader, new FileOutputStream(dest));

        final HashMap<String, String> info = reader.getInfo();
        info.putAll(metadata);

        stamper.setMoreInfo(info);
    } finally {
        if (null != stamper) {
            stamper.close();
        }
        if (null != reader) {
            reader.close();
        }
    }
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodExit());
}

From source file:net.laubenberger.wichtel.helper.HelperPdf.java

License:Open Source License

/**
 * Modifies the meta data of given PDF and stores it in a new {@link File}.
 * <strong>Meta data example:"</strong> metadata.put("Title", "Example");
 * metadata.put("Author", "Stefan Laubenberger"); metadata.put("Subject",
 * "Example PDF meta data"); metadata.put("Keywords", "Example, PDF");
 * metadata.put("Creator", "http://www.laubenberger.net/");
 * metadata.put("Producer", "Silvan Spross");
 * /*from w w  w  .  j  ava  2  s  . c o  m*/
 * @param source
 *           {@link File}
 * @param dest
 *           {@link File} for the modified PDF
 * @param metadata
 *           list with the new meta data informations
 * @throws DocumentException
 * @throws IOException
 * @since 0.0.1
 */
@SuppressWarnings("unchecked")
public static void setMetaData(final File source, final File dest, final Map<String, String> metadata)
        throws IOException, DocumentException { // $JUnit$
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodStart(source, dest, metadata));
    if (null == source) {
        throw new RuntimeExceptionIsNull("source"); //$NON-NLS-1$
    }
    if (null == dest) {
        throw new RuntimeExceptionIsNull("dest"); //$NON-NLS-1$
    }
    if (HelperObject.isEquals(source, dest)) {
        throw new RuntimeExceptionIsEquals("source", "dest"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    if (null == metadata) {
        throw new RuntimeExceptionIsNull("metadata"); //$NON-NLS-1$
    }

    try (FileOutputStream fos = new FileOutputStream(dest)) {
        final PdfReader reader = new PdfReader(source.getAbsolutePath());
        final PdfStamper stamper = new PdfStamper(reader, fos);

        final HashMap<String, String> info = reader.getInfo();
        info.putAll(metadata);

        stamper.setMoreInfo(info);

        stamper.close();
        reader.close();
    }
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodExit());
}

From source file:net.mitnet.tools.pdf.book.pdf.util.PdfBookmarkBuilder.java

License:Open Source License

public void addBookmarks(String inputPdfFile, List<HashMap<String, Object>> bookmarks, String outputPdfFile)
        throws IOException, DocumentException {

    PdfReader reader = new PdfReader(inputPdfFile);

    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPdfFile));

    if (bookmarks != null) {
        System.out.println("bookmarks.size: " + bookmarks.size());
    }/*  ww  w.j a v a2  s .  c  o  m*/
    System.out.println("bookmarks: " + bookmarks);

    stamper.setOutlines(bookmarks);

    stamper.addViewerPreference(PdfName.NONFULLSCREENPAGEMODE, PdfName.USEOUTLINES);

    stamper.close();
}

From source file:net.mitnet.tools.pdf.book.publisher.BookPublisher.java

License:Open Source License

/**
 * Update PDF book with meta-data.//from   www  . j a  va  2 s. c  om
 * 
 * @see http://itext-general.2136553.n4.nabble.com/how-to-add-meta-information-to-a-document-that-is-closed-td2137179.html
 * @see com.lowagie.examples.general.copystamp.AddWatermarkPageNumbers
 */
private void updatePdfBookWithMeta(File pdfBookFile) throws IOException, DocumentException {

    info("updating PDF book with meta ...");

    File inputPdfFile = pdfBookFile;
    String inputPdfFilename = inputPdfFile.getAbsolutePath();
    File outputPdfFile = File.createTempFile(DEFAULT_PDF_BOOK_FILE_NAME, FileExtensionConstants.PDF_EXTENSION);
    debug("outputPdfFile: " + outputPdfFile);
    String outputPdfFilename = outputPdfFile.getAbsolutePath();

    PdfReader reader = new PdfReader(inputPdfFilename);

    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPdfFilename));

    HashMap metaMap = new HashMap();

    String metaTitle = config.getMetaTitle();
    addNonEmptyMapValue(metaMap, PdfMetaKeys.TITLE, metaTitle);

    String metaSubject = config.getMetaSubject();
    addNonEmptyMapValue(metaMap, PdfMetaKeys.SUBJECT, metaSubject);

    String metaKeywords = config.getMetaKeywords();
    addNonEmptyMapValue(metaMap, PdfMetaKeys.KEYWORDS, metaKeywords);

    String metaCreator = PDF_PUBLISHER_TOOLS_IDENT + " with " + Document.getVersion();
    addNonEmptyMapValue(metaMap, PdfMetaKeys.CREATOR, metaCreator);

    String metaAuthor = config.getMetaAuthor();
    addNonEmptyMapValue(metaMap, PdfMetaKeys.AUTHOR, metaAuthor);

    String metaVersionId = config.getMetaVersionId();
    addNonEmptyMapValue(metaMap, PdfMetaKeys.VERSION_ID, metaVersionId);

    debug("updating PDF book with meta map: " + metaMap);

    stamper.setMoreInfo(metaMap);

    stamper.close();

    if (outputPdfFile.exists()) {
        FileUtils.copyFile(outputPdfFile, pdfBookFile);
        FileUtils.deleteQuietly(outputPdfFile);
    }
}