I generated html file from base64 format using javascript after that i'm open that file in new tab , and i did that with succes , now i would like to apply stylesheet on my file.
here is my code to generate and open the file :
//s_utf8String is result of the content that i use to generate the file.
var binary = atob(a.s_utf8String.replace(/\s/g, ''));
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++)
{
view[i] = binary.charCodeAt(i);
}
var blob = new Blob([view], {type: "application"});
var url = URL.createObjectURL(blob);
window.open(url);
Any one have an idea how i can add the stylesheet
Related
I am getting the response from rest api as:
<Response>
<PDFContent>SlZCRVJpMHhMalFLSmVMano5TUtNU0F3SUc5aWFnbzhQQzlUTDBwaGRtRlRZM0pwY0hRdlNsTW9kR2hwY3k1NmIyOXRJRDBnTVRBd095aytQZ3BsYm1Sdlltb0tOU0F3SUc5aWFnbzhQQzlEYjJ4dmNsTndZV05sTDBSbGRtbGpaVWR5WVhrdlUzVmlkSGx3WlM5SmJXRm5aUzlJWldsbmFIUWdNVFV3TDBacGJIUmxjaTlHYkdGMFpVUmxZMjlrWlM5VWVYQmxMMWhQWW1wbFkzUXZWMmxrZEdnZ056Y3lMMHhsYm1kMGFDQTNNek0zTDBKcGRITlV3cjFTdkgvd0JvNy9rbm1uLzloV1AvQU5GUzBBZUFmOEozNHcvNkd2WFAvQmpOL3dERlVmOEFDZCtNUCtocXhycFg5L2V5ZlRZRURvYTRmdUNBNWNDQjFVSjJEd005cWwyZE9LbzlOSDVhVXdkdjVTVFRYbkMwVWVZbnlyVE5N6bnRLaXRSWHV1REUxUHNSL2lGQ2FpdGhvTUlacGQ0NmxMU0d3aVdZSkZoVVVaRm5KbnN5NHpPWE9BZS94ZDEIyOTBJREl6SURBZ1VpOVRhWHBsSURJMVBqNEtjM1JoY25SNGNtVm1DakUzT1RjMU5Rb2xKVVZQUmdvPQ==</PDFContent>
<Success>True</Success>
</Response>
How to get the response inside and generate pdf using React js
you can simply add in object tab in reactjs
<div>
<object
style={{width: '100%', height: '200pt'}}
type="application/pdf"
data={'data:application/pdf;base64,'+base64data}></object>
</div>
I am assuming the bytes within <PDFContent> tag are base64 encoded bytes of the PDF file. If this is incorrect, you need to update your REST API to perform base64 encoding on the PDF bytes first. You can't have your server send raw PDF bytes to the web client as is.
In the javascript, once you have received the base64 encoded PDF bytes, you can generate the PDF in two steps:
Convert the base64 encoded bytes to a PDF BLOB.
Create a file URL out of this BLOB and open the URL.
Here's a sample JavaScript code for the same:
<script>
function displayPDF() {
//The PDFContent bytes are mapped to an input element called pdfString
if($('#pdfString').val() == '')
return;
var file = b64toBlob($('#pdfString').val(), 'application/pdf');
//If the browser is IE or Edge
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file);
}
else {
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
}
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
</script>
I'm trying to pass a PDF file from the server and display it inside the browser, but the output comes out corrupted.
var blob = atob(data.Package);
console.log(blob);
var file = new Blob([blob], { type: "application/pdf" });
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
Console log outputs something that appears to be correct PDF (just the beginning of output):
I'm saving a copy of the PDF on the server before transfer to make sure it is not corrupt and it works.
URL constructed with URL.createObjectURL(file) seems to be short:
blob:http://localhost:61631/ad749684-2992-4311-8b17-f382a7c687be
server side code:
Object doc = Convert.ToBase64String(_Document.DocumentStream.ToArray());
JObject response = new JObject(new JProperty("Package", JObject.FromObject(doc)));
return new AspResponse<Object>(response);
It looks like the issue is because you need to convert the PDF data into an actual byte array, then pass that into the Blob constructor. Try this:
function convertToByteArray(input) {
var sliceSize = 512;
var bytes = [];
for (var offset = 0; offset < input.length; offset += sliceSize) {
var slice = input.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
bytes.push(byteArray);
}
return bytes;
}
var blob = atob(data.Package);
console.log(blob);
var file = new Blob(convertToByteArray(blob), { type: "application/pdf" });
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
This solution worked for me, basically generating the pdf as a base64 string in the backend and rendering the content in an anchor tag for downloading the pdf file.
https://kainikhil.medium.com/nodejs-how-to-generate-and-properly-serve-pdf-6835737d118e
I'm using a webservice to get a base64 string and I need to show that document to the user as a PDF.
var charactersArray = atob(base64String);
var byteNumbers = new ArrayBuffer(charactersArray.length);
for (var i = 0; i < charactersArray.length; i++) {
byteNumbers[i] = charactersArray.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var file = new File([byteArray], "file.pdf", {
type: "application/pdf",
});
I'm then using this "file" to create a url with
var url = URL.createObjectURL(file);
I'm opening this url in a button with the ng-click directive, but I'm getting loading the PDF.
You need to write the character codes to the byteArray rather than the ArrayBuffer
var charactersArray = atob(base64String);
var len = charactersArray.length;
var byteNumbers = new ArrayBuffer(len);
var byteArray = new Uint8Array(byteNumbers);
for (var i = 0; i < len; i++) {
byteArray[i] = charactersArray.charCodeAt(i);
}
var file = new File([byteArray], "file.pdf", {
type: "application/pdf",
});
I recently work on a project like this and had the same issue. I used the base64-arraybuffer NPM library to convert a base64 string to a byte array.
It's a JS library so it needs to be imported like this after it's installed:
import * as buffer from 'base64-arraybuffer';
The object URL is created like this:
var byteArray = buffer.decode(base64String);
var file = new Blob([byteArray], {type: 'application/pdf'});
var pdfUrl = URL.createObjectURL(file);
I hope this helps!
I have a function that is loading a user selected file using the Javascript File API, but I want to limit the type of file that can be loaded. Is this possible and how do I go about doing it? So for example, I only want the user to be able to load a DAT file. Here's my function loading the file.
function readFile(file){
var reader = new FileReader();
var holder;
var holderArray = [];
var fileArray = [];
reader.readAsText(file, "UTF-8");
reader.onload = function(){
file = reader.result;
file = file.split(/\s+/g);
formatFile(holderArray, 3, holder, file, fileArray);
for(var i = 0; i < 2; i++){
formatFile(holderArray, 1, holder, file, fileArray);
}
for(var i = 0; i < 2; i++){
formatFile(holderArray, 2, holder, file, fileArray);
}
var meh = file.length / fileArray.length;
for(var i = 0; i < meh; i++){
formatFile(holderArray, 5, holder, file, fileArray);
}
fileArray.pop();
plume = new Plume(fileArray[0], fileArray[4], fileArray[3]);
$("#eventDate").val(plume.dateTime);
$("#eventLat").val(plume.startLat);
$("#eventLon").val(plume.startLong);
$("#eventDictionary").val(plume.dict);
$("#eventSymbol").val(plume.symbol);
fileArray = fileArray.splice(5);
plume.graphic = fileArray;
}
}
$("#load").on("click", function(){
$("#eventNameInput").val("");
var selectedFile = $("#selectedFile");
selectedFile = selectedFile[0].files[0];
if(selectedFile){
readFile(selectedFile);
$("#fileDetails").show();
}
})
Sure. You can declare MIME type in "accept" attribute For example this input will upload images :
<input type="file" name="img" accept="image/*">
for .dat you can do this (.dat is unknown MIME type):
<input type="file" name="img" accept=".dat">
I'm using flash to capture audio, encode it to mp3, then send it to javascript as ByteArray.
Now I want the javascript to save it as MP3 on my computer (not flash saves it to my computer). I am using Blob and then getDataURL, but the file isn't playing when saved. I used to do the same exact method to save WAV files and it worked perfectly fine.
Here's the JS code:
var getDataFromSWF = function (bytes) {
var myBlob = new Blob([bytes], { type: "audio/mpeg3" });
var url = (window.URL || window.webkitURL).createObjectURL(myBlob);
var link = window.document.createElement('a');
link.href = url;
// $("label").text(url);
link.download = 'output.mp3';
var click = document.createEvent("Event");
click.initEvent("click", true, true);
link.dispatchEvent(click);
// console.log(bytes);
}
I'm pretty much sure that the byteArray is fine because if I let the SWF save the file it works OK too. But I want to know what's wrong with the JS code. (note: i'm new to BLOB)
Try this to get the Blob
function base64toBlob(base64Data, contentType) {
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}