Jerry Jacob's Blog

Create Word Documents Using Jasper API

Posted in Java/ J2EE by jerlinworld on March 9, 2010

All the basics for creating a document using Jasper API remains the same except the Exporter. Please refer to my earlier post to create PDF and RTF reports.

Given below is the code that would return the word document in byte array.
NOTE: You have to use the jasper api version 3.5.x or higher

public byte[] buildDocResume(final String ssnNumber) {

		final String sourceMethod = "buildDocResume";
				sourceMethod, ssnNumber);
		byte[] docResume = null;
		try {
			final Seeker seeker = this.getSeekerBySsn(ssnNumber);
			final JasperPrint jasperPrint = this.renderResume(seeker);

			final JRDocxExporter docExporter = new JRDocxExporter();
			final ByteArrayOutputStream docStream = new ByteArrayOutputStream();
			docExporter.setParameter(JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, Boolean.TRUE);
			docResume = docStream.toByteArray();
		} catch (final JRException e) {
					ResumeEngineImpl.sourceClass, sourceMethod,
					"Exception caught:", e);
		} catch (final RuntimeException e) {
					ResumeEngineImpl.sourceClass, sourceMethod,
					"Exception caught:", e);

		return docResume;

Tip: The generated word document will be formatted using several nested tables. If the property, JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, is set to false, the table rows do not increase in height automatically and the user has to enlarge them manually in word.