Aspose Demos > Java Components > Aspose.Pdf.Kit for Java > Java > Set PDF Security

Set PDF Security - Aspose.Pdf.Kit

This demo applies Security settings over input Pdf document, based over users selection. Using EncryptFile method in PdfFileSecurity class of Aspose.Pdf.Kit component, developers can make PDF documents secured, by simply encrypting the documents.You can also set privileges on a PDF document without applying encryption. By Using SetPrivilege method in PdfFileSecurity class of Aspose.Pdf.Kit component, several privileges can be applied on a PDF document.

Fore more information, please visitImplementing Security.

Check security options and click Execute Demo to see how demo takesinput PDF file , applies security options and sends the resulting document to user for review.

You can allow

User Password:

Owner Password:

JAVA

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

package com.aspose.pdf.kit.demos.jsf;

import java.io.Serializable;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.aspose.pdf.kit.*;

import javax.faces.context.FacesContext;
import javax.faces.event.*;
import javax.faces.component.UIComponent;

// We parse pdf privilege by name
import java.lang.reflect.*;

public class Security extends BaseDemo implements ValueChangeListener, Serializable 
{
    private int _privs = 0;

    private String _userPassword;
    public String getUser() {
        return _userPassword;
    }
    public void setUser(String v) {
        _userPassword = v;
    }

    private String _ownerPassword;
    public String getOwner() {
        return _ownerPassword;
    }
    public void setOwner(String v) {
        _ownerPassword = v;
    }

    // Default Constructor
    public Security() {
    }
   
    /**
     * Processes page selection
     *
     */
    public void processValueChange(ValueChangeEvent event) {
        FacesContext context = FacesContext.getCurrentInstance();

        Object component = event.getComponent();

        try
        {
            Field fieldlist[] = PdfPrivilege.class.getDeclaredFields();

            Object newValues = event.getNewValue();
            if (null!=newValues) {
                String[] vals = (String[])newValues;
                for (int i=0;i<vals.length;i++) 
                {
                    //System.out.println("Detecing " + vals[i]);
                    for (int j= 0; j < fieldlist.length; j++) 
                    {
                       Field fld = fieldlist[j];
                       if (fld.getName().equals(vals[i]))
                       {
                            int p = fld.getInt(null);   // null for static fields
                            _privs |= p;
                            //System.out.println(p + " (" + fld.toString() + ")");
                            break;
                       }
                    }
                }
            }
        }catch(Exception ex)
        {
            ex.printStackTrace();

        }
    }
    
    /**
     * Execute request
     *
     * @return success
     */
    public Boolean execute(HttpServletRequest request, HttpServletResponse response) {

        try
        {
            String path = "/resources/";

            //get the page numbers
            InputStream input = getFile(request, path+"Aspose.Pdf.Kit.pdf");
            
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PdfFileSecurity fileSecurity = new PdfFileSecurity(input, outputStream);
            fileSecurity.encryptFile(getUser(), getOwner(), _privs, false);
            setResponse(FILE_NAME, outputStream);

            //context.responseComplete();
            return true;
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }

        return false;
    }
}

JAVA

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

package com.aspose.pdf.kit.demos.jsf;

import java.io.Serializable;

import java.io.*;
import java.util.*;
import java.net.URL;

import javax.servlet.*;
import javax.servlet.http.*;

import java.text.SimpleDateFormat;

import javax.faces.context.FacesContext;

import com.icesoft.faces.context.ByteArrayResource;
import com.icesoft.faces.context.Resource;

import java.lang.reflect.*;

public abstract class BaseDemo
{
    // Default Constructor
    public BaseDemo() {
        initLicense(new com.aspose.pdf.kit.License());
    }

    public abstract Boolean execute(HttpServletRequest request, HttpServletResponse response);

    protected String getFileName(HttpServletRequest request, String absoluteName)
        throws java.io.FileNotFoundException
    {
        URL url = getClass().getClassLoader().getResource(absoluteName);
        if (null==url && null!=request)
        {
            String path =
                request.getRealPath(absoluteName).replace("\\", "/");

            System.err.println("Failed to load " + absoluteName);
            System.err.println("Loading file from " + path);

            return path;
        }

        String path = new File(url.getPath()).getAbsolutePath();
        //return url.toString();
        return path;
    }

    protected InputStream getFile(HttpServletRequest request, String absoluteName)
        throws java.io.FileNotFoundException
    {
        InputStream is = getClass().getClassLoader().getResourceAsStream(absoluteName);
        if (null==is && null!=request)
        {
            String path =
                request.getRealPath(absoluteName).replace("\\", "/");

            System.err.println("Failed to load " + absoluteName);
            System.err.println("Loading file from " + path);
            is = new FileInputStream(path);
        }

        return is;
    }

    public String generate() {

        FacesContext context = FacesContext.getCurrentInstance();

        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();

        try
        {
            System.out.println("BaseGenerate called for " + this.toString());

            if (execute(request, response))
            {
                //context.responseComplete();
            }


        }catch(Exception ex)
        {
            ex.printStackTrace();
        }

        return "stay";
    }

    protected final String FILE_NAME = "result.pdf";

    public Resource getGeneratedfile() {
        byte[] res = getResult();
        if (null==res || res.length<1) {
            return null;
        }
        return new ByteArrayResource(res);
    }

