Aspose Demos > Java Components > Aspose.Words for Java > Java > Barcode

Welcome to the Aspose.Words for Java Featured Demos!

This demo shows one of the ways you can generate a sales invoice with a header, order details and a summary with Aspose.Words. In this demo you will learn how to mail merge data from multiple tables, format date and numeric fields and use merge regions to grow portions of the document.

Important : To produce Word documents, the machine to run Aspose.Words for Java does not need to have Microsoft Word and Windows installed. However, to view the contents of Word documents produced by demos, the machine to view them needs at least Microsoft Word Viewer installed. Microsoft Word Viewer can be downloaded for free.

In all of these examples no OLE automation is used, all work is performed by Aspose.Words for Java without Microsoft Word installed on the web server.

Select output format:

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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

//////////////////////////////////////////////////////////////////////////
// Copyright 2001-2011 Aspose Pty Ltd. All Rights Reserved.
//
// This file is part of Aspose.Words. The source code in this file
// is only intended as a supplement to the documentation, and is provided
// "as is", without warranty of any kind, either expressed or implied.
//////////////////////////////////////////////////////////////////////////
package com.aspose.words.demos;

import com.aspose.barcode.ImageQuality;
import com.aspose.barcode.Symbology;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.barcode.BarCodeBuilder;

import javax.faces.el.ValueBinding;
import java.awt.image.BufferedImage;
import java.lang.reflect.Field;
import java.util.Random;

/**
 * Creates and inserts a barcode with random settings into a document using Aspose.Words and Aspose.Barcode.
 */
public class BarCodeDemo extends Demo
{
    public BarCodeDemo()
    {
    }

    public Document execute() throws Exception
    {
        //Open the template document
        Document doc = new Document(getPathToTemplateDoc());

        // Create a barcode with random properties
        BarCodeBuilder barCode = CreateBarCode();

        // Fill merge fields in the document to show barcode properties
        FillProperties(doc, barCode);
        // Insert the barcode image
        InsertBarcodeImage(doc, barCode);

        return doc;
    }

        public String executeDemo() {

            // Java-added rethrow in order to avoid changing this method's signature.
            try
            {
                init("BarCodeDemo");

                // Get the output format selected by user.
                String formatType = request.getParameter("format");
                ValueBinding theBean = context.getApplication().createValueBinding("#{mycontext.outputtype}");
                if (null!=theBean)
                {
                    formatType = (String)theBean.getValue(context);
                }

                boolean openNewWindow = request.getParameter("openNewWindow") != null;
                theBean = context.getApplication().createValueBinding("#{mycontext.opennewwindow}");
                if (null!=theBean)
                {
                    openNewWindow = (Boolean)theBean.getValue(context);
                }

                Document doc = execute();

                if (null!=doc) {
                    // Once we have a document, we can save it to a file, stream or send to the client browser.
                    // We just send the document to the browser in this case.
                    sendToBrowser(doc, mDemoName, formatType, openNewWindow);
                }
            }
            catch (Exception e)
            {
                throw new RuntimeException(e);
            }

            return "";
        }

    /**
     * Called for every merge field encountered in the document.
     * We can either return some data to the mail merge engine or do something
     * else with the document. In this case we choose to modify cell formatting.
     */
    private static void FillProperties(Document doc, BarCodeBuilder barCode) throws Exception
    {
       String[] fieldNames = new String[] { "SymbologyType", "CodeText", "SupplementData",
                                                "RotationAngle", "ImageQuality" };
       Object[] fieldValues = new Object[] { GetNameOfEnumValue(Symbology.class, barCode.getSymbology()), barCode.getCodeText(), barCode.getSupplementText(),
                                                 barCode.getRotationAngle(), GetNameOfEnumValue(ImageQuality.class, barCode.getImageQuality())};

       // Execute mail merge
       doc.getMailMerge().execute(fieldNames, fieldValues);
    }

    /**
     * Inserts the barcode into the document at the specified bookmark.
     */
    private static void InsertBarcodeImage(Document doc, BarCodeBuilder barCode) throws Exception
    {
        DocumentBuilder builder = new DocumentBuilder(doc);

        // Move to the appropriate table cell
        builder.moveToBookmark("BarcodeImage");
        // Insert the barcode image
        BufferedImage image = (BufferedImage)barCode.generateBarCodeImage();
        builder.insertImage(image);
    }

    /**
     * Generates a barcode with random settings.
     */
     private BarCodeBuilder CreateBarCode()
    {
        // Instantiate a LinearBarCode object
        BarCodeBuilder barCode = new BarCodeBuilder();

        // Call necessary methods each of which returns a random value for the
        // corresponding barcode property
        barCode.setSymbology(GetRandomSymbology());
        barCode.setCodeText(GetRandomCodeText(barCode));
        barCode.setSupplementText(GetRandomSupplementData());
        barCode.setImageQuality((int)GetRandomImageQualityMode());
        barCode.setRotationAngle(GetRandomRotationAngle());

        return barCode;
    }

    /**
     * Returns a random Symbology enumeration.
     */
    private long GetRandomSymbology()
    {
        return GetRandomEnumValue(Symbology.class);
    }

    /**
     * Returns a random code text string.
     */
    private String GetRandomCodeText(BarCodeBuilder barCode)
    {
        // Some barcode standard specifications have certain restrictions of the
        // number of digits in the code
        switch ((int)barCode.getSymbology())
        {
           case (int)Symbology.EAN13:
              return GetRandomDigits(12);
           case (int)Symbology.EAN8:
              return GetRandomDigits(7);
           case (int)Symbology.UPCA:
           case (int)Symbology.UPCE:
              return GetRandomDigits(10);
           default:
              return GetRandomDigits(12);
        }
    }

    /**
     * Returns a random supplement data string.
     */
    private String GetRandomSupplementData()
    {
        // Random number between 10,000 and 100,000
        return String.valueOf((rnd.nextInt(90000)+10000));
    }

    /**
     * Returns a random angle between 0 and 359 degrees.
     */
    private int GetRandomRotationAngle()
    {
        // Find next random angle.
        return rnd.nextInt(360);
    }

    /**
     * Gets a random ImageQuality enumeration.
     */
    private long GetRandomImageQualityMode()
    {
        return GetRandomEnumValue(ImageQuality.class);
    }

    /**
     * Aspose.Barcode for Java stores enumerations in classes. This method random enumeration value stored within
     * the specified class. Not all of these classes have built-in methods to retrieve the name and value of the internal
     * enumerations so we will extract them using reflection instead.
     */
    private long GetRandomEnumValue(Class enumType)
    {
        try{
            // Get all fields of this class.
            Field[] fields = enumType.getFields();

            // Java implements nextInt similarly to .NET, the upper value is exclusive so the result will always be one less
            // than the passed length.
            int num = rnd.nextInt(fields.length);

            // Get a random enumeration.
            Field field = fields[num];

            // Retrieve the value from a new instance of this class.
            Object enumObject = enumType.newInstance();

            // Return the value.
            return field.getLong(enumObject);
            }

            catch(Exception e)
            {
              return 0;
            }

        }

        /**
        * Get the name of the enumeration from the specified class. The name to retrieve is which enum matches the passed value.
        */
        private static String GetNameOfEnumValue(Class enumType, long value)
        {
            try{
                // Get all fields in the class.
                Field[] fields = enumType.getFields();

                /// Create a new instance of the enumeration class.
                Object enumObject = enumType.newInstance();

                // Loop through all fields and find the enumeration whose value matches.
                for(Field field : fields)
                {
                    if(field.getLong(enumObject) == value)
                        return field.getName();
                }

                // Couldn't find value, return empty string.
                return "";
            }

            catch(Exception e)
            {
               return "";
            }
        }

        /**
        * Gets a random string digits of specified length.
        */
        private String GetRandomDigits(int digits)
        {
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < digits; i++)
                builder.append(rnd.nextInt(10));

