Example usage for com.lowagie.text.pdf PdfWriter AllowPrinting

List of usage examples for com.lowagie.text.pdf PdfWriter AllowPrinting

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter AllowPrinting.

Prototype

int AllowPrinting

To view the source code for com.lowagie.text.pdf PdfWriter AllowPrinting.

Click Source Link

Usage

From source file:com.orange.atk.atkUI.corecli.utils.PdfUtilities.java

License:Apache License

/**
 * Encrypt (allow only printing permission) the given pdf file with the given passwords.
 * Encryption must be the latest operation on the file.
 * @param pdfFileName/*  www  .j a v  a 2 s  .  c o  m*/
 * @throws IOException
 * @throws DocumentException
 */
public void encryptPDF(String pdfFileName) throws IOException, DocumentException {
    // 1. copy
    File tmpPDFFile = new File(tmpDir, "tmpPDF.pdf");
    copyFile(new File(pdfFileName), tmpPDFFile);
    // 2. encrypt
    PdfReader reader = new PdfReader(tmpPDFFile.getAbsolutePath());
    PdfEncryptor.encrypt(reader, new FileOutputStream(pdfFileName), true, pdfEncryptionUserPassword,
            pdfEncryptionOwnerPassword, PdfWriter.AllowPrinting /*| PdfWriter.AllowCopy*/);
}

From source file:fr.univlorraine.mondossierweb.controllers.CalendrierController.java

License:Apache License

/**
 * //ww  w . j ava  2s. c o  m
 * @return le fichier pdf du calendrier des examens.
 */
public com.vaadin.server.Resource exportPdf() {

    String nomFichier = applicationContext.getMessage("pdf.calendrier.title", null, Locale.getDefault()) + " "
            + MainUI.getCurrent().getEtudiant().getNom().replace('.', ' ').replace(' ', '_') + ".pdf";

    nomFichier = nomFichier.replaceAll(" ", "_");

    StreamResource.StreamSource source = new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
                PdfWriter docWriter = null;
                Document document = configureDocument(MARGE_PDF);
                docWriter = PdfWriter.getInstance(document, baosPDF);
                docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                docWriter.setStrictImageSequence(true);
                creerPdfCalendrier(document, MainUI.getCurrent().getEtudiant());
                docWriter.close();
                baosPDF.close();
                //Creation de l'export
                byte[] bytes = baosPDF.toByteArray();
                return new ByteArrayInputStream(bytes);
            } catch (DocumentException e) {
                LOG.error("Erreur  la gnration du calendrier des examens : DocumentException ", e);
                return null;
            } catch (IOException e) {
                LOG.error("Erreur  la gnration du calendrier des examens : IOException ", e);
                return null;
            }

        }
    };

    // Cration de la ressource 
    StreamResource resource = new StreamResource(source, nomFichier);
    resource.setMIMEType("application/force-download;charset=UTF-8");
    resource.setCacheTime(0);
    return resource;

}

From source file:fr.univlorraine.mondossierweb.controllers.InscriptionController.java

License:Apache License

/**
 * /*from w  w  w.j  a va2  s  . c om*/
 * @return le fichier pdf.
 */
public com.vaadin.server.Resource exportPdf(Inscription inscription) {

    // verifie les autorisations
    if (!etudiantController.proposerCertificat(inscription, MainUI.getCurrent().getEtudiant())) {
        return null;
    }

    String nomFichier = applicationContext.getMessage("pdf.certificat.title", null, Locale.getDefault()) + "_"
            + inscription.getCod_etp() + "_" + inscription.getCod_anu().replace('/', '-') + "_"
            + MainUI.getCurrent().getEtudiant().getNom().replace('.', ' ').replace(' ', '_') + ".pdf";
    nomFichier = nomFichier.replaceAll(" ", "_");

    StreamResource.StreamSource source = new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
                PdfWriter docWriter = null;
                Document document = configureDocument();
                docWriter = PdfWriter.getInstance(document, baosPDF);
                docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                docWriter.setStrictImageSequence(true);
                creerPdfCertificatScolarite(document, MainUI.getCurrent().getEtudiant(), inscription);
                docWriter.close();
                baosPDF.close();
                //Creation de l'export
                byte[] bytes = baosPDF.toByteArray();
                return new ByteArrayInputStream(bytes);
            } catch (DocumentException e) {
                LOG.error("Erreur  la gnration du certificat : DocumentException ", e);
                return null;
            } catch (IOException e) {
                LOG.error("Erreur  la gnration du certificat : IOException ", e);
                return null;
            }

        }
    };

    // Cration de la ressource 
    StreamResource resource = new StreamResource(source, nomFichier);
    resource.setMIMEType("application/force-download;charset=UTF-8");
    resource.setCacheTime(0);
    return resource;
}

From source file:fr.univlorraine.mondossierweb.controllers.ListeInscritsController.java

License:Apache License

