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.
Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion.
We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class. In ByteArrayInputStream there is an internal buffer present that contains bytes that reads from the stream.
Basically we are going to : Get the bytes of the String. Create a new ByteArrayInputStream using the bytes of the String. Assign the ByteArrayInputStream object to an InputStream variable (which you can do as InputStream is a superclass of ByteArrayInputStream )
To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.
new StreamSource(new StringReader(str))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With