Example usage for com.itextpdf.text.pdf PdfWriter ALLOW_COPY

List of usage examples for com.itextpdf.text.pdf PdfWriter ALLOW_COPY

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfWriter ALLOW_COPY.

Prototype

int ALLOW_COPY

To view the source code for com.itextpdf.text.pdf PdfWriter ALLOW_COPY.

Click Source Link

Document

The operation permitted when the document is opened with the user password

Usage

From source file:SignPDF.java

License:Open Source License

public static void main(String args[]) {
    try {// w  ww.j  a va2 s. c o  m

        if (args.length != 1) {
            System.err.println("usage: $0 <pdf-file>");
            System.exit(1);
        }
        src = args[0];
        dest = src + ".temp";

        rcname = System.getenv("SIGNPDFRC");
        if (rcname == null || rcname.length() == 0)
            rcname = System.getenv("HOME") + "/.signpdf";
        else
            System.out.println("using SIGNPDFRC=" + rcname);

        if (!getProperties())
            createDefaultProperties();

        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(path), keystore_password.toCharArray());
        if (alias == null || alias.length() == 0)
            alias = (String) ks.aliases().nextElement();
        Certificate[] chain = ks.getCertificateChain(alias);
        PrivateKey key = (PrivateKey) ks.getKey(alias, key_password.toCharArray());

        X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
        System.out.println("Signer ID serial     " + cert.getSerialNumber());
        System.out.println("Signer ID version    " + cert.getVersion());
        System.out.println("Signer ID issuer     " + cert.getIssuerDN());
        System.out.println("Signer ID not before " + cert.getNotBefore());
        System.out.println("Signer ID not after  " + cert.getNotAfter());

        // show days valid
        long ticks_now = new Date().getTime();
        long ticks_to = cert.getNotAfter().getTime();

        long ticks_delta = (ticks_to - ticks_now) / TICKS_PER_DAY;
        System.out.println("Certificate will expire in " + ticks_delta + " days.");

        Signature s = Signature.getInstance("SHA1withRSA");
        s.initVerify(ks.getCertificate(alias));

        try {
            cert.checkValidity();
            System.out.println("Validation check passed.");
        } catch (Exception e) {
            System.out.println("Certificate expired or invalid. Abroting.");
            System.exit(1);
        }

        PdfReader reader = new PdfReader(src);
        FileOutputStream os = new FileOutputStream(dest);
        //PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, false);
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        stamper.setEncryption(true, null, null,
                PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_SCREENREADERS | PdfWriter.ALLOW_COPY);

        HashMap<String, String> info = reader.getInfo();
        info.put("Creator", "SingPDF " + version);
        stamper.setMoreInfo(info);

        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();

        appearance.setReason(reason);
        appearance.setLocation(location);
        appearance.setContact(contact);
        appearance.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);

        /// ts + ocsp
        PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
        dic.setReason(appearance.getReason());
        dic.setLocation(appearance.getLocation());
        dic.setContact(appearance.getContact());
        dic.setDate(new PdfDate(appearance.getSignDate()));
        appearance.setCryptoDictionary(dic);

        // timestamping + ocsp

        if (tsa_url != null && tsa_url.length() > 0) {

            byte[] ocsp = null;
            TSAClient tsc = null;

            int contentEstimated = 15000;
            HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
            exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
            appearance.preClose(exc);

            InputStream data = appearance.getRangeStream();
            MessageDigest mdig = MessageDigest.getInstance("SHA1");

            byte buf[] = new byte[8192];
            int n;
            while ((n = data.read(buf)) > 0) {
                mdig.update(buf, 0, n);
            }

            if (root_cert != null && root_cert.length() > 0) {
                String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
                CertificateFactory cf = CertificateFactory.getInstance("X509");
                FileInputStream is = new FileInputStream(root_cert);
                X509Certificate root = (X509Certificate) cf.generateCertificate(is);
                ocsp = new OcspClientBouncyCastle().getEncoded((X509Certificate) chain[0], root, url);
            }

            byte hash[] = mdig.digest();
            Calendar cal = Calendar.getInstance();
            PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA1", null, false);
            byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
            sgn.update(sh, 0, sh.length);

            if (tsa_url != null && tsa_url.length() > 0) {
                tsc = new TSAClientBouncyCastle(tsa_url, tsa_login, tsa_passw);
                byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);
                if (contentEstimated + 2 < encodedSig.length)
                    throw new Exception("Not enough space");
                byte[] paddedSig = new byte[contentEstimated];
                System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
                PdfDictionary dic2 = new PdfDictionary();
                dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
                appearance.close(dic2);
            }
        }
        // ~timestamping + ocsp 

        File mysrc = new File(src);
        mysrc.delete();
        File mydest = new File(dest);
        mydest.renameTo(mysrc);

        System.exit(0);
    }

    catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:PdfEncryptApp.java

License:Open Source License

/**
 *
 *///w w  w  . j  av a2 s  . co m
public void pdf() throws JRException {
    long start = System.currentTimeMillis();
    File sourceFile = new File("build/reports/PdfEncryptReport.jrprint");

    JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile);

    File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".pdf");

    JRPdfExporter exporter = new JRPdfExporter();

    exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
    exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile));
    SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
    configuration.setEncrypted(true);
    configuration.set128BitKey(true);
    configuration.setUserPassword("jasper");
    configuration.setOwnerPassword("reports");
    configuration.setPermissions(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING);
    exporter.setConfiguration(configuration);
    exporter.exportReport();

    System.err.println("PDF creation time : " + (System.currentTimeMillis() - start));
}

From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFEncryptionActionExecuter.java

License:Apache License

/**
 * Build the permissions mask for iText/*w w w  . j  a va 2s.co  m*/
 * 
 * @param options
 * @return
 */
private int buildPermissionMask(Map<String, Object> options) {
    int permissions = 0;

    if ((Boolean) options.get(PARAM_ALLOW_PRINT)) {
        permissions = permissions | PdfWriter.ALLOW_PRINTING;
    }
    if ((Boolean) options.get(PARAM_ALLOW_COPY)) {
        permissions = permissions | PdfWriter.ALLOW_COPY;
    }
    if ((Boolean) options.get(PARAM_ALLOW_CONTENT_MODIFICATION)) {
        permissions = permissions | PdfWriter.ALLOW_MODIFY_CONTENTS;
    }
    if ((Boolean) options.get(PARAM_ALLOW_ANNOTATION_MODIFICATION)) {
        permissions = permissions | PdfWriter.ALLOW_MODIFY_ANNOTATIONS;
    }
    if ((Boolean) options.get(PARAM_ALLOW_SCREEN_READER)) {
        permissions = permissions | PdfWriter.ALLOW_SCREENREADERS;
    }
    if ((Boolean) options.get(PARAM_ALLOW_DEGRADED_PRINT)) {
        permissions = permissions | PdfWriter.ALLOW_DEGRADED_PRINTING;
    }
    if ((Boolean) options.get(PARAM_ALLOW_ASSEMBLY)) {
        permissions = permissions | PdfWriter.ALLOW_ASSEMBLY;
    }
    if ((Boolean) options.get(PARAM_ALLOW_FORM_FILL)) {
        permissions = permissions | PdfWriter.ALLOW_FILL_IN;
    }

    return permissions;
}

From source file:org.h819.commons.file.MyPDFUtils.java

/**
 *  pdf /*w  ww.  j  a v  a2s .  com*/
 *
 * @param srcPdfFile       ?
 * @param descPdfFile      
 * @param userPassword     ?? ,null ?
 * @param ownerPassword    ?? ,null ?
 * @param allowHideMenuBar ????
 * @param allowHideToolbar ??
 * @param allowPrinting    ???
 * @param allowCopy        ???
 * @throws java.io.IOException
 * @throws DocumentException
 */