/**
 * Retourne le trombinoscope en pdf// ww w .j  a v  a 2s  . c  o m
 * @param linscrits
 * @param listecodind
 * @return
 */
public InputStream getPdfStream(List<Inscrit> linscrits, List<String> listecodind, String libObj,
        String annee) {

    LOG.debug("generation pdf : " + libObj + " " + annee + " " + linscrits.size() + " " + listecodind.size());
    try {
        ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
        PdfWriter docWriter = null;
        Document document = configureDocument(MARGE_PDF);
        docWriter = PdfWriter.getInstance(document, baosPDF);
        docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
        docWriter.setStrictImageSequence(true);
        creerPdfTrombinoscope(document, linscrits, listecodind, libObj, annee);
        docWriter.close();
        baosPDF.close();
        //Creation de l'export
        byte[] bytes = baosPDF.toByteArray();
        return new ByteArrayInputStream(bytes);
    } catch (DocumentException e) {
        LOG.error("Erreur  la gnration du trombinoscope : DocumentException ", e);
        return null;
    } catch (IOException e) {
        LOG.error("Erreur  la gnration du trombinoscope : IOException ", e);
        return null;
    }

}

From source file:fr.univlorraine.mondossierweb.controllers.NoteController.java

License:Apache License

/**
 * // w  w  w  . j  a  va2s.c  om
 * @return le fichier pdf du rsum des notes.
 */
public com.vaadin.server.Resource exportPdfResume() {

    String nomFichier = applicationContext.getMessage("pdf.notes.title", null, Locale.getDefault()) + " "
            + MainUI.getCurrent().getEtudiant().getNom().replace('.', ' ').replace(' ', '_') + ".pdf";
    nomFichier = nomFichier.replaceAll(" ", "_");

    StreamResource.StreamSource source = new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
                PdfWriter docWriter = null;
                Document document = configureDocument(MARGE_PDF);
                docWriter = PdfWriter.getInstance(document, baosPDF);
                docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                docWriter.setStrictImageSequence(true);
                if (configController.isInsertionFiligranePdfNotes()) {
                    docWriter.setPageEvent(new Watermark());
                }
                creerPdfResume(document, MainUI.getCurrent().getEtudiant());
                docWriter.close();
                baosPDF.close();
                //Creation de l'export
                byte[] bytes = baosPDF.toByteArray();
                return new ByteArrayInputStream(bytes);
            } catch (DocumentException e) {
                LOG.error("Erreur  la gnration du rsum des notes : DocumentException ", e);
                return null;
            } catch (IOException e) {
                LOG.error("Erreur  la gnration du rsum des notes : IOException ", e);
                return null;
            }

        }
    };

    // Cration de la ressource 
    StreamResource resource = new StreamResource(source, nomFichier);
    resource.setMIMEType("application/force-download;charset=UTF-8");
    resource.setCacheTime(0);
    return resource;
}

From source file:fr.univlorraine.mondossierweb.controllers.NoteController.java

License:Apache License

/**
 * /*  ww  w.java2s . c om*/
 * @return le fichier pdf du detail des notes.
 */
public com.vaadin.server.Resource exportPdfDetail(Etape etape) {

    String nomFichier = applicationContext.getMessage("pdf.detail.title", null, Locale.getDefault()) + " "
            + MainUI.getCurrent().getEtudiant().getNom().replace('.', ' ').replace(' ', '_') + ".pdf";
    nomFichier = nomFichier.replaceAll(" ", "_");

    StreamResource.StreamSource source = new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
                PdfWriter docWriter = null;
                Document document = configureDocument(MARGE_PDF);
                docWriter = PdfWriter.getInstance(document, baosPDF);
                docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                docWriter.setStrictImageSequence(true);
                if (configController.isInsertionFiligranePdfNotes()) {
                    docWriter.setPageEvent(new Watermark());
                }
                creerPdfDetail(document, MainUI.getCurrent().getEtudiant(), etape);
                docWriter.close();
                baosPDF.close();
                //Creation de l'export
                byte[] bytes = baosPDF.toByteArray();
                return new ByteArrayInputStream(bytes);
            } catch (DocumentException e) {
                LOG.error("Erreur  la gnration du dtail des notes : DocumentException ", e);
                return null;
            } catch (IOException e) {
                LOG.error("Erreur  la gnration du dtail des notes : IOException ", e);
                return null;
            }

        }
    };

    // Cration de la ressource 
    StreamResource resource = new StreamResource(source, nomFichier);
    resource.getStream().setParameter("Content-Disposition", "attachment; filename=" + nomFichier);
    //resource.setMIMEType("application/unknow");
    resource.setMIMEType("application/force-download;charset=UTF-8");
    resource.setCacheTime(0);
    return resource;
}

From source file:it.pdfsam.console.tools.CmdParser.java

License:Open Source License

/**
 * @param encAlg encryption algorithm/*ww w  .j a v a  2 s .c o m*/
 * @return The permissions map based on the chosen encryption
 */
