I am unable to retrive inline images/screen shot from Java in Lotus Notes from
document.getItemValueString('Body')
By above function am i able retrive text available in mailbody not inline images.
Please provide your suggestions in order to retrive inlines images from the mail body
Thanks in advance.
LSP Jyothi
First of all: Body is a NotesRichtextItem. You would have to use the NotesRichtextItem- methods and properties to get the inline- image... if there where any for that purpose.
Inline- images are not handled by any means in LotusScript. To get them, you need to:
Export the document as XML
Find the part in the XML that represents the inline image
take the Base64- encoded value there and convert it into a binary format, use Mime- Classes for that (Trick).
Write the data to a file
There is a lot of code involved in doing this. I just post the "crucial" parts of the code here (untested, no syntax check, just as a starting point):
EDIT: Sorry, I am not an expert in Java and only saw the tag "lotusscript", therefor my example is LotusScript- Code (should be similar with java, and I think Base64- operations are alreays built in in java, no need to use the Mime- Trick)
Dim strDxl as String
Dim strFoundBase64 as String
Dim exporter as NotesDXLExporter
Dim stream as NotesStream
Dim docConvert as NotesDocument
Dim mimeEntity as NotesMimeEntity
Set exporter = session.CreateDXLExporter
exporter.ConvertNotesBitmapsToGIF = True
strDxl = exporter.Export(document)
'- Search through strDxl and find everything that is in the following tags:
'- <gif></gif>, <gif originalformat='notesbitmap'></gif>, <jpeg></jpeg>, <png></png>
strFoundBase64 = ...'assign text between tags
'- use Mime class to convert to binary
Set docConvert = New NotesDocument( document.ParentDatabase )
Set mimeEntity = docConvert.CreateMIMEEntity
Call mimeEntity.SetContentFromBytes(strFoundBase64, "image/gif", ENC_BASE64)
'- Write result to file
Set stream = ses.CreateStream
Call stream.Open( "C:\Temp\image.gif", "binary")
Call mimeEntity.GetContentAsBytes(stream)
Call stream.Close()
Related
I am developing font converter app which will convert Unicode font text to Krutidev/Shree Lipi (Marathi/Hindi) font text. In the original docx file there are formatted words (i.e. Color, Font, size of the text, Hyperlinks..etc. ).
I want to keep format of the final docx same as the original docx after converting words from Unicode to another font.
PFA.
Here is my Code
try {
fileInputStream = new FileInputStream("StartDoc.docx");
document = new XWPFDocument(fileInputStream);
XWPFWordExtractor extractor = new XWPFWordExtractor(document);
List<XWPFParagraph> paragraph = document.getParagraphs();
Converter data = new Converter() ;
for(XWPFParagraph p :document.getParagraphs())
{
for(XWPFRun r :p.getRuns())
{
String string2 = r.getText(0);
data.uniToShree(string2);
r.setText(string2,0);
}
}
//Write the Document in file system
FileOutputStream out = new FileOutputStream(new File("Output.docx");
document.write(out);
out.close();
System.out.println("Output.docx written successully");
}
catch (IOException e) {
System.out.println("We had an error while reading the Word Doc");
}
Thank you for ask-an-answer.
I have worked using POI some years ago, but over excel-workbooks, but still I’ll try to help you reach the root cause of your error.
The Java compiler is smart enough to suggest good debugging information in itself!
A good first step to disambiguate the error is to not overwrite the exception message provided to you via the compiler complain.
Try printing the results of e.getLocalizedMessage()or e.getMessage() and see what you get.
Getting the stack trace using printStackTrace method is also useful oftentimes to pinpoint where your error lies!
Share your findings from the above method calls to further help you help debug the issue.
[EDIT 1:]
So it seems, you are able to process the file just right with respect to the font conversion of the data, but you are not able to reconstruct the formatting of the original data in the converted data file.
(thus, "We had an error while reading the Word Doc", is a lie getting printed ;) )
Now, there are 2 elements to a Word document:
Content
Structure or Schema
You are able to convert the data as you are working only on the content of your respective doc files.
In order to be able to retain the formatting of the contents, your solution needs to be aware of the formatting of the doc files as well and take care of that.
MS Word which defined the doc files and their extension (.docx) follows a particular set of schemas that define the rules of formatting. These schemas are defined in Microsoft's XML Namespace packages[1].
You can obtain the XML(HTML) format of the doc-file you want quite easily (see steps in [1] or code in link [2]) and even apply different schemas or possibly your own schema definitions based on the definitions provided by MS's namespaces, either programmatically, for which you need to get versed with XML, XSL and XSLT concepts (w3schools[3] is a good starting point) but this method is no less complex than writing your own version of MS-Word; or using MS-Word's inbuilt tools as shown in [1].
[1]. https://www.microsoftpressstore.com/articles/article.aspx?p=2231769&seqNum=4#:~:text=During%20conversion%2C%20Word%20tags%20the,you%20can%20an%20HTML%20file.
[2]. https://svn.apache.org/repos/asf/poi/trunk/src/scratchpad/testcases/org/apache/poi/hwpf/converter/TestWordToHtmlConverter.java
[3]. https://www.w3schools.com/xml/
My answer provides you with a cursory overview of how to achieve what you want to, but depending on your inclination and time availability, you may want to use your discretion before you decide to head onto one path than the other.
Hope it helps!
I am trying to read the HTML contents of a Document object(mail) as a part of my plug in development in Lotus Notes 9.
With this HTML content, we would like to create a file and send it as an attachment file in our query, so we can preserve the formatting, images, etc.
Even after session.setConvertMIME(false); I still do not get the Mime entity when I call doc.getMIMEEntity().
I have made preferences setting in Preferences>Mail>Internet
Internet mail format to "HTML and plain text".
I have tried doc.createMIMEEntity and then tried to retrieve it
mimePart = doc.getMIMEEntity("Body");
When i right clicked on Incoming mails from outlook I was able to see multiple Body items, one of which contained the HTML part.However I was still not able to access it via getMIMEEntity.
The mails I created from lotus notes, do not have multiple Body items. When I receive the mails from Lotus Notes > Outlook and I inspect source in Outlook, I see it as HTML. So I assume there is a place where this conversion takes place.
ShelfSession.getInstance().localSession.setConvertMime(false);
MIMEEntity nMime = (MIMEEntity) doc.getMIMEEntity("Body");
I want the Mime part to be set to this variable so I can retrieve the content to form the HTML file.
Please help with any code suggestions or is there some Lotus notes setting that I have missed out on that is making the Mime variable always null?
You said, "The mails I created from lotus notes, do not have multiple Body items." This almost certainly means the Body item is stored as rich text instead of MIME. You can confirm this by looking at the document properties in Notes.
You can use document.convertToMIME() to convert a Body item from Notes rich text to MIME. Here's an example:
MIMEEntity mimeEntity = null;
Item item = document.getFirstItem("Body");
if (item != null) {
if (item.getType() == Item.RICHTEXT) {
// Convert Notes rich text to MIME
document.convertToMIME(Document.CVT_RT_TO_PLAINTEXT_AND_HTML, 0);
}
mimeEntity = document.getMIMEEntity();
}
I've adapted this example from some code in MimeEntityHelper from the XPages Extension Library. I'd encourage you to take a look at that code for more context. For example, you still need to call session.setConvertMIME(false) to avoid converting a document that is already MIME to rich text. The MimeEntityHelper class uses both session.setConvertMIME() and document.convertToMIME() to control document conversions.
I have a canvas painted by the user.
In the JavaScript I do:
var data = canvas.toDataURL().substr(22);
// snipped code that sets up xhr POST to "d/"
var params = "img=" + encodeURIComponent(data);
xhr.send(params);
I substr(22) to get rid of "data:image/png;base64,"
Then in app engine I do:
doodle.setProperty("img", new Text(req.getParameter("img")));
So I am setting the img property of the doodle Entity to the canvas.toDataURL().substr(22)
Now, when I want to retrieve the image, I do:
if (debugimg) {
resp.setContentType("text/plain");
resp.getWriter().print(((Text)groove.getProperty("img")).getValue());
}
else {
resp.setContentType("image/png;base64");
resp.getWriter().print(((Text)groove.getProperty("img")).getValue());
}
But for the life of me, the image never comes up.
Here is an example. I drew this, and can save it and render it in JavaScript.
https://yougotadoodle.appspot.com/d.jsp?id=1483002
If I use debugimg, this is what is being saved:
http://yougotadoodle.appspot.com/d?id=1483002&img=true&debugimg=true
But when I try to serve it with setContentType("image/png;base64") or even just "image/png" you get a broken picture:
http://yougotadoodle.appspot.com/d?id=1483002&img=true
I have tried a few different things, including not substr(22)ing it. Any ideas?
I tried using a Blob(), so storing it like this:
doodle.setProperty("img", new Blob(req.getParameter("img").getBytes()));
and reading it like this:
resp.getWriter().print(((Blob)groove.getProperty("img")).getBytes());
But that seemed to spit out somethign like this:
[B#1f11e0f
You have to decode this string before serving it as image/png because it is the Base64 encoded version.
I tested it locally in Python and your Hello SO! worked perfectly after decoding the given string. I'm not sure how to do it in Java but it should be fairly easy.
Here are three code snippets that have worked for me on the JS side (jpg) through the put to a blob property. May not be optimal, but it does work. HTH. -stevep
Create canvas render:
imgFinalData = canvas.toDataURL('image/jpg', 1.0);
Setup variable for POST to GAE:
f64 = imgFinalData.substr(imgFinalData.indexOf(',')+1).toString();
Post to GAE (fd is an array used to store mutiple POST vars):
fd.push('bytes=' + escape(f64));
//Here is the call with fd that handles the post:
postXmlHttpRequest(url, fd.join('&'), handlePostFinal);
One the GAE side (Python):
Property that stores POST data (line from entity class):
bytes = db.BlobProperty(required=True, indexed=False)
How the post data is processed b/4 put:
data = urllib.unquote(self.request.get('bytes'))
data = data.replace(' ','+')
bytes = base64.b64decode(data + '=' * (4 - len(data) % 4))
Property line inside the entity statement for put:
bytes = db.Blob(bytes),
I have a solution that inserts strings into an XHTML document and prints the results as Reports. My employer has asked if we could pull images off their SQL database (stored as byte arrays) to insert into the Reports.
I am using FlyingSaucer as the XHTML interpreter and I've been using Java DOM to modify pre-stored reports that I have stored in the Report Generator's package.
The only solution I can think of at the moment is to construct the images, save them as a file, link the file in an img tag (or background-image) in a constructed report, print the report and then delete the file. This seems really sloppy and I imagine it will be very time consuming.
I can't help but feel there must be a more elegant solution. Any suggestions for inserting a byte array into html?
Read the image and convert it into it's Base64-encoded form:
InputStream image = getClass().getClassLoader().getResourceAsStream("image.png");
String encodedImage = BaseEncoding.base64().encode(ByteStreams.toByteArray(image));
I've used BaseEncoding and ByteStreams from Google Guava.
Change src attribute of img element within your Document object.
Document doc = ...; // get Document from XHTMLPanel.getDocument() or create
// new one using DocumentBuilderFactory
doc.getElementById("myImage").getAttributes().getNamedItem("src").setNodeValue("data:image/png;base64," + encodedImage);
Unfortunatley FlyingSaucer does not support DataURIs out-of-the-box so you'll have to create your own ReplacedElementFactory. Read Using Data URLs for embedding images in Flying Saucer generated PDFs article - it contains a complete solution.
We are in the process of converting over to using the XSLT compiler for page generation. I have a Xalan Java extention to exploit the CSSDK and capture some meta data we have stored in the Extended Attributes for output to the page. No problems in getting the EA's rendered to the output file.
The problem is that I don't know how to dynamically capture the file path and name of the output file.
So just as POC, I have the CSVPath hard coded to the output file in my Java extension. Here's a code sample:
CSSimpleFile sourceFile = (CSSimpleFile)client.getFile(new CSVPath("/some-path-to-the-output.jsp"));
Can someone point me in the CSSDK to where I could capture the output file?
I found the answer.
First, get or create your CSClient. You can use the examples provided in the cssdk/samples. I tweaked one so that I captured the CSClient in the method getClientForCurrentUser(). Watch out for SOAP vs Java connections. In development, I was using a SOAP connection and for the make_toolkit build, the Java connection was required for our purposes.
Check the following snippet. The request CSClient is captured in the static variable client.
CSSimpleFile sourceFile = (CSSimpleFile)client.getFile(new CSVPath(XSLTExtensionContext.getContext().getOutputDirectory().toString() + "/" + XSLTExtensionContext.getContext().getOutputFileName()));