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

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

Introduction

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

Prototype

public void setMoreInfo(HashMap moreInfo) 

Source Link

Document

An optional String map to add or change values in the info dictionary.

Usage

From source file:es.gob.afirma.signers.pades.PdfPreProcessor.java

License:Open Source License

/** Añade campos adicionales al diccionario PDF.
 * @param moreInfo Campos a añadir al diccionario PDF
 * @param stp Estampador de PDF, debe abrirse y cerrarse fuera de este método */
public static void addMoreInfo(final Map<String, String> moreInfo, final PdfStamper stp) {
    if (moreInfo == null || moreInfo.isEmpty()) {
        return;// w ww.  j a  v a 2 s . co m
    }
    stp.setMoreInfo(moreInfo);
}

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/*from   ww w .j  a  va2s .co  m*/
 */
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 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  ww  w.  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: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");
 * /*from w w  w  . j  a  v  a  2  s  . 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");
 * //  w  w w  .  j ava2 s .  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.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.publisher.BookPublisher.java

License:Open Source License

/**
 * Update PDF book with meta-data.// www .j av  a2s.  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);
    }
}

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

License:Open Source License

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

    PDFStruct doc = toPDFDocument(source, password, null);
    PdfReader pr = doc.getPdfReader();/*from ww w  . j ava  2s .  c om*/
    OutputStream os = null;
    try {
        if (destination == null) {
            if (doc.getResource() == null)
                throw engine.getExceptionUtil().createApplicationException(
                        "source is not based on a resource, destination file is required");
            destination = doc.getResource();
        } else if (destination.exists() && !overwrite)
            throw engine.getExceptionUtil()
                    .createApplicationException("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(engine.getStringUtil().ucFirst(e.getKey().getLowerString()),
                    engine.getCastUtil().toString(e.getValue()));
        }
        // author
        Object value = info.get("author", null);
        if (value != null)
            moreInfo.put("Author", engine.getCastUtil().toString(value));
        // keywords
        value = info.get("keywords", null);
        if (value != null)
            moreInfo.put("Keywords", engine.getCastUtil().toString(value));
        // title
        value = info.get("title", null);
        if (value != null)
            moreInfo.put("Title", engine.getCastUtil().toString(value));
        // subject
        value = info.get("subject", null);
        if (value != null)
            moreInfo.put("Subject", engine.getCastUtil().toString(value));
        // creator
        value = info.get("creator", null);
        if (value != null)
            moreInfo.put("Creator", engine.getCastUtil().toString(value));
        // trapped
        value = info.get("Trapped", null);
        if (value != null)
            moreInfo.put("Trapped", engine.getCastUtil().toString(value));
        // Created
        value = info.get("Created", null);
        if (value != null)
            moreInfo.put("Created", engine.getCastUtil().toString(value));
        // Language
        value = info.get("Language", null);
        if (value != null)
            moreInfo.put("Language", engine.getCastUtil().toString(value));

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

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

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 ww .  j  av  a2  s. co  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();
    }
}