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";
		ResumeEngineImpl.log.entering(ResumeEngineImpl.sourceClass,
				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.JASPER_PRINT,
					jasperPrint);
			docExporter.setParameter(JRDocxExporterParameter.OUTPUT_STREAM,
					docStream);
			docExporter.setParameter(JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, Boolean.TRUE);
			docExporter.exportReport();
			docResume = docStream.toByteArray();
		} catch (final JRException e) {
			ResumeEngineImpl.log.logp(Level.WARNING,
					ResumeEngineImpl.sourceClass, sourceMethod,
					"Exception caught:", e);
		} catch (final RuntimeException e) {
			ResumeEngineImpl.log.logp(Level.WARNING,
					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.

Advertisements

One Response

Subscribe to comments with RSS.

  1. Rodolfo Velasco said, on January 22, 2015 at 12:40 pm

    Where do I need to add this code?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: