Docx4j - Replacing Word merge field with HTML content - html

I am trying to replace a Word merge field "test" with an HTML content :
String myText = "<html><body><h1>Hello</h1></body></html>";
using Docx4j.
String myText = "<html><body><h1>Hello</h1></body></html>";
try {
WordprocessingMLPackage docxOut =
WordprocessingMLPackage.load(new java.io.File("/tmp/template.docx"));
Map<DataFieldName, String> data = new HashMap<>();
data.put(new DataFieldName("test"), myText);
org.docx4j.model.fields.merge.MailMerger.performMerge(docxOut, data, true);
docxOut.save(new java.io.File("/tmp/newTemplate.docx"));
} catch (Docx4JException e) {
LOGGER.error(e.getMessage());
}
As a result, I have an output (newTemplate.docx) with my merge field replaced by
"<html><body><h1>Hello</h1></body></html>"
without being interpreted as HTML. I tried adding :
docxOut.getContentTypeManager().addDefaultContentType("html", "text/html");
but it still didn't work. I am not even sure if interpreting HTML while replacing a Word merge field can be done using Docx4j or if I'm missing something.
Any help would be welcome.

You can use the OpenDoPE approach to bind a content control to a Custom XML element which contains escaped XHTML.

Related

XML to Json conversion with HTML string data

I have XML documents that I am trying to convert to Json but some of the string fields have HTML tags in them (from copy/paste of text fields from Word documents). The source XML looks like this:
<my:Request_Description>
<html xml:space="preserve" xmlns="http://www.w3.org/1999/xhtml">
<div>test</div>
</html>
</my:Request_Description>
When JsonConvert.SerializeXmlNode is called the Json ends up as this:
"Request_Description": {
"html": {
"#xml:space": "preserve",
"#xmlns": "http://www.w3.org/1999/xhtml",
"#significant-whitespace": [
"\r\n ",
"\r\n"
],
"div": "test"
}
}
I tried to just declare the field as a string but when calling deserializeobject the error is Unexpected character encountered while parsing value.
Is there something I should do on the serializexmlnode to make the Json result different? Or is there something I can do on the deserializeobject to have it ignore the HTML tag?
Ideally the json would be something like below but I assume some escape characters would need to be included for the quote marks. The main point being that HTML tags do NOT denote a separate node but instead are part of the value for the node. I started looking into XSLT and thought that might be an option.
{
"Request_Description": "<html xml:space="preserve" xmlns="http://www.w3.org/1999/xhtml"><div>test</div></html>"
}
Switched to using XDocument and this code worked.
XElement req_desc = newxdoc.Root.Element("Request_Description");
if (req_desc != null)
{
XElement replacenode = new XElement(req_desc.Name, req_desc.Value);
req_desc.Parent.Add(replacenode);
req_desc.Remove();
}

Javascript does not accept HTML String from MVC?

