27

I'm trying to generate a PDF document using FOP and Java.

I receive the XML as a string and not as a file.

How can I convert this XML string to an XML input stream so that I can call xslfoTransformer.transform(source, res); where source is my XML string as an Input stream.

Please provide your suggestions.

jobinbasani
  • 2,075
  • 6
  • 47
  • 66

3 Answers3

53
new StreamSource(new StringReader(str))
Vladimir Dyuzhev
  • 18,130
  • 10
  • 48
  • 62
24

You probably want to convert it to a Reader, not an InputStream. Use StringReader to do this. StreamSource has a constructor that takes a Reader, and you can pass that StreamSource to Transformer.transform().

I say you probably want a Reader rather than an InputStream because a String holds characters, not bytes, and an InputStream is a stream of bytes while a Reader is a stream of characters.

jobinbasani
  • 2,075
  • 6
  • 47
  • 66
Laurence Gonsalves
  • 137,896
  • 35
  • 246
  • 299
  • I tried this method but I'm getting an exception. java.lang.NullPointerException at org.apache.fop.area.AreaTreeHandler.endDocument(AreaTreeHandler.java:264) at org.apache.fop.fo.FOTreeBuilder.endDocument(FOTreeBuilder.java:171) at net.sf.saxon.event.ContentHandlerProxy.close(ContentHandlerProxy.java:255) at net.sf.saxon.event.ImplicitResultChecker.close(ImplicitResultChecker.java:69) at net.sf.saxon.event.ProxyReceiver.close(ProxyReceiver.java:87) at net.sf.saxon.event.ComplexContentOutputter.close(ComplexContentOutputter.java:468) at Any clues? – jobinbasani Oct 02 '09 at 19:26
  • Ok..I figured it out... It worked when I renamed the root element of the xml to 'root'. Thanks for the help!!!! – jobinbasani Oct 02 '09 at 19:44
2

Use ByteArrayInputStream:

String S = ...;
InputStream source = new ByteArrayInputStream(S.getBytes(encoding))
ChssPly76
  • 99,456
  • 24
  • 206
  • 195