            return builder.toString();
        }

        // Used to create random settings for the barcode.
        private Random rnd = new Random();
}

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

//////////////////////////////////////////////////////////////////////////
// Copyright 2001-2011 Aspose Pty Ltd. All Rights Reserved.
//
// This file is part of Aspose.Words. The source code in this file
// is only intended as a supplement to the documentation, and is provided
// "as is", without warranty of any kind, either expressed or implied.
//////////////////////////////////////////////////////////////////////////
package com.aspose.words.demos;

import java.io.Serializable;

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

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.faces.event.ActionEvent;

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

public class AsposeContext implements Serializable
{
    private String _outputType = "DOC";
    public String getOutputtype() {
        return _outputType;
    }
    public void setOutputtype(String v) {
        _outputType = v;
        if("DOC".equals(_outputType))
        {
            _mimeType = "application/msword";
        }
        else if("DOCX".equals(_outputType))
        {
            _mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        }
        else if("HTML".equals(_outputType))
        {
            _mimeType = "text/html";
        }
        else if("TXT".equals(_outputType))
        {
            _mimeType = "text/plain";
        }
        else if("ODT".equals(_outputType))
        {
            _mimeType = "application/vnd.oasis.opendocument.text";
        }
        else if("PDF".equals(_outputType))
        {
            _mimeType = "application/pdf";
        }else
        {
            _mimeType = "application/msword";
        }
    }

    private String _mimeType = "application/msword";
    public String getMimetype() {
        return _mimeType;
    }

    private Boolean _openNew = false;
    public Boolean getOpennewwindow() {
        return _openNew;
    }
    public void setOpennewwindow(Boolean v) {
        _openNew = v;
    }

    // Default Constructor
    public AsposeContext() {
    }
}

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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492

//////////////////////////////////////////////////////////////////////////
// Copyright 2001-2011 Aspose Pty Ltd. All Rights Reserved.
//
// This file is part of Aspose.Words. The source code in this file
// is only intended as a supplement to the documentation, and is provided
// "as is", without warranty of any kind, either expressed or implied.
//////////////////////////////////////////////////////////////////////////
package com.aspose.words.demos;

import com.aspose.words.*;

import java.io.*;
import java.net.URI;
import java.net.URL;
import java.sql.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.faces.context.FacesContext;

///////////////////////
import java.text.SimpleDateFormat;
import com.icesoft.faces.context.ByteArrayResource;
import com.icesoft.faces.context.Resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.lang.reflect.*;

/**
 * Base class for Aspose.Words.Demos classes that execute specific demos.
 */
public abstract class Demo
{
    /**
     * Called before launching any concrete demo-classes.
     * We need application path so we can find the database and template documents.
     */
    private void initDemo() throws Exception
    {
        // Calculate common project dirs and files used by all demos.
        mProjectDir = getProjectDir();
        File baseDir = mProjectDir.getParentFile();
        mDocumentsDir = new File(baseDir, "Documents");
        mGeneratedDir = new File(mProjectDir, "generated");
        mDatabaseDir = new File(baseDir, "Database");
        mDatabase = new File(mDatabaseDir, "Northwind.mdb");
        mResultSetCollection = new ArrayList();

        // Check all paths exist.
        checkExistense();

        // Clear all files from the output directory.
        if (mGeneratedDir.exists())
        {
            File[] files = mGeneratedDir.listFiles();
            for (int i = 0; i < files.length; i++)
                files[i].delete();
        }
        else
        {
            mGeneratedDir.mkdir();
        }

        // Create a connection to the database.
        createConnection();

        // Construct paths to where images are saved during HTML export.
        mHtmlImagesDir = new File(request.getSession().getServletContext().getRealPath("../"), "aspose.words\\Documents");
        mHtmlImageAliasPath = new URI(request.getScheme(), null, request.getServerName(), SERVER_PORT, "/aspose.words/Documents/", null, null);

        // Ensure that the folder used to store images when exporting to HTML exists.
        if(!mHtmlImagesDir.exists())
        {
           // Use mkdirs to create any necessary parent directories as well.
           mHtmlImagesDir.mkdirs();
        }

        // Check through the images folder for any files that are old and are to be removed.
        for(File file : mHtmlImagesDir.listFiles())
        {
            // Find the extension of the file name if it has one.
            String ext = null;
            String s = file.getName();
            int i = s.lastIndexOf('.');

            if (> 0 &&  i < s.length() - 1) {
                ext = s.substring(i+1).toLowerCase();
            }

            // Only check if the file is to be removed if it is an PNG image file.
            if(ext != null && ext.equals("png"))
            {
                // The time and date the file was modified.
                Date fileDate = new Date(file.lastModified());
                // The current time and date.
                Date currentDate = new Date();

                // Get milliseconds of each time and subtract them.
                long diff = currentDate.getTime() - fileDate.getTime();
                // Calculate the difference in hours.
                int hoursDiff = (int)(diff / (1000 * 60 * 60));

                // If this png file is more than a day old then it can be removed.
                if(hoursDiff > 24)
                   file.delete();
            }
        }

        initLicense(new com.aspose.words.License());
        initLicense(new com.aspose.cells.License());
        initLicense(new com.aspose.barcode.License());

        isInitialized = true;
    }

