Wednesday, February 27, 2013

Convert word document (.docx) to PDF

This post will describes how to convert word document to PDF using Java.

To convert document to Pdf we will have different type of approaches.
But in this post i am using  docx4j. It is one of the good API for conversion from XSLT to PDF and Word Document to PDF etc..

We can convert from document to Pdf with Simple java program.

Steps to follow.

Step1 :open Eclipse and create new java project- provide name as you like.

Step 2: Create new Java class  which ever you like (ex: ConvertDocToPDF )

Step 3: Paste the below lines of code inside main method of created java class

 try {

long start = System.currentTimeMillis();

// 1) Load DOCX into WordprocessingMLPackage

InputStream is = new FileInputStream(new File("test.docx"));
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(is);
//If your header and body information got over lapped then use the below code
List sections = wordMLPackage.getDocumentModel().getSections();
for (int i = 0; i < sections.size(); i++) {

System.out.println("sections Size" + sections.size());

//if you want use any Physical fonts then use the below code.

Mapper fontMapper = new IdentityPlusMapper();

PhysicalFont font = PhysicalFonts.getPhysicalFonts().get("Comic Sans MS");

fontMapper.getFontMappings().put("Algerian", font);


// 2) Prepare Pdf settings

PdfSettings pdfSettings = new PdfSettings();

// 3) Convert WordprocessingMLPackage to Pdf

org.docx4j.convert.out.pdf.PdfConversion conversion = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage);

OutputStream out = new FileOutputStream(new File("test.pdf"));
System.err.println("Time taken to Generate pdf  "+ (System.currentTimeMillis() - start) + "ms");
} catch (Throwable e) {


Step 4: Now you can run the Java program, PDF will be generate for your Document file.

Wednesday, February 13, 2013

spring and xslt example

This post will describe to work with spring and xslt.

1. open Eclipse and create a dynamic webproject - provide name as  spring-xslt(you can give what ever name you want)

2. After that select the target runtime environment(ex: location of tomcat or Jboss or respective server)

3. open web.xml which already created by eclipse for you, modify as mentioned below.


<web-app id="WebApp_ID" version="2.4" xmlns:xsi="" xmlns="" xsi:schemalocation="">







4. After that create simple-servlet.xml like mentioned below and put inside WEB-INF

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
        xsi:schemaLocation=" " >
  <bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver" >
  <property name="order"><value>1</value></property>
  <property name="basename" value="views" />
  <bean id="xsltViewResolver"
  class="org.springframework.web.servlet.view.xslt.XsltViewResolver" >
  <property name="order"><value>2</value></property>
  <property name="viewClass"
  value="org.springframework.web.servlet.view.xslt.XsltView" /> 
  <property name="sourceKey" value="obj" /> 
  <property name="suffix" value=".xsl" />
  <property name="prefix" value="/WEB-INF/xsl/" />
  <bean id="simpleUrlMapping"
  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" >
  <property name="mappings" >
  <bean id="myxsl"
  class="com.siva.HomePageController" />
  <!--<bean id="myxsl"
  class="com.siva.XsltDisplayController" />
5. Now we have to create xslt file under /WEB-INF/xsl/home.xslt and place the below mentioned code

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="">
<xsl:output method="html" omit-xml-declaration="yes"/>
<xsl:template match="/">
<h1>My First Words</h1>
<xsl:template match="word">
<xsl:value-of select="."/><br/>

6. Now Need to create Contoller class by extending AbstractCommandController.
package com.siva;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HomePageController extends AbstractController{
protected ModelAndView handleRequestInternal(
HttpServletRequest request,
HttpServletResponse response) throws Exception {

Map map = new HashMap();
List wordList = new ArrayList();


map.put("wordList", wordList);
return new ModelAndView("home", map);

7. Need to create xslt view class to iterate the xslt elements.

package com.siva;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import org.springframework.web.servlet.view.xslt.AbstractXsltView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class HomePage extends AbstractXsltView {
protected Source createXsltSource(Map model, String rootName, HttpServletRequest
request, HttpServletResponse response) throws Exception {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element root = document.createElement(rootName);

List words = (List) model.get("wordList");
for (Iterator it = words.iterator(); it.hasNext();) {
String nextWord = (String);
Element wordNode = document.createElement("word");
Text textNode = document.createTextNode(nextWord);
return new DOMSource(root);
8.Create file under WEB-INF/classes/


9.finally create one index.html or jsp to submit the form.

<form action="login.htm" name="login">
Word Id :<input type="text" value="" name="wordId">
Word NAME :<input type="text" value="" name="wordName">
<input type="submit" value="submit">



Above mentioned html/jsp is for to submit the form, if we required fileds need to be eneterd by the user then we have to get that values from command object, and then needs to process.

10. Now Everthing is completed. Once you configured and copied the above code into respective places.
We can exceuting the application and can able to see the results.
11. for this project required jars are..



Contact Form


Email *

Message *