Aspose Demos > Java Components > Aspose.Pdf.Kit for Java > Java > Stamp Watermark to PDF

Stamp Watermark to PDF - Aspose.Pdf.Kit

This demo Stamps Image or Text, over the input Pdf document, based over users selection. Using AddStamp method in PdfFileStamp class of Aspose.Pdf.Kit component, developers can add watermark in the form of image (Jpg, Gif and Png) on each page/selected pages of Pdf file, at any specified location. Not even images, PdfFileStamp provides the flexibility to add Formatted text String as Logo over each page/selected pages of the PDF document, at any specified location.
Using PdfFileStamp, image can also be set as background to the Pdf document. Set the value for IsBackground property toTrue before calling AddStamp.

For more information, on how to add Text Logo, please visit Add Logo.
For more information, on how to set watermark, please visit Add Watermark.
For more information, on how to set background, please visit Add Background.

Choose text, message size and placement and/or image placement details and click Execute Demo to see how demo takesinput PDF file stamping it with text and/orimage and sends the resulting document to user for review.

An image and a text are added as watermark, logo or background on the inputpdf here,

Page range (Be sure to select at least one page in order to see the demo in effect )

Rotation

Origin X:
Origin Y:

Using original size Specified Width
px
px

FontSize

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 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

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;

public class StampWatermark extends BaseDemo implements Serializable 
{
    private ArrayList _pages = new ArrayList();
    public ArrayList getPages() {
        return _pages;
    }
    public void setPages(ArrayList v) {
        _pages = v;
    }

    private String _message = "Hello World!";
    public String getMessage() {
        return _message;
    }
    public void setMessage(String v) {
        _message = v;
    }

    private Integer _rotation = 15;
    public Integer getRotation() {
        return _rotation;
    }
    public void setRotation(Integer v) {
        _rotation = v;
    }

    private Integer _originx = 150;
    public Integer getOriginx() {
        return _originx;
    }
    public void setOriginx(Integer v) {
        _originx = v;
    }

    private Integer _originy = 200;
    public Integer getOriginy() {
        return _originy;
    }
    public void setOriginy(Integer v) {
        _originy = v;
    }


    private Integer _width = 100;
    public Integer getWidth() {
        return _width;
    }
    public void setWidth(Integer v) {
        _width = v;
    }

    private Integer _height = 100;
    public Integer getHeight() {
        return _height;
    }
    public void setHeight(Integer v) {
        _height = v;
    }

    private Integer _fontsize = 30;
    public Integer getFontsize() {
        return _fontsize;
    }
    public void setFontsize(Integer v) {
        _fontsize = v;
    }

    private Boolean _useOriginalSize = false;
    public Boolean getUseoriginalsize() {
        return _useOriginalSize;
    }
    public void setUseoriginalsize(Boolean v) {
        _useOriginalSize = v;
    }

    private Integer _type = 1;
    public Integer getType() {
        return _type;
    }
    public void setType(Integer v) {
        _type = v;
    }

    private Integer _source = 3;
    public Integer getSource() {
        return _source;
    }
    public void setSource(Integer v) {
        _source = v;
    }

    // Default Constructor
    public StampWatermark() {
        _pages.add(new Integer(1));
        _pages.add(new Integer(2));
        _pages.add(new Integer(3));
        _pages.add(new Integer(4));
        _pages.add(new Integer(5));
    }
   
    /**
     * 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");

            Stamp logoStamp = new Stamp();
            Stamp stamp = new Stamp();

            switch (getSource())
            {
                // Image
                case 3:
                {
                    stamp.bindImage(getFileName(request, path + "butterfly.jpg"));

                    //Is background
                    if (!getUseoriginalsize()) {
                        stamp.setImageSize(getWidth(), getHeight());
                    }

                    if (2==getType())
                    {
                        stamp.isBackground(true);
                        stamp.setOrigin(getOriginx(), getOriginy());
                    } else {
                        stamp.isBackground(false);
                        stamp.setRotation(getRotation());
                    }
                } break;

                // Text
                case 4:
                {
                    logoStamp.bindLogo(
                        new FormattedText(
                            getMessage(),
                            new FontColor(180, 0, 0), 
                            FontStyle.TimesRoman, 
                            EncodingType.Winansi, false,
                            getFontsize()));
                } break;
            }

            if (_pages.size()<1)
            {
                System.out.println("No pages defined");
                return false;
            }
            int[] pageNumbs = new int[_pages.size()];
            for (int p = 0; p<_pages.size();p++){
                pageNumbs[p]=Integer.parseInt(_pages.get(p).toString());
            }
            stamp.setPages(pageNumbs);
            logoStamp.setPages(pageNumbs);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PdfFileStamp fileStamp = new PdfFileStamp(input,outputStream);
            fileStamp.addStamp(logoStamp);
            fileStamp.addStamp(stamp);
            fileStamp.close();

            setResponse(FILE_NAME, outputStream);

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

        return false;
    }

     public void action(ActionEvent event)
     {
        try
        {
            System.out.println("Got action");
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

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 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

<!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">
        Stamp and Watermark - 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;Stamp Watermark to PDF - 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 <b> Stamps </b> Image or Text, over the input Pdf document, based over users selection.

 Using <b> AddStamp </b> method in <a href="http://www.aspose.com/documentation/java-components/aspose.pdf.kit-for-java/com/aspose/pdf/kit/pdffilestamp.html"> PdfFileStamp </a> class of Aspose.Pdf.Kit component, developers can add watermark in the form of image (Jpg, Gif and Png) on each page/selected pages of Pdf file, at any specified location. Not even images, PdfFileStamp provides the flexibility to add Formatted text String as Logo over each page/selected pages of the PDF document, at any specified location.
<br/>
Using PdfFileStamp, image can also be set as background to the Pdf document. Set the value for <b> IsBackground </b> property to <b>True </b> before calling AddStamp.

<br/><br/>
For more information, on how to add Text Logo, please visit <a href="http://www.aspose.com/documentation/java-components/aspose.pdf.kit-for-java/add-logo.html"> Add Logo.</a> 
<br/>
For more information, on how to set watermark, please visit <a href="http://www.aspose.com/documentation/java-components/aspose.pdf.kit-for-java/add-watermark.html"> Add Watermark. </a> 

<br/>
For more information, on how to set background, please visit <a href="http://www.aspose.com/documentation/java-components/aspose.pdf.kit-for-java/add-background.html"> Add Background.</a>


<br/><br/>      Choose text, message size and placement and/or image placement details and click
        <b> Execute Demo </b> to see how demo takes  <a href="../resources/Aspose.Pdf.Kit.pdf">input PDF file</a> 
        stamping it with text and/or <a href="../resources/butterfly.jpg">image</a>
        and sends the resulting document to user for review.
        </p>

        <p>An <a href="../resources/butterfly.jpg" style="height:16px;width:40px;"> image</a> 
        and a text are added as watermark, logo or background on the input <a href="./resources/Aspose.Pdf.Kit.pdf">pdf</a> here,</p>

            <p>
            Page range (<b>Be sure to select at least one page in order to see the demo in effect</b>)
            <h:selectManyCheckbox
                id="checkpages" 
                value="#{stamp.pages}"> 
                <f:selectItem id="into1" itemValue="1"  itemLabel="Page 1" />
                <f:selectItem id="into2" itemValue="2"  itemLabel="Page 2" />
                <f:selectItem id="into3" itemValue="3"  itemLabel="Page 3" />
                <f:selectItem id="into4" itemValue="4"  itemLabel="Page 4" />
                <f:selectItem id="into5" itemValue="5"  itemLabel="Page 5" />
            </h:selectManyCheckbox>
                <h:message for="checkpages" />
            </p>

            <h:selectOneRadio id="type" value="#{stamp.type}" 
                immediate="true"
                layout="pageDirection"> 
                <f:selectItem itemValue="1" itemLabel="Add a watermark(layed on top of page)" />
                <f:selectItem itemValue="2" itemLabel="Add a background(layed behind page)" />
            </h:selectOneRadio>
                <h:message for="type" />

            <h:selectOneRadio id="source" value="#{stamp.source}" 
                layout="pageDirection"> 
                <f:selectItem itemValue="3" itemLabel="From the previewed image" />
                <f:selectItem itemValue="4" itemLabel="From text" />
            </h:selectOneRadio>
                <h:message for="source" />

            <p>
                Rotation
                <h:message for="rotation" />
                <h:inputText id="rotation" value="#{stamp.rotation}" />
            </p>

            <p>
                <h:message for="originx" />
                Origin X:&nbsp;<h:inputText id="originx" value="#{stamp.originx}" /><br/>

                <h:message for="originy" />
                Origin Y:&nbsp;<h:inputText id="originy" value="#{stamp.originy}" />
            </p>
            
            <img src="./resources/butterfly.jpg" style="border-width:2px;border-style:Groove;height:136px;width:216px;" />
            <p>
                Using original size
                <h:selectBooleanCheckbox
                    id="useorig"
                    title="Using original size"
                    value="#{stamp.useoriginalsize}" />
                <h:message for="useorig" />

                Specified Width<br/>
                <h:message for="width" />
                <h:inputText id="width" value="#{stamp.width}" /> px<br/>
                <h:message for="height" />
                <h:inputText id="height" value="#{stamp.height}" /> px<br/>
            </p>

            <p>
                FontSize
                <h:message for="fontsize" />
                <h:inputText id="fontsize" value="#{stamp.fontsize}" />
            </p>

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

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