Set data URI in TinyMCE - html

TinyMCE init options
$scope.tinymceOptions = {
plugins: 'base64img image imagetools paste ...',
relative_urls: false,
paste_data_images: true,
...
};
paste_data_images: true option means that data:url images (inline images) should NOT be removed from the pasted contents (see docs).
I use TinyMCE 4.2.8. Inside base64img plugin I've written the following code
var editor; // TinyMCE editor
var imgData; // base64 image data string, like "data:image/png;base64,...="
editor.setContent("<img src='" + imgData + "' />", {format: 'raw'});
// editor.execCommand('mceInsertRawHtml', false, '<img src=\'' + imgData + '\' />'); // another way
to embed an image which is loaded in memory as base64 string. After the command is executed img src is magically converted into 'blob:http%3A//localhost%3A8080/...'. Why?
It works (images are displayed), but I want to store images as data: rather than upload them to server and store as blob. How to change this behaviour?

Image is saved internally as 'data:image/png;base64,...=', so you don't need to worry. No uploading is performed, 'blob:http%3A//localhost%3A8080/...' is used for displaying an image info only.

Related

Flying Saucer - Open an attachment from pdf link

I would like to know if there is a way to create a link (Using HTML) to open an attachment embedded in the pdf document.
Something like this...
Open the attachment file or Open the attachment file
Any suggestion or recommendation?
Thanks
I have been able to implement this scenario after reading the next useful post
https://groups.google.com/forum/#!topic/flying-saucer-users/KuwPoTjaQYU
Steps:
Check out the next repository https://github.com/osnard/flyingsaucer
Analyse the file ITextOutputDevice.java, method processLink(RenderingContext c, Box box)
Make changes based on your needs
Build the project and use the jar file generated
Here the code to create an embedded file based on base64 content.
Java
...String doEmbedFile = handler.getAttributeValue( elem, "data-fs-embed-file" );
if ("true".equals(doEmbedFile.toLowerCase())) {
String fileName = new File(uri).getName();
String content = handler.getAttributeValue( elem, "content" );
com.lowagie.text.Rectangle targetArea = checkLinkArea(c, box);
if (targetArea == null) {
return;
}
try {
if (!_attachments.contains(fileName)) {
byte[] fileBytes = Base64.getDecoder().decode(content.getBytes("UTF-8"));
PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(_writer, null, fileName, fileBytes);
fs.addDescription(fileName, true);
_writer.addFileAttachment(fs);
_attachments.add(fileName);
}
targetArea.setBorder(0);
targetArea.setBorderWidth(0);
//This only works on Adobe Acrobat Reader
PdfAction action = PdfAction.javaScript(
"this.exportDataObject({cName:\"" + fileName + "\", nLaunch:2});",
_writer
);...
HTML
<body><div id='div1'><p><a href='test.png' data-fs-embed-file='true' content='iVBORw0KGgoAAAANSUhEU...'>open test.png file</a></p></div><div id='div2'><p><a href='test.pdf' data-fs-embed-file='true' content='JVBERi0xLjUNCiW1tbW1D...'>open test.pdf file</a></p></div><div id='div3'><p><a href='test.txt' data-fs-embed-file='true' content='VEVFRUVFRUVFRVNUIFRYVA=='>open test.txt file</a></p></div></body>
*base64 content truncated
Output
Greetings and I hope it can help others
just open it on new tab, add attribute target="_blank" in your anchor tag
Open attachment

Adding screenshot to TestNG

I am running some tests using testNG and Selenium. The test data comes from a CSV file. In each step it is possible to take a screenshot of the page. I am trying to add this screenshot to the testNG HTML report (emailable report).
I am using this to add the img element;
Reporter.log("<img src=\"file:///" + pathToScreen + "\" alt=\"\"/><br />");
Now this works partially, because it is in fact adding this to the report as you can see in the screenshot below. But the HTML code does not seem to work.
Is the path to the image file wrong? I think so, but I am not sure how I can fix this.
UPDATE:
This is from the source code of the HTML report. Apparently its not even parsing it as HTML???
<div class="messages"><img src="file://C:\Users\myUSername\Desktop/screenshots/step 1_enter username_baseline.png" alt=""/></img></div>
To have the screenshot embedded in the index.html report I used relative paths as:
System.setProperty("org.uncommons.reportng.escape-output", "false");
Reporter.log(
"<a title= \"title\" href=\"../path/from/target/" + fileName + "\">" +
"<img width=\"418\" height=\"240\" alt=\"alternativeName\" title=\"title\" src=\"../surefire-reports/html/screenShots/"+fileName+"\">
</a>");
In this case, the Screenshot is displayed in the OutputReport not in the main index page with the stacktrace of the fails which is a bit anoying. But at least images and links are working.
I edit myself to add the complete solution, setting the property "org.uncommons.reportng.escape-output" as false we are passing the html code instead of the text.
I recommend to use ReportNG where the screenshots are attached correctly to the test failure with the complete stack trace:
Ok apparantly I was looking at the wrong file. I was looking at the emailable-report.html while reporter.log sends everything to index.html. In the index.html file everything is working fine using the code in my first post.
if you want to save your image both as file(jpg/png etc ..) and base64 format try below complete code .
Base64 format is recommended for emailable reports .
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//Saving image to current working directory , you can ignore this step if dont want to save file
FileUtils.copyFile(src, new File("./demotest.png"));
String fileName = System.getProperty("user.dir") + "/demotest.png";
Reporter.setEscapeHtml(false); //This need to be set as false
byte[] fileContent = FileUtils.readFileToByteArray(new File(fileName));
String encodedString = Base64.getEncoder().encodeToString(fileContent);
String path = "<img src=\"data:image/png;base64, " + encodedString + "\" width=\"300\" height=\"350\" />";
Reporter.log(path);
or if you want only Base64 file format then ..
String src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);
String path = "<img src=\"data:image/png;base64, " + src + "\" width=\"300\" height=\"350\" />";
Reporter.log(path);
See Output:

phantomjs and passing imagedata as json

Can I use phantomjs to create an image of the contents of <div><iframe ..></div> (The div contains an iframe)
how do I make this image (binary data) as part of a json ? , as ({img: binary data}) ?
Is it possible to load the iframe by itself? If you can achieve that then there's no reason why you can't call var base64string = page.renderBase64(); to get a base-64 encoded string. See the API for renderBase64().
You can re-create the image later by evaluating img.src = "data:image/png;base64," + base64string;.

Loading image binary data returned by Ext.Ajax.request into <img> tag

This is a Sencha Touch + HTML question.
I retrieve image data from server using Ext.Ajax.request.
Ext.Ajax.request({
url: 'http://localhost:3000/someimage.jpg',
method: 'GET',
success: function(res) {
rec.set('imagedata', 'data:image/jpeg;base64{' + res.responseText + '}');
},
failure: function() {
console.log ( 'Failed to GET image data ' + url );
},
scope: this
});
Above res.responseText seems to contain the contents of the jpg file.
At a later point, I pass image data into an tag in html, as follows,
<img src="{imagedata}" style="width:100%;"/>
Result:
Instead of the image, i see garbled text in image box. The garbled text is the content of responseText.
( PS... I am doing this to be able to store the image data locally into a sencha store. )
I would just store the URLs of the images in the store and then create IMG elements on the fly like you do with the src set to the URL instead.
Keep it simple.

Uploading Image (Local) to Tinymce

I would like to ask if there is any plugin available that is able to upload image from my local system to tinymce? Tinymce has an image upload but for online images. Furthermore, the uploading of images from local system is an advanced feature of tinymce, needs to be bought. So, is there a free plugin I can use to integrate uploading of images from local system to tinymce? Thanks! :)
You could write an own plugin and insert your images as a base64-encoded string.
Example: You will need to fetch a javascript function from the web and create the string my_image_base64_string (already given here). The snippet shows howto insert the image afterwards. Using an own plugin you will be able to create a button and use for example a popup.
var my_image_base64_string = 'R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';
tinymce.activeEditor.execCommand('insertHTML', false, '<img src="data:image/gif;base64,' + my_image_base64_string + '" width="16" height="14">');
I have created a plugin on Github Which allow you to upload image and as a embed , after that image will automatically converted to Base64 data string the plugin is found on the link below:
https://github.com/buddyexpress/bdesk_photo
You can create custom button:
tinymce.init({
selector: `#${this.props.id}`,
...
toolbar: '... uploadimage ...',
paste_data_images: true,
setup:
...
editor.addButton('uploadimage', {
text: '',
icon: 'image',
onclick: this.uploadImage,
});
},
})
And uploadImage function:
uploadImage() {
var editor = tinymce.activeEditor;
// create input element, call modal dialog w
var fileInput = document.createElement('input');
fileInput.setAttribute('type', 'file');
fileInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
// if file is submitted run our key code
fileInput.addEventListener('change', () => {
if (fileInput.files != null && fileInput.files[0] != null) {
// create instance of FileReader()
let reader = new FileReader();
// create event triggered after successful reading operation
reader.onload = (e) => {
// insert content in TinyMCE
editor.insertContent('<img src="' + e.target.result + '">');
fileInput.value = '';
};
reader.readAsDataURL(fileInput.files[0]);
}
});
fileInput.click()
}
After this you should see your base64 image in the editor.