public static void encryptPdf(File srcPdfFile, File descPdfFile, String userPassword, String ownerPassword,
        boolean allowHideMenuBar, boolean allowHideToolbar, boolean allowPrinting, boolean allowCopy)
        throws IOException {

    if (srcPdfFile == null || !srcPdfFile.exists())
        throw new IOException("src pdf file '" + srcPdfFile + "' does not exist.");

    byte[] userByte = null;
    byte[] ownerByte = null;

    /** User password. */
    if (userPassword != null)
        userByte = userPassword.getBytes();
    /** Owner password. */
    if (ownerPassword != null)
        ownerByte = ownerPassword.getBytes();

    try {

        PdfReader reader = getPdfReader(srcPdfFile);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(descPdfFile.getAbsoluteFile()));

        // 
        // ???? PdfWriter.setViewerPreferences   addViewerPreference
        // ? api ??? addViewerPreference ?
        // ???"|"()?, ? PdfWriter.HideWindowUI
        // ???, ??

        // ( addViewerPreference )
        stamper.getWriter().addViewerPreference(PdfName.CENTERWINDOW, PdfBoolean.PDFTRUE);
        stamper.getWriter().addViewerPreference(PdfName.DISPLAYDOCTITLE, PdfBoolean.PDFTRUE);
        stamper.getWriter().addViewerPreference(PdfName.FITWINDOW, PdfBoolean.PDFTRUE);
        // writer.addViewerPreference(PdfName.HIDEWINDOWUI,
        // PdfBoolean.PDFTRUE);

        if (!allowHideToolbar)
            stamper.getWriter().addViewerPreference(PdfName.HIDETOOLBAR, PdfBoolean.PDFTRUE);

        if (!allowHideMenuBar)
            stamper.getWriter().addViewerPreference(PdfName.HIDEMENUBAR, PdfBoolean.PDFTRUE);

        //  allow 
        if (allowPrinting && allowCopy)
            stamper.setEncryption(userByte, ownerByte, PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY, true);

        else if (allowPrinting)
            stamper.setEncryption(userByte, ownerByte, PdfWriter.ALLOW_PRINTING, true);

        else if (allowCopy)
            stamper.setEncryption(userByte, ownerByte, PdfWriter.ALLOW_COPY, true);

        else
            stamper.setEncryption(userByte, ownerByte, 0, true);

        stamper.close();
        reader.close();

        logger.info(srcPdfFile.getAbsoluteFile() + " encrypt finished.");

    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.h819.commons.file.MyPDFUtilss.java

/**
 *  pdf /*w  ww . j a va  2  s .  c  o m*/
 *
 * @param srcPdfFile        ?
 * @param descPdfFile       
 * @param userPassword      ?? ,null ?
 * @param ownerPassword     ?? ,null ?
 * @param allow_HideMenubar ????
 * @param allow_HideToolbar ??
 * @param allow_printing    ???
 * @param allow_copy        ???
 * @throws java.io.IOException
 * @throws DocumentException
 */
public static void encryptPdf(File srcPdfFile, File descPdfFile, String userPassword, String ownerPassword,
        boolean allow_HideMenubar, boolean allow_HideToolbar, boolean allow_printing, boolean allow_copy)
        throws IOException {

    if (srcPdfFile == null || !srcPdfFile.exists())
        throw new IOException("src pdf file '" + srcPdfFile + "' does not exsit.");

    byte[] USER = null;
    byte[] OWNER = null;

    /** User password. */
    if (userPassword != null)
        USER = userPassword.getBytes();
    /** Owner password. */
    if (ownerPassword != null)
        OWNER = ownerPassword.getBytes();

    try {

        PdfReader reader = getPdfReader(srcPdfFile);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(descPdfFile.getAbsoluteFile()));

        // 
        // ???? PdfWriter.setViewerPreferences   addViewerPreference
        // ? api ??? addViewerPreference ?
        // ???"|"()?, ? PdfWriter.HideWindowUI
        // ???, ??

        // ( addViewerPreference )
        stamper.getWriter().addViewerPreference(PdfName.CENTERWINDOW, PdfBoolean.PDFTRUE);
        stamper.getWriter().addViewerPreference(PdfName.DISPLAYDOCTITLE, PdfBoolean.PDFTRUE);
        stamper.getWriter().addViewerPreference(PdfName.FITWINDOW, PdfBoolean.PDFTRUE);
        // writer.addViewerPreference(PdfName.HIDEWINDOWUI,
        // PdfBoolean.PDFTRUE);

        if (!allow_HideToolbar)
            stamper.getWriter().addViewerPreference(PdfName.HIDETOOLBAR, PdfBoolean.PDFTRUE);

        if (!allow_HideMenubar)
            stamper.getWriter().addViewerPreference(PdfName.HIDEMENUBAR, PdfBoolean.PDFTRUE);

        //  allow 
        if (allow_printing && allow_copy)
            stamper.setEncryption(USER, OWNER, PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY, true);

        else if (allow_printing)
            stamper.setEncryption(USER, OWNER, PdfWriter.ALLOW_PRINTING, true);

        else if (allow_copy)
            stamper.setEncryption(USER, OWNER, PdfWriter.ALLOW_COPY, true);

        else
            stamper.setEncryption(USER, OWNER, 0, true);

        stamper.close();

        logger.info(srcPdfFile.getAbsoluteFile() + " encrypt finished.");

    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.la3.pdfunlock.PdfUnlock.java

License:BSD License

private void launch(String[] args) throws Exception {
    parseOptions(args);/*ww  w  . j av  a 2  s. co  m*/

    System.err.println("Unlocking " + lockedFile + " to " + unlockedFile);

    PdfReader reader;
    if (password == null) {
        reader = new PdfReader(lockedFile);
    } else {
        reader = new PdfReader(lockedFile, password.getBytes());
    }
    PdfEncryptor.encrypt(reader, new FileOutputStream(unlockedFile), null, null,
            PdfWriter.ALLOW_ASSEMBLY | PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_DEGRADED_PRINTING
                    | PdfWriter.ALLOW_FILL_IN | PdfWriter.ALLOW_MODIFY_ANNOTATIONS
                    | PdfWriter.ALLOW_MODIFY_CONTENTS | PdfWriter.ALLOW_PRINTING
                    | PdfWriter.ALLOW_SCREENREADERS,
            false);

    System.err.println("PDF Unlocked successfully!");
    System.exit(0);
}