private HashMap getPermissionMap(String encAlg) {
    HashMap retMap = new HashMap();
    if (encAlg.equals(CmdParser.E_AES_128) || encAlg.equals(CmdParser.E_RC4_128)) {
        retMap.put(CmdParser.E_PRINT, new Integer(PdfWriter.AllowPrinting));
        retMap.put(CmdParser.E_MODIFY, new Integer(PdfWriter.AllowModifyContents));
        retMap.put(CmdParser.E_COPY, new Integer(PdfWriter.AllowCopy));
        retMap.put(CmdParser.E_ANNOTATION, new Integer(PdfWriter.AllowModifyAnnotations));
        retMap.put(CmdParser.E_FILL, new Integer(PdfWriter.AllowFillIn));
        retMap.put(CmdParser.E_SCREEN, new Integer(PdfWriter.AllowScreenReaders));
        retMap.put(CmdParser.E_ASSEMBLY, new Integer(PdfWriter.AllowAssembly));
        retMap.put(CmdParser.E_DPRINT, new Integer(PdfWriter.AllowDegradedPrinting));
    } else {
        retMap.put(CmdParser.E_PRINT, new Integer(PdfWriter.AllowPrinting));
        retMap.put(CmdParser.E_MODIFY, new Integer(PdfWriter.AllowModifyContents));
        retMap.put(CmdParser.E_COPY, new Integer(PdfWriter.AllowCopy));
        retMap.put(CmdParser.E_ANNOTATION, new Integer(PdfWriter.AllowModifyAnnotations));
    }
    return retMap;
}

From source file:org.areasy.common.doclet.document.Document.java

License:Open Source License

/**
 * Creates the document instance and initializes it.
 *///from   ww  w . ja  va  2s  . com
public static void initialize() throws Exception {
    // step 1: creation of a document-object
    pdfDocument = new com.lowagie.text.Document();

    float leftmargin = DefaultConfiguration.getFloat(ARG_DOC_MARGIN_LEFT, LEFT_MARGIN_WIDTH);
    float rightmargin = DefaultConfiguration.getFloat(ARG_DOC_MARGIN_RIGHT, RIGHT_MARGIN_WIDTH);
    float topmargin = DefaultConfiguration.getFloat(ARG_DOC_MARGIN_TOP, TOP_MARGIN_WIDTH);
    float bottommargin = DefaultConfiguration.getFloat(ARG_DOC_MARGIN_BOTTOM, BOTTOM_MARGIN_WIDTH);
    boolean printing = DefaultConfiguration.getBooleanConfigValue(ARG_ALLOW_PRINTING, ARG_VAL_YES);
    boolean encrypting = DefaultConfiguration.getBooleanConfigValue(ARG_ALLOW_ENCRYPTION, ARG_VAL_NO);

    // set left-, right-, top- and bottom-margins
    pdfDocument.setMargins(leftmargin, rightmargin, topmargin, bottommargin);

    // step 2:
    // we create a writer that listens to the document and directs a PDF-stream to a file
    pdfWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(Doclet.getPdfFile()));

    if (encrypting) {
        if (printing)
            pdfWriter.setEncryption(PdfWriter.STRENGTH40BITS, null, null, PdfWriter.AllowPrinting);
        else
            pdfWriter.setEncryption(PdfWriter.STRENGTH40BITS, null, null, 0);
    }

    //set document data
    pdfDocument.addAuthor(DefaultConfiguration.getConfiguration().getString(ARG_DOC_AUTHOR, ""));
    pdfDocument.addSubject(DefaultConfiguration.getConfiguration().getString(ARG_DOC_TITLE, ""));
    pdfDocument.addTitle(DefaultConfiguration.getConfiguration().getString(ARG_DOC_TITLE, ""));
}

From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void encrypt(int pageCount, PdfPageData currentPageData, EncryptPDFDocument encryptPage) {
    String p = encryptPage.getPermissions();
    int encryptionLevel = encryptPage.getEncryptionLevel();
    String userPassword = encryptPage.getUserPassword();
    String masterPassword = encryptPage.getMasterPassword();

    int permit[] = { PdfWriter.AllowPrinting, PdfWriter.AllowModifyContents, PdfWriter.AllowCopy,
            PdfWriter.AllowModifyAnnotations, PdfWriter.AllowFillIn };

    int permissions = 0;
    for (int i = 0; i < p.length(); ++i) {
        permissions |= (p.charAt(i) == '0' ? 0 : permit[i]);
    }/*from  w  ww  . java  2s.c om*/

    File tempFile = null;

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {
        PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        PdfEncryptor.encrypt(reader, new FileOutputStream(selectedFile), userPassword.getBytes(),
                masterPassword.getBytes(), permissions, encryptionLevel == 0);

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

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

License:Open Source License

/**
 * @param args the command line arguments
 *///from w  ww .  j  a  v a2  s  .co  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());
    }
}