Decrypt PDF file on client side and view with pdf.js - encryption

I'm working on a project that all pdf files are encrypted on Web Server.
With XMLHttpRequest I get content of the encrypted pdf file. Then with JavaScript tools I decrypt the file. After all assign the content of file to a javascript variable as decrypted_file. All this is done at client side.
Here is what i want to do;
pdf.js renders and views pdf file that is located on web server or the same directory base.
How could I handle pdf.js to get content from javascript variable not url as "http//yourdomain.com/first-test.pdf or file as "first-test.pdf"?
Any answers are welcome, thank you.

Assuming that you are using the viewer.html of PDF.js, opening a PDF file from data is as easy as calling PDFViewerApplication.open with the right parameters.
Example: Typed arrays (Uint8Array / ArrayBuffer / ..)
// in viewer.html
var data = new Uint8Array( /* ... data ... */ );
PDFViewerApplication.open(data);
Example: Blob / File objects
// in viewer.html
var data = new Blob([ '%PDF....'] , {type: 'application/pdf'});
var url = URL.createObjectURL(data);
PDFViewerApplication.open(url);
Example: data URL (if supported by browser)
var url = 'data:application/pdf;base64,....';
PDFViewerApplication.open(url);
Example: data URL (any browser)
This consists of two steps: Decoding the base64 data-URL, and then converting the binary string to an Uint8Array.
var url = 'data:application/pdf;base64,....';
var data = url.split(';base64,')[1];
// Decode base64
var binaryString = atob(data);
// Convert binary string to Uint8Array
data = new Uint8Array(binaryString.length);
for (var i = 0, ii = binaryString.length; i < ii; ++i) {
data[i] = binaryString.charCodeAt(i);
}
PDFViewerApplication.open(data);
Example: Using PDF.js in a frame
<iframe src="viewer.html" id="pdfjsframe"></iframe>
<script>
var pdfjsframe = document.getElementById('pdfjsframe');
// At the very least, wait until the frame is ready, e.g via onload.
pdfjsframe.onload = function() {
var data = ... data here or elsewhere ... ;
pdfjsframe.contentWindow.PDFViewerApplication.open(data);
};
</script>

Related

Using kendo.saveAs to download an excel or csv file from an action method

I have a Kendo Grid. I'm using a jquery AJAX call to send data from the Grid to an Action method for processing. Ok fine, no problem there. So after the processing of the data i now want to down either an excel file or csv file (which are basically the same thing). But Jquerys AJAX method doesn't allow Action method to return files like (an excel file). I had figured out another way to do this using
window.location.href = "Controller/Actionmethod/MethodName?" + parameters
But this was a no go as my boss wants it all in one Action Method, not two..
So now introduce this into the success call back of my AJAX call:
kendo.saveAs({
dataURI: data.file,
fileName: "PayrollExport.csv"
});
And here is my code for building the csv file which works fine.
var export = Fundraisers.ProcessPledgeCardUltiproExport().Where(t => FundraiserIDs.Contains(t.FundraiserID)).ToList();
var csv = new StringBuilder();
csv.AppendLine(String.Format("Employee Number, Deduction code, Benefit Status, Coverage Start, Deduction Start Date, Employee Amount"));
foreach (var e in export)
{
var newLine = String.Format("{0},{1},{2},{3},{4:d},{5}", e.EmployeeID, "UW", "A", "", new DateTime(DateTime.Now.Year + 1, 1, 1), e.PledgeAmount);
csv.AppendLine(newLine);
}
var byteArray = Encoding.ASCII.GetBytes(csv.ToString());
var stream = new MemoryStream(byteArray);
Now my question is: How do i return this from the action method.?
All i have as of right now is return Json(new { success = true, file = stream });
An example of what i would need that works for a PDF file is something along the line of:
return Json(new { success = true, message = "Verified!", file = "data:text/html;base64," + Convert.ToBase64String(fileContent) });
Any idea on the what i should put in the return for the posted above code after creating the csv file?
Any help would be much appreciated.

How to read a local json file and display