    /**
     * Calculates the root dir of the demo project.
     *
     * The demo project dir is "demos/Aspose.Words.Demos".
     * It is proposed that compiled classes will be placed by compiler into "classes" subdir
     * of the project dir, so Demo.class (this) will be placed into
     * "demos/Aspose.Words.Demos/classes/com/aspose/words/demos/Demo.class".
     */
    private static File getProjectDir()
    {
        URL url = Demo.class.getResource("Demo.class");

        String path = new File(url.getPath()).getAbsolutePath();
        String subPath = "\\classes\\com\\aspose\\words\\demos\\Demo.class";

        return new File(path.substring(0, path.length() - subPath.length()));
    }

    /**
     * Note: The wrong project path will generally result in the wrong path to dependent directories and the
     * generated files.
     */
    private static void checkExistense()
    {
        if (!mProjectDir.exists())
            throw new IllegalArgumentException("Can't find the Project dir: " + mProjectDir.getAbsolutePath());

        if (!mDocumentsDir.exists())
            throw new IllegalArgumentException("Can't find the template documents dir: " + mDocumentsDir.getAbsolutePath());

        if (!mDatabaseDir.exists())
            throw new IllegalArgumentException("Can't find the database dir: " + mDatabaseDir.getAbsolutePath());

        if (!mDatabase.exists())
            throw new IllegalArgumentException("Can't find the database file: " + mDatabase.getAbsolutePath());
    }


    /**
     * Utility function that creates a database statement
     */
    public static Statement createStatement() throws Exception
    {
        return mConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    }

    /**
     * Cleans up and closes all ResultSets and Statements used. Then closes the connection to the database.
     */
    public static void closeResources() throws Exception
    {
        // Iterate through each ResultSet used by the demos. Close the result set and
        // parent statement.
        for(ResultSet rs : (Iterable<ResultSet>) mResultSetCollection)
        {
            if(rs != null)
            {
                Statement statement = rs.getStatement();

                rs.close();

                if(statement != null)
                    statement.close();
            }
        }

        mConnection.close();
    }

    /**
     * Called by concrete demo-class. Calculates paths to files used solely by this concrete demo.
     */
    protected void init(String demoName) throws Exception
    {
        context = FacesContext.getCurrentInstance();
        request = (HttpServletRequest) context.getExternalContext().getRequest();
        response = (HttpServletResponse) context.getExternalContext().getResponse();

        if(!isInitialized)
            initDemo();

        // Calculate files used solely by this concrete demo.
        mDemoName = demoName;
        File docTemplate = new File(mDocumentsDir, mDemoName + ".doc");
        File docxTemplate = new File(mDocumentsDir, mDemoName + ".docx");

        // Check to see if a DOC or DOCX template is used else throw an exception if no template
        // could be found.
        if (docTemplate.exists())
            mTemplate = docTemplate;
        else if (docxTemplate.exists())
            mTemplate = docxTemplate;
        else
            throw new IllegalArgumentException("Can't find the template document file for demo: " + demoName);
    }