Javascript does not accept HTML String from MVC?
My MVC contoller from where I am sending the HTML template in string from txt file
using (StreamReader sr = new StreamReader(#"D:\Templates\NewGridTemplate.txt"))
{
// Read the stream to a string, and write the string to the console.
obj.sGridTemplate = sr.ReadToEnd().Replace(Environment.NewLine, " ");
//Console.WriteLine(line);
}
return View(obj);
Actual code in csHTMl Javascript
var sHTML=$(#Model.sGridTemplate);
Below is screen shot for error . HTML string is not accepted by Javascript. shows character "<" etc.. Please help let me know what I missed.Image 3
You need to put your content within quotes so that it becomes a Javascript string, otherwise it'll be interpreted as syntax and you get the error because it's not valid JS syntax
var sHTML=$('#Model.sGridTemplate');
And the problematic line in the resulting client-side code should look more like this:
var sHTML=$(' < ...
... than:
var sHTML=$( < ...

ObjectMapper explicitly printing carriage returns and escaping quotation marks in my JSON

Been asked to modify a project to save space in our console and log files that has the following Spring application property which I've been asked to leave in place:
spring.jackson.serialization.indent_output=true
Obviously, that's going to pretty print all of our JSON and take up a ton of space in the console and log files.
The application has a groovy class that extends Spring's OncePerRequestFilter class that grabs HTTP requests and responses and sends them through a groovy class that masks sensitive data. This class has a method that takes in a string which is essentially the stringified version of the request's or response's body.
Once the string has been masked, it is run through Jackson's ObjectMapper to basically undo the spring application property to make every print pretty:
Code #1:
return objectMapper.writer().without(SerializationFeature.INDENT_OUTPUT).writeValueAsString(stringToWrite);
Here's some example input that will be going through the code:
{
"person" : {
"personName" : "BAR, FOO",
}
}
... and the result ends up being ...
Result #1:
"{\r\n \"person\" : {\r\n \"personName\" : \"BAR, FOO\",\r\n }\r\n }"
... trying to take the easy way out, I figured applying a simple .replaceAll() on the string would knock out the explicit quote escapes and carriage returns, but I found the carriage returns disappeared and that the quote escapes just come right back...
Code #2:
return objectMapper.writer().without(SerializationFeature.INDENT_OUTPUT).writeValueAsString(stringToWrite.replaceAll("\\\"", '"').replaceAll("\\r", "").replaceAll("\\n", ""));
Result #2:
"{ \"person\" : { \"personName\" : \"BAR, FOO\" } }"
... and finally, if I just use
Code #3
.replaceAll("\\\"", "")
... instead of what I used in Code #2 which was ...
.replaceAll("\\\"", '"')
... then I get ...
Result #3
"{ person : { personName : BAR, FOO } }"
... but what is asked of me is ...
Desired Result:
"{ "person" : { "personName" : "BAR, FOO" } }"
It appears to be a result of something the objectMapper is using, but I'm a little at a loss at this point.
Turns out you can set this, but it isn't obvious.
There is probably a better way, but I found this works:
DefaultPrettyPrinter p = new DefaultPrettyPrinter();
DefaultPrettyPrinter.Indenter i = new DefaultIndenter(" ", "\n");
p.indentArraysWith(i);
p.indentObjectsWith(i);
mapper.setDefaultPrettyPrinter(p);
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(myObject);
As it turns out, I was complicating this whole situation by thinking it was an issue with objectMapper. Instead, my custom OncePerRequestFilter is logging my custom javax.servlet.http.HttpServletRequestWrapper's requestBody which is a byte[] converted to a String so all I needed was to replace the explicit return carriages and line feeds for UTF-8 encoding:
stringToWrite.replaceAll("\\r", "").replaceAll("\\n", "")

How can I pass json string into HtmlHelper's result?

I want to pass a serialized json object and returned it within custom Html Helper's result. Something like this
public static HtmlString SomeHelper(this HTMLHelper htmlHelper)
{
var MyObject = new Foo();
var oSerializer = new JavaScriptSerializer();
var str = string.Format(#"<a href""#""
onclick=""var myObject = $.parseJSON(0);
alert('my object name property '+ myObject.Name); ""> Click me</a>",
oSerializer.Serialize(MyObject));
return new HtmlString(str);
}
That thing theoretically should work, but it doesn't. It puts serialized string to markup and then everything gets messy, because of double and single quotes. I tried to apply HtmlString after serialization, I even tried to use HTmlString.ToHtmlString(). Nothing works.
In fact I probably shouldn't do that. The click event call should be used unobtrusively. I know. Then I still have to save json object somewhere in the resulting markup.
Upd: I even tried to do that:
sJson.replace("\"",""")
Not helping. Browser automatically converts "s into ". I don't know how to preserve the markup
Is html.Encode the answer?
return new HtmlString(Html.Encode(str));
I guess the only solution would be to replace all double quotes in oSerializer.Serialize(MyObject)) with some other symbol, which wouldn't conflict in html markup, and then before the parsing put double quotes back, otherwise it wouldn't be a legit json string.

Replacing string in html dynamically in Android

I am using "loadDataWithBaseUrl(...)" to load a html file, stored in assets, to Webview. that contains a string "Loading..." and a rotating GIF. String "Loading..." is hard coded, and it'll not be localized. How to replace that string dynamically, so that it can be localized?
Please help me to resolve this.
There are various solutions I could think of :
Load a different asset file according to the current language (get the current language using Locale.getDefault()), This way you can translate your HTML files independently.
Use place holders in your HTML file (for instance #loading_message#), then load the asset file in a String, replace all the occurences of the placeholder by the appropriate localised message (String.replaceAll("#loading_message#", getText(R.string.loading_message).toString())), finally load the processed HTML into the WebView using the loadData(String data, String mimeType, String encoding) function.
To load the asset file, you can do something like that:
File f = new File("file:///android_asset/my_file.html");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
String eachLine = br.readLine();
while(eachLine != null) {
sb.append(eachLine);
sb.append("\n");
eachLine = br.readLine();
}
// sb.toString is your HTML file as a String
I had a similar problem when using the WebView to show help text that should be translated.
My solution was to add multiple translated HTML files in assets and loading them with:
webView.loadUrl("file:///android_asset/" + getResources().getString(R.string.help_file));
For more details go to: Language specific HTML Help in Android
String str = "Loading ..."
String newStr = str.substring("Loading ".length());
newStr = context.getResourceById(R.string.loading) + newStr;
I hope the code is sufficiently clear to understand the idea: extract the string without "Loading " and concatenate it with the localized version of "Loading" string