newbie here,I could not find any example on Xamarin Forms read a local json file and display it. I need to do a local testing to read the local Json file.
1) Where do I save the json file for reading? in Android and iOS Projects or just in PCL project?
2) How to read the file?
here the code but it is not complete as I dont how to read the file.
using (var reader = new System.IO.StreamReader(stream))
{
var json = reader.ReadToEnd();
var rootobject = JsonConvert.DeserializeObject<Rootobject>(json);
whateverArray = rootobject.Whatever;
}
The code miss the Path and others which required.
You can directly add your JSON file in PCL. Then change build action to Embedded Resource
Now you can read Json data by:
var assembly = typeof("<ContentPageName>").GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("Your_File.json");
using (var reader = new System.IO.StreamReader(stream))
{
var json = reader.ReadToEnd();
var data= JsonConvert.DeserializeObject<Model>(json);
}

Cannot write data into the sqlite db file inside asar archive in electron app

var fs = require('fs');
var SQL = require('sql.js');
var filebuffer = fs.readFileSync('./resources/app.asar/app/data/sample.db');
var db = new SQL.Database(filebuffer);
function save_data(){
var name=document.getElementById('name').value;
var ip=document.getElementById('serverip').value;
var result=db.each("UPDATE Settings SET Name=$name, IP=$ip WHERE SettingsId=$set",{$name:name,$ip : ip,$set:1},function(row){console.log(row.name)});
var data = db.export();
var buffer = new Buffer(data);
fs.writeFileSync('./resources/app.asar/app/data/sample.db', buffer);
}
I was able to read the data from the database file inside the asar archive, but while writing the data into db file, it doesn't gets updated inside asar archive. So please help me crack this issue.
Asar is a read-only archive. It just concatenates all the files together into a single blob.

Azure blob file download link

I have a blob which I've stored in Azure blob storage (using the development emulator).
Its all saved and I can see it in the server explorer in the blob store (file.mp3 if that matters).
I'm then linking to it in my site but when I click the link I'm getting a 206 (partial content) back (and obviously no file). If I right click save as everything is happy and the file downloads.
I'm sure this is something pretty noobish that I'm missing but I cant see it.
That is because, browser does not download media file as whole, browser requests Range for which Blob Storage correctly responds with one byte and with headers. This is called HTTP streaming, where parts of file will be downloaded in ranges and will be played progressively. In this form of streaming you can skip parts of file and go to end to play the end part of media without downloading whole file.
Imagine you are watching a big movie, and that movie is of 100 MB. And you want to watch last One minute of it, you can move player's tracker forward on timeline and browser will only download last few megabytes as per the timeline structure in Media file. Usually MP4 & similar media containers support file byte position tracking.
Browsers & most media players try to stream the media file if possible.
You can try following download attribute,
Reference: http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download
download me
You can try following code, from this answer, Reference: Chrome extension: How to save a file on disk
var url = window.webkitURL || window.URL || window.mozURL || window.msURL;
var a = document.createElement('a');
a.download = 'MyHangouts-MomentCapture.jpg';
a.href = url.createObjectURL(dataURIToBlob(data.active, 'jpg'));
a.textContent = 'Click here to download!';
a.dataset.downloadurl = ['jpg', a.download, a.href].join(':');
/**
* Converts the Data Image URI to a Blob.
*
* #param {string} dataURI base64 data image URI.
* #param {string} mimetype the image mimetype.
*/
var dataURIToBlob = function(dataURI, mimetype) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
var bb = new this.BlobBuilder();
bb.append(uInt8Array.buffer);
return bb.getBlob(mimetype);
};

How to access the properties and parts of an SSRS report at runtime

I'm using the ReportViewer control to display a server report in an ASP.NET page and I'm looking for a way to get the report into an object that I can then read and/or modify.
This kind of thing:
var rw = report.Width;
var t = ((Chart)report.Body.Item[3]).Title;
Is there a way, or am I stuck with parsing the XML file?
ETA:
I'm beginning to think I will need to access the XML file but I can't find out how to download that from the server, modify it (in memory) and then send it to the ReportViewer control.
ETA2:
Here's how to download the report definition (clean up left out for brevity):
// Download the report
var rs = new ReportingService2010();
rs.UseDefaultCredentials = true;
var reportDefinition = rs.GetItemDefinition("/DashboardReports/MyChart");
// Convert to XML
var ms = new MemoryStream(reportDefinition);
var doc = new System.Xml.XmlDocument();
doc.Load(ms);
// To load the stream into the report viewer
stream.Position = 0; // needed because we used the stream above - doc.Load(ms)
this.ReportViewer1.ServerReport.LoadReportDefinition(stream);

Resources