Aspose Demos > Java Components > Aspose.Pdf.Kit for Java > Java > Adhere Text/Image to PDF

Adhere Text/Image to PDF - Aspose.Pdf.Kit

This demo Adheres Image and Text, to the input Pdf document, based over users selection. Using AddText method in PdfFileMend class of Aspose.Pdf.Kit component, developers can adhere formatted text to any page of the PDF document, at any specified location. Using AddImage it also enables developers to adhere image (in Jpg, Gif or Png formats) at any specified location in a specified page number of the PDF document.

For more information, on how to Adhere Text, please visit Adhere Text.
For more information, on how to Adhere Image, please visit Adhere Image.

Click Execute Demo to see how demo takes inpurt PDF file and adds text and an image , sending resulting document to user for review.

Coordinates of theimage Coordinates of the Where to apply
Coordinates Value
Lower Left X
Lower Left Y
Upper Right X
Upper Right Y
Coordinates Value
Lower Left X
Lower Left Y
Upper Right X
Upper Right Y

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

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 Adhere extends BaseDemo implements Serializable 
{
    // Default Constructor
    public Adhere() {
        _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));
    }
   
    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 _imgleftx = 100;
    public Integer getImgleftx() {
        return _imgleftx;
    }
    public void setImgleftx(Integer v) {
        _imgleftx = v;
    }

    private Integer _imglefty = 100;
    public Integer getImglefty() {
        return _imglefty;
    }
    public void setImglefty(Integer v) {
        _imglefty = v;
    }

    private Integer _imgrightx = 150;
    public Integer getImgrightx() {
        return _imgrightx;
    }
    public void setImgrightx(Integer v) {
        _imgrightx = v;
    }

    private Integer _imgrighty = 150;
    public Integer getImgrighty() {
        return _imgrighty;
    }
    public void setImgrighty(Integer v) {
        _imgrighty = v;
    }

    private Integer _textleftx = 200;
    public Integer getTextleftx() {
        return _textleftx;
    }
    public void setTextleftx(Integer v) {
        _textleftx = v;
    }

    private Integer _textlefty = 200;
    public Integer getTextlefty() {
        return _textlefty;
    }
    public void setTextlefty(Integer v) {
        _textlefty = v;
    }

    private Integer _textrightx = 400;
    public Integer getTextrightx() {
        return _textrightx;
    }
    public void setTextrightx(Integer v) {
        _textrightx = v;
    }

    private Integer _textrighty = 240;
    public Integer getTextrighty() {
        return _textrighty;
    }
    public void setTextrighty(Integer v) {
        _textrighty = v;
    }

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

        try
        {
            String path = "/resources/";

           int[] pageNumbs = new int[getPages().size()];
           for (int p = 0; p<getPages().size();p++){
                pageNumbs[p]=Integer.parseInt(_pages.get(p).toString());
           }

            InputStream inPdfStream = getFile(request, path + "Aspose.Pdf.pdf");
            InputStream inImgStream = getFile(request, path + "imgLogoPDFKit.gif");

            ByteArrayOutputStream output = new ByteArrayOutputStream();

            PdfFileMend mendor = new PdfFileMend(inPdfStream, output);
            mendor.addImage(inImgStream, pageNumbs,
                getImgleftx().floatValue(),
                getImglefty().floatValue(),
                getImgrightx().floatValue(),
                getImgrighty().floatValue());

            mendor.addText(
                new FormattedText(
                        getMessage(),
                       new FontColor(180, 0, 0), 
                       FontStyle.TimesRoman, 
                       EncodingType.Winansi, false, 40),
                pageNumbs,
                getTextleftx().floatValue(),
                getTextlefty().floatValue(),
                getTextrightx().floatValue(),
                getTextrighty().floatValue());
            mendor.close();
            setResponse(FILE_NAME, output);

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

<!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 File Mend - 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;Adhere Text/Image 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> Adheres</b> Image and Text, to the input Pdf document, based over users selection. Using <b> AddText </b> method in <a href="http://www.aspose.com/documentation/java-components/aspose.pdf.kit-for-java/com/aspose/pdf/kit/pdffilemend.html"> PdfFileMend </a> class of Aspose.Pdf.Kit component, developers can adhere formatted text to any page of the PDF document, at any specified location. Using <b> AddImage </b> it also enables developers to adhere image (in Jpg, Gif or Png formats) at any specified location in a specified page number of the PDF document.
     
<br/><br/>
For more information, on how to Adhere Text, please visit <a href="http://www.aspose.com/documentation/java-components/aspose.pdf.kit-for-java/adhere-text.html"> Adhere Text.</a> 
<br/>
For more information, on how to Adhere Image, please visit <a href="http://www.aspose.com/documentation/java-components/aspose.pdf.kit-for-java/adhere-image.html"> Adhere Image.</a> 

<br/><br/>Click <b> Execute Demo </b> to see how demo takes <a href="../resources/Aspose.Pdf.Kit.pdf"> inpurt PDF file </a> 
        and adds text and an <a href="../resources/imgLogoPDFKit.jpg"> image </a>, sending
        resulting document to user for review.
        </p>

        <table cellspacing="0" cellpadding="0" border="0" width="90%" align="center">
        <tr>
            <th>
                Coordinates of the <a href="../resources/imgLogoPDFKit.gif">image</a>
            </th>
            <th>
                Coordinates of the &nbsp;
                <h:inputText id="text" value="#{adhere.message}" />
                <h:message for="text" />
            </th>
            <th>
                Where to apply
            </th>
        </tr>
        <tr>
            <td style="width:40%">
            <table align="center" cellspacing="0" cellpadding="2" border="1px" width="90%">
                <tr>
                    <th scope="col" width="96px" nowrap="true">Coordinates</th>
                    <th scope="col" width="100%">Value</th>
                </tr>
                <tr>
                    <td><em><b>Lower Left X</b></em></td>
                    <td>
                        <h:message for="lowleftx2" />
                        <h:inputText id="lowleftx2" value="#{adhere.imgleftx}" style="width:90%" />
                    </td>
                </tr>
                <tr>
                    <td><em><b>Lower Left Y</b></em></td>
                    <td>
                        <h:message for="lowlefty2" />
                        <h:inputText id="lowlefty2" value="#{adhere.imglefty}" style="width:90%"  />
                    </td>
                </tr>
                <tr>
                    <td><em><b>Upper Right X</b></em></td>
                    <td>
                        <h:message for="uprightx2" />
                        <h:inputText id="uprightx2" value="#{adhere.imgrightx}" style="width:90%"  />
                    </td>
                </tr>
                <tr>
                    <td><em><b>Upper Right Y</b></em></td>
                    <td>
                        <h:message for="uprighty2" />
                        <h:inputText id="uprighty2" value="#{adhere.imgrighty}" style="width:90%"  />
                    </td>
                </tr>
            </table>
        </td>
        <td style="width:40%">
            <table align="center" cellspacing="0" cellpadding="2" border="1px" width="90%">
                <tr>
                    <th scope="col" width="96px" nowrap="true">Coordinates</th>
                    <th scope="col" width="100%">Value</th>
                </tr>
                <tr>
                    <td><em><b>Lower Left X</b></em></td>
                    <td>
                        <h:message for="lowleftx1" />
                        <h:inputText id="lowleftx1" value="#{adhere.textleftx}" style="width:90%"  />
                    </td>
                </tr>
                <tr>
                    <td><em><b>Lower Left Y</b></em></td>
                    <td>
                        <h:message for="lowlefty1" />
                        <h:inputText id="lowlefty1" value="#{adhere.textlefty}" style="width:90%"  />
                    </td>
                </tr>
                <tr>
                    <td><em><b>Upper Right X</b></em></td>
                    <td>
                        <h:message for="uprightx1" />
                        <h:inputText id="uprightx1" value="#{adhere.textrightx}" style="width:90%"  />
                    </td>
                </tr>
                <tr>
                    <td><em><b>Upper Right Y</b></em></td>
                    <td>
                        <h:message for="uprighty1" />
                        <h:inputText id="uprighty1" value="#{adhere.textrighty}" style="width:90%"  />
                    </td>
                </tr>
            </table>
        </td>
        <td>
            <h:selectManyCheckbox id="pageselector" layout="pageDirection"
                immediate="true"
                value="#{adhere.pages}" >
              <f:selectItem id="page1" itemLabel="at 1st page" itemValue="1" />
              <f:selectItem id="page2" itemLabel="at 2nd page" itemValue="2" />
              <f:selectItem id="page3" itemLabel="at 3rd page" itemValue="3" />
              <f:selectItem id="page4" itemLabel="at 4th page" itemValue="4" />
              <f:selectItem id="page5" itemLabel="at 5th page" itemValue="5" />
            </h:selectManyCheckbox>
        </td>
    </tr>
    </table>
        <p>
            <h:commandButton id="generate" 
                action="#{adhere.generate}"
                value="Execute Demo"> 
            </h:commandButton>

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