    private String fileName = FILE_NAME;
    public String getFilename() {
        return fileName;
    }

    public void setFilename(String v) {

        SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MMM-dd_hh_mm_ss-", Locale.US);
        String curDate = formatter.format(new Date());

        this.fileName = curDate + v;
    }

    public  byte[] getResult()
    {
        return response;
    }

    protected void setResponse(String fName, ByteArrayOutputStream out) throws IOException {
        setFilename(fName);
        response = out.toByteArray();
        out.close();
        // outputStream.write(this.response);
    }
    protected byte[] response;

    /**
     *
     * Initializes license (if demo license is available).
     * you may insert your licensing code here that would use obj's
     * setLicense based on InputStream rather than passing it on
     * to 3rd-party class.
     *
     */
    public static void initLicense(Object obj) {
        try {

            Class myclass = Class.forName("com.aspose.demos.Common");
            if (null==myclass) {
                System.out.println("initLicense not found");
                return ;
            }

            //Use reflection to list methods and invoke them
            Method[] methods = myclass.getMethods();
            Object object = myclass.newInstance();

            Class partypes[] = new Class[1];
            partypes[0] = Object.class;
           
            Method meth = myclass.getMethod("initLicense", partypes);
            if (null!=meth) {

                    System.out.println("Calling " + meth.getName());
                    Object arglist[] = new Object[1];
                    arglist[0] = obj;

                    meth.invoke(object, arglist);
            }
        } catch (ClassNotFoundException cnfe) {
            // Ignore
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

XHTML

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ice="http://www.icesoft.com/icefaces/component"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:c="http://java.sun.com/jstl/core"
      >

<ui:composition template="/WEB-INF/includes/templates/page-template.xhtml">
                        
    <ui:define name="pageTitle">
        PDF Security - Aspose.PDF Demos
    </ui:define>

    <ui:define name="page-content">
        <ui:decorate template="/WEB-INF/includes/templates/tabbed_container.xhtml">
            <ui:define name="example">

   

<table width="90%" align="center" cellspacing="0" cellpadding="0" border="0">
  <tr>
    <td width="19"><img src="../../../../Common/images/heading_lft.jpg" alt="" width="19" height="41" /></td>
    <td width="100%" class="demos-heading-bg"><h2 class="demos-heading-bg"> &nbsp;Set PDF Security - Aspose.Pdf.Kit</h2></td>
    <td width="19"><img src="../../../../Common/images/heading_rt.jpg" alt="" width="19" height="41" /></td>
  </tr>
</table>


 <p class="componentDescriptionTxt">
  This demo applies <b> Security </b> settings over input Pdf document, based over users selection.
 Using <b> EncryptFile </b> method in <a href="http://www.aspose.com/documentation/java-components/aspose.pdf.kit-for-java/com/aspose/pdf/kit/pdffilesecurity.html"> PdfFileSecurity </a> class of Aspose.Pdf.Kit component, developers can make PDF documents secured, by simply encrypting the documents.You can also set privileges on a PDF document without applying encryption. By Using <b> SetPrivilege </b> method in <a href="http://www.aspose.com/documentation/java-components/aspose.pdf.kit-for-java/com/aspose/pdf/kit/pdffilesecurity.html"> PdfFileSecurity </a> class of Aspose.Pdf.Kit component, several privileges can be applied on a PDF document.

<br/><br/>
Fore more information, please visit <a href="http://www.aspose.com/documentation/java-components/aspose.pdf.kit-for-java/implementing-security.html">Implementing Security. </a>

 <br/> <br/>    Check security options and click <b> Execute Demo </b> to see how demo takes <a href="../resources/Aspose.Pdf.Kit.pdf">input PDF file</a> 
        , applies security options and sends the resulting document to user for review.
        </p>

            You can allow
            <h:selectManyCheckbox id="secureselector" layout="pageDirection"
                immediate="true"
                valueChangeListener="#{security.processValueChange}" >
              <f:selectItem itemLabel="Copying" itemValue="Copy" />
              <f:selectItem itemLabel="Printing" itemValue="Print" />
              <f:selectItem itemLabel="Modifying content" itemValue="ModifyContents" />
              <f:selectItem itemLabel="Modifying annotation" itemValue="ModifyAnnotations" />
              <f:selectItem itemLabel="Filling Forms" itemValue="FillIn" />
              <f:selectItem itemLabel="Screening Readers" itemValue="ScreenReaders" />
              <f:selectItem itemLabel="Assemblying" itemValue="Assembly" />
              <f:selectItem itemLabel="Degraded Printing" itemValue="DegradedPrinting" />
            </h:selectManyCheckbox>
            <p>
                User Password:&nbsp;<h:inputText id="user" value="#{security.user}" />
            </p>
            <p>
                Owner Password:&nbsp;<h:inputText id="owner" value="#{security.owner}" />
            </p>

            <h:commandButton id="generate" 
                action="#{security.generate}"
                value="Execute Demo"> 
            </h:commandButton>

            <ice:outputResource id="outputResource"
                mimeType="application/pdf"
                resource="#{security.generatedfile}"
                fileName="#{security.filename}"
                shared="false" />
            </ui:define>
        </ui:decorate>
    </ui:define>
</ui:composition>
</html>