receive data from arrayBuffer by using XTK - arraybuffer

I'm trying to use XTK to load DICOM files, by using the following code:
var _dicom = ['1','2','3']
volume.file = _dicom.sort().map(function(v) {
return 'data/path/' + v + '.DCM';
});
The Output:
is an arrayBuffer
I would like to know how to read the arrayBuffer and render it. I tried volume.filedata = dataFromArrayBuffer, but it does not work.

Related

Saxon CS: transform.doTransform cannot find out file from first transformation on windows machine but can on mac

I am creating an azure function application to validate xml files using a zip folder of schematron files.
I have run into a compatibility issue with how the URI's for the files are being created between mac and windows.
The files are downloaded from a zip on azure blob storage and then extracted to the functions local storage.
When the a colleague runs the transform method of the saxon cs api on a windows machine the method is able to run the first transformation and produce the stage 1.out file, however on the second transformation the transform method throws an exception stating that it cannot find the file even though it is present on the temp directory.
On mac the URI is /var/folders/6_/3x594vpn6z1fjclc0vx4v89m0000gn/T and on windows it is trying to find it at file:///C:/Users/44741/AppData/Local/Temp/ but the library is unable to find the file on the windows machine even if it is moved out of temp storage.
Unable to retrieve URI file:///C:/Users/44741/Desktop/files/stage1.out
The file is present at this location but for some reason the library cannot pick it up on the windows machine but it works fine on my mac. I am using Path.Combine to build the URI.
Has anyone else ran into this issue before?
The code being used for the transformations is below.
{
try
{
var transform = new Transform();
transform.doTransform(GetTransformArguments(arguments[Constants.InStage1File],
arguments[Constants.SourceDir] + "/" + schematronFile, arguments[Constants.Stage1Out]));
transform.doTransform(GetTransformArguments(arguments[Constants.InStage2File], arguments[Constants.Stage1Out],
arguments[Constants.Stage2Out]));
transform.doTransform(GetFinalTransformArguments(arguments[Constants.InStage3File], arguments[Constants.Stage2Out],
arguments[Constants.Stage3Out]));
Log.Information("Stage 3 out file written to : " + arguments[Constants.Stage3Out]);;
return true;
}
catch (FileNotFoundException ex)
{
Log.Warning("Cannot find files" + ex);
return false;
}
}
private static string[] GetTransformArguments(string xslFile, string inputFile, string outputFile)
{
return new[]
{
"-xsl:" + xslFile,
"-s:" + inputFile,
"-o:" + outputFile
};
}
private static string[] GetFinalTransformArguments(string xslFile, string inputFile, string outputFile)
{
return new[]
{
"-xsl:" + xslFile,
"-s:" + inputFile,
"-o:" + outputFile,
"allow-foreign=true",
"generate-fired-rule=true"
};
}```
So assuming the intermediary results are not needed as files but you just want the result (I assume that is the Schematron schema compiled to XSLT) you could try to run XSLT 3.0 using the API of SaxonCS (using Saxon.Api) by compiling and chaining your three stylesheets with e.g.
using Saxon.Api;
string isoSchematronDir = #"C:\SomePath\SomeDir\iso-schematron-xslt2";
string[] isoSchematronXslts = { "iso_dsdl_include.xsl", "iso_abstract_expand.xsl", "iso_svrl_for_xslt2.xsl" };
Processor processor = new(true);
var xsltCompiler = processor.NewXsltCompiler();
var baseUri = new Uri(Path.Combine(isoSchematronDir, isoSchematronXslts[2]));
xsltCompiler.BaseUri = baseUri;
var isoSchematronStages = isoSchematronXslts.Select(xslt => xsltCompiler.Compile(new Uri(baseUri, xslt)).Load30()).ToList();
isoSchematronStages[2].SetStylesheetParameters(new Dictionary<QName, XdmValue>() { { new QName("allow-foreign"), new XdmAtomicValue(true) } });
using (var schematronIs = File.OpenRead("price.sch"))
{
using (var compiledOs = File.OpenWrite("price.sch.xsl"))
{
isoSchematronStages[0].ApplyTemplates(
schematronIs,
isoSchematronStages[1].AsDocumentDestination(
isoSchematronStages[2].AsDocumentDestination(processor.NewSerializer(compiledOs)
)
);
}
}
If you only need the compiled Schematron to apply it further to validate an XML instance document against that Schematron you could even store the Schematron as an XdmDestination whose XdmNode you feed to XsltCompiler e.g.
using Saxon.Api;
string isoSchematronDir = #"C:\SomePath\SomeDir\iso-schematron-xslt2";
string[] isoSchematronXslts = { "iso_dsdl_include.xsl", "iso_abstract_expand.xsl", "iso_svrl_for_xslt2.xsl" };
Processor processor = new(true);
var xsltCompiler = processor.NewXsltCompiler();
var baseUri = new Uri(Path.Combine(isoSchematronDir, isoSchematronXslts[2]));
xsltCompiler.BaseUri = baseUri;
var isoSchematronStages = isoSchematronXslts.Select(xslt => xsltCompiler.Compile(new Uri(baseUri, xslt)).Load30()).ToList();
isoSchematronStages[2].SetStylesheetParameters(new Dictionary<QName, XdmValue>() { { new QName("allow-foreign"), new XdmAtomicValue(true) } });
var compiledSchematronXslt = new XdmDestination();
using (var schematronIs = File.OpenRead("price.sch"))
{
isoSchematronStages[0].ApplyTemplates(
schematronIs,
isoSchematronStages[1].AsDocumentDestination(
isoSchematronStages[2].AsDocumentDestination(compiledSchematronXslt)
)
);
}
var schematronValidator = xsltCompiler.Compile(compiledSchematronXslt.XdmNode).Load30();
using (var sampleIs = File.OpenRead("books.xml"))
{
schematronValidator.ApplyTemplates(sampleIs, processor.NewSerializer(Console.Out));
}
The last example writes the XSLT/Schematron validation SVRL output to the console but could of course also write it to a file.

jsPDF get the generated document as base64

I´m trying to generate a PDF on my application, using something like this, from documentation:
var doc = new jsPDF();
doc.html(document.body, {
callback: function (doc) {
doc.save();
}
});
But what I need is to get this generated file, as a base64 content, to send as an attachment on an email. Is there a way to get this directly on callback?
It's worth noting that the datauri option changes the document location, see the following snippet from jsPDF lib:
case 'datauri':
case 'dataurl':
return global.document.location.href = datauri;
This is fine unless you are trying to use an IFrame, as it would cause its body to be replaced by an embed tag displaying the pdf just generated.
Instead, the safest option is to use datauristring as this simply returns the pdf in a base64 string:
var pdf = new jsPDF('p', 'pt', 'a4');
var base = pdf.output('datauristring'); // base64 string
console.log("base64 is ", base);
Honestly, I don't know why anybody would want to use the datauri option instead of datauristring as latter's behaviour it's what most people expect anyway.
You can do like below.
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.html(document.getElementById('doc'), {
callback: function (pdf) {
// example text
pdf.text(20, 20, 'Hello world!');
pdf.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
var base = pdf.output('datauri'); // directly to base664
console.log("base64 is ");
console.log(base);
// you can generate in another format also like blob
var out = pdf.output('blob');
var reader = new FileReader();
reader.readAsDataURL(out);
reader.onloadend = function() { // for blob to base64
base64data = reader.result;
console.log("base64 data is ");
console.log(base64data );
}
pdf.save('DOC.pdf');
}
})
You can see more on output() method in the following link.
jspdf output() source code

PDFJS and PDF encoding

We are implementing PDFJS to render pdf files on a website.
When trying to initiate a PDFdocument/Viewer as an arrayBuffer, we get al sorts of errors and the file is not rendered.
When opening the same file in the viewer from url (DEFAULT_URL variable), the file renders fine.
There are however some files that do render as streams. Comparing these files in notepad shows they have different encoding/characters.
This piece of code is used to open the file in the viewer:
function rawStringToBuffer( str ) {
var idx, len = str.length, arr = new Array( len );
for ( idx = 0 ; idx < len ; ++idx ) {
arr[ idx ] = str.charCodeAt(idx) & 0xFF;
}
return new Uint8Array( arr ).buffer;
}
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
var uint8array = rawStringToBuffer(contents);
pdfjsframe.contentWindow.PDFViewerApplication.open(uint8array,0);
};
reader.readAsText(file);
}
test.pdf helloworld pdf which is not rendered with code above.
test2.pdf helloworld pdf which does rendered with code above.
The behaviour is not browser dependent. The build is b15f335.
Is there something with the code or default configuration of the viewer so that test.pdf can not be rendered by the viewer?
I don't think that your string conversion routine rawStringToBuffer() does what you want. You are reading the file as text, which transforms UTF-8 to UTF-16. But rawStringToBuffer() just takes the low order byte of each UTF-16 character and discards the high order byte, which is not the inverse transform. This will work with 7-bit ASCII data, but not with other characters. The best way to convert a string to UTF-8 is with the TextEncoder API (not supported on all browsers but polyfills are available).
However, converting the data from UTF-8 and back again is unnecessary. Just use FileReader.readAsArrayBuffer() instead of readAsText() to produce your ArrayBuffer directly.
Here's an (untested) replacement function:
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
pdfjsframe.contentWindow.PDFViewerApplication.open(contents, 0);
};
reader.readAsArrayBuffer(file);
}

PDFJS.getDocument not working and not throwing an error

It's not going into the .then afterwards, and it's not throwing any error.
Here's my calling code:
function loadPage(base64Data, pageIndex) {
var pdfData = base64ToUint8Array(base64Data);
// this gets hit
PDFJS.getDocument(pdfData).then(function (pdf) {
// never gets here
pdf.getPage(pageIndex).then(function (page) {
var scale = 1;
var viewport = page.getViewport(scale);
var canvas = document.getElementById('pdfPage');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({ canvasContext: context, viewport: viewport });
});
});
}
function base64ToUint8Array(base64) {
var raw = atob(base64); // convert base 64 string to raw string
var uint8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
}
At one point it worked. When I step through it in the debugger, I can step into PDFJS.getDocument but that's way over my head.
My base64Data looks like JVBERi0x...g==. It's a base64 encoded pdf document.
To solve this, I had to add
PDFJS.disableWorker = true;
to the beginning of my loadPage function.
From View PDF files directly within browser using PDF.js,
PDF.js uses Web Workers concept of HTML5 internally to process the
request. If this statement is set to false, it creates an instance of
Web workers. Web Workers run in an isolated thread. For more
information on web workers; please refer
http://www.html5rocks.com/en/tutorials/workers/basics/
Promise is missing in your code. Here how i fixed this probelm:
PDFJS.getDocument(pdfData).promise.then(function (pdf) {
// do your stuff
});

Make picture from base64 on client-side

How to make a picture from a base64-string to send it to server by using HttpRequest.request?
For example, I have the following base64-string:
'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
Instead of sending it I would like to post a jpeg to server? Is it possible?
Convert Base64 to bytes
How to native convert string -> base64 and base64 -> string
Upload binary as image
Dart how to upload image
EDIT
(this is the server part, I have to look for the client part)
Client code:
var request = new HttpRequest()
..open("POST", 'http://yourdomain.com/yourservice')
..overrideMimeType("image/your-imagetype") // might be that this doesn't work than use the next line
..setRequestHeader("Content-Type", "image/your-imagetype")
..onProgress.listen((e) => ...);
request
..onReadyStateChange.listen((e) => ...)
..onLoad.listen((e) => ...)
..send(yourBinaryDataAsUint8List);
Convert to image:
I think you need to create a dataURL like show here How to upload a file in Dart?
and then use the created dataUrl as src in code like shown here How to load an image in Dart
see also Base64 png data to html5 canvas as #DanFromGermany mentioned in his comment on the question.
It may be necessary to convert List to Uint8List in between.
Please add a comment if you need more information.
I like decoding on server-side, but anyways.
Basically you just split a text you got from canvas.toDataUrl(), convert the Base64 text to binary data, then send it to server. Use "CryptoUtils" in "crypto" library to treat Base64. I haven't tested with any proper http server, but this code should work.
// Draw an on-memory image.
final CanvasElement canvas = document.createElement('canvas');
canvas.width = 256;
canvas.height = 256;
final CanvasRenderingContext2D context = canvas.getContext('2d');
final CanvasGradient gradient = context.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(0, "#1e4877");
gradient.addColorStop(0.5, "#4584b4");
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(10, 10);
context.lineTo(240, 240);
context.lineWidth = 10;
context.strokeStyle = '#ff0000';
context.stroke();
// Convert the image to data url
final String dataUrl = canvas.toDataUrl('image/jpeg');
final String base64Text = dataUrl.split(',')[1];
final Uint8ClampedList base64Data = new Uint8ClampedList.fromList(
CryptoUtils.base64StringToBytes(base64Text));
// Now send the base64 encoded data to the server.
final HttpRequest request = new HttpRequest();
request
..open("POST", 'http://yourdomain.com/postservice')
..onReadyStateChange.listen((_) {
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print("onReadyStateChange: " + request.responseText); // output the response from the server
}
})
..onError.listen((_) {
print("onError: " + _.toString());
})
..send(base64Data);
I posted a complete snippet here. https://gist.github.com/hyamamoto/9391477
I found the Blob conversion part not to be working (anymore?).
The code from here does work:
Blob createImageBlob(String dataUri) {
String byteString = window.atob(dataUri.split(',')[1]);
String mimeString = dataUri.split(',')[0].split(':')[1].split(';')[0];
Uint8List arrayBuffer = new Uint8List(byteString.length);
Uint8List dataArray = new Uint8List.view(arrayBuffer.buffer);
for (var i = 0; i < byteString.length; i++) {
dataArray[i] = byteString.codeUnitAt(i);
}
Blob blob = new Blob([arrayBuffer], mimeString);
return blob;
}

Resources