    /**
     * Utility function that creates a connection to the Database.
     */
    public static void createConnection() throws Exception
    {
        //  Load a DB driver that is used by the demos
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        // Compose connection string.
        String connectionString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};" +
                                  "DBQ=" + mDatabase + ";UID=Admin";
        // DSN-less DB connection.
        mConnection = DriverManager.getConnection(connectionString);
    }

    /**
     * Executes the demo and returns a generated document. Implement in the derived classes.
     */
    public abstract Document execute() throws Exception;

    /**
     * Executes a query to the demo database using a new statement and returns the result in a ResultSet.
     */
    protected ResultSet executeQuery(String query) throws Exception
    {
        ResultSet rs = createStatement().executeQuery(query);
        // Add this resultset to be closed later.
        mResultSetCollection.add(rs);
        return rs;
    }

    //JAVA-added
    /**
     * Returns an demo name.
     */
    String getDemoName()
    {
        return mDemoName;
    }

    //JAVA-added
    /**
     * Returns a full path where the document generated by this demo should be stored.
     */
    String getPathToGeneratedDoc()
    {
        return new File(mGeneratedDir, mDemoName + ".doc").getAbsolutePath();
    }

    //JAVA-added
    /**
     * Returns a full path where the document generated by this demo should be stored.
     */
    String getPathToGeneratedHtml()
    {
        return new File(mGeneratedDir, mDemoName + ".html").getAbsolutePath();
    }

    //JAVA-added
    /**
     * Returns a full path where the document generated by this demo should be stored.
     */
    String getPathToGeneratedDocx()
    {
        return new File(mGeneratedDir, mDemoName + ".docx").getAbsolutePath();
    }

    //JAVA-added
    /**
     * Returns a full path where the document generated by this demo should be stored.
     */
    String getPathToGeneratedTxt()
    {
        return new File(mGeneratedDir, mDemoName + ".txt").getAbsolutePath();
    }

    //JAVA-added
    /**
     * Returns a root dir of this Aspose.Words release.
     * (the dir where unzipped downloaded Aspose.Words distributive).
     * Probably in that dir will be placed license file.
     *
     * Note: Can be called only after the demo initialization (initDemo() method).
     */
    static File getRootDistributiveDir()
    {
        assert mProjectDir != null;
        return mProjectDir.getParentFile().getParentFile();
    }

    String getPathToTemplateDoc()
    {
        return mTemplate.getAbsolutePath();
    }

    /**
     * Gets the path to the image to be inserted into the document
     */
    protected String getImagePath(){
         return mDocumentsDir + "\\Aspose.Words.gif";
    }

    /**
     * Project dir. Something like: 'Aspose.Words.Java installation path'\\demos\\Aspose.Words.Demos
     */
    protected static File mProjectDir;
    /**
     * Directory for template documents used by the demos: demos\\Documents.
     */
    protected static File mDocumentsDir;
    /**
     * Directory for documents generated by the demos: demos\\generated.
     */
    protected static File mGeneratedDir;
    /**
     * Directory for the Database used by the demos: demos\\Database.
     */
    protected static File mDatabaseDir;
    /**
     * This directory is used to store images generated in HTML format when documents are exported in
     * HTML format. Images are saved externally and they must be saved to a folder.
     * e.g C:\TomCat6.0\webapps\aspose.words\images\
     */
    protected static File mHtmlImagesDir;
    /**
     *Path used for the IMG tag in generated HTML which links to the external images stored in the folder above.
     * e.g http://localhost:80/aspose.words/Images/
     */
    protected static URI mHtmlImageAliasPath;
    /**
     * Define this explicitly as some server setups may return the wrong port.
     */
    protected static final int SERVER_PORT = 8081;
    /**
     * Database file used by the demos: demos\\Database\\Northwind.mdb.
     */
    protected static File mDatabase;
    /**
     * Stores a connection to the database.
     */
    protected static Connection mConnection;
    /**
     * Stores if the base variables used by all demos have been populated.
     */
    protected static boolean isInitialized = false;
    /**
     * Stores a list of ResultSet objects used in the demos. These are released when the demos have finished.
     */
    protected static ArrayList mResultSetCollection;
    /**
     * The name of this demo. Template document and all generated documents use this name.
     */
    protected String mDemoName;
    /**
     * Template document file used by the concrete demo.
     */
    protected File mTemplate;

    /**
     * Sends the document to the client's browser.
     */
    protected void sendToBrowser(Document doc, String demoName, String formatType, boolean openNewWindow)
            throws Exception
    {
        String fileName = demoName + "." + formatType;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int saveFormat = FileFormatUtil.extensionToSaveFormat(formatType);

        if(saveFormat == SaveFormat.HTML || saveFormat == SaveFormat.MHTML || saveFormat == SaveFormat.EPUB)
        {
            // Set options used during export to HTML based formats.
            HtmlSaveOptions htmlOptions = new HtmlSaveOptions(saveFormat);
            htmlOptions.setExportHeadersFootersMode(ExportHeadersFootersMode.NONE);
            htmlOptions.setExportXhtmlTransitional(true);
            // This option improves how tables are displayed when exporting to EPUB format.
            htmlOptions.setTableWidthOutputMode(HtmlElementSizeOutputMode.NONE);
            // These two below are only needed for .html format to set where images are saved to and how to construct
            // the URI to the saved location.
            htmlOptions.setImagesFolder(mHtmlImagesDir.getAbsolutePath());
            htmlOptions.setImagesFolderAlias(mHtmlImageAliasPath.toString());

            doc.save(out, htmlOptions);
        }
        else
        {
           doc.save(out, saveFormat);
        }

        setResponse(fileName, out);
    }

    protected FacesContext context;
    protected HttpServletRequest request;
    protected HttpServletResponse response;

    //////////////////////////////////////////////////////////
    protected final String FILE_NAME = "result.doc";

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

    private String respType = "application/msword";
    public String getResptype() {
        return respType;
    }
    public void setResptype(String v) {
        respType = v;
    }

    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 resp;
    }

    protected void setResponse(String fName, ByteArrayOutputStream out) throws IOException {
        setFilename(fName);
        resp = out.toByteArray();
        out.close();
    }
    protected byte[] resp;

    /**
     *
     * 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) {
                    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

<!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"
      xmlns:jsf="http://www.aspose.com/jsf"
      >

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

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


                <p class="componentDescriptionTxt">Welcome to the <STRONG> Aspose.Words for Java</STRONG> Featured Demos!</p>
                <p class="componentDescriptionTxt">
                                        This demo shows one of the ways you can generate a sales invoice with a header, order details and a summary with Aspose.Words. In this demo you will 
                                        learn how to mail merge data from multiple tables, format date and numeric fields and use merge regions to grow portions of the document.
                </p>
                <P class="componentDescriptionTxt"><STRONG>Important</STRONG>: To produce Word documents, the machine to
                    run Aspose.Words for Java does not need to have Microsoft Word and Windows installed.
                    However, to view the contents of Word documents produced by demos, the machine to view
                    them needs at least Microsoft Word Viewer installed. Microsoft Word Viewer can be
                    <A href="http://www.microsoft.com/downloads/details.aspx?FamilyID=95e24c87-8732-48d5-8689-ab826e7b8fdf&amp;DisplayLang=en">
                    downloaded</A> for free.</P>
                <P class="componentDescriptionTxt">In all of these examples no OLE automation is used, all work is
                    performed by Aspose.Words for Java without Microsoft Word installed on the web server.</P>

                    <ui:include src="/WEB-INF/includes//templates/selectformat.xhtml" />

                <h:commandButton id="generate" action="#{barcode.executeDemo}" value="Generate" /> 

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