How to prevent blob + guid in browser title - javascript

Basically, what I am doing is generating a PDF file on the server and showing it in the browser via javascript like this:
file = new window.Blob([data], { type: 'application/pdf' });
var fileUrl = URL.createObjectURL(file);
var wnd = window.open(fileUrl, "_blank", "location=no, fullscreen=yes, scrollbars=auto, width=" + screen.width + ",height=" + screen.height);
All this works fine but every browser is showing an ugly subtitle (something like this): blob:2da57927-311e-4b3d-a261-d2679074802c
Is there any way to get rid of this subtitle or to replace it with something meaningful?
Edited:
Here is a screen capture of the improved code (after applying VisioN's suggestion):

As I mentioned in the comments, one possible way is to make an <iframe> in the popup window, that displays the current Blob data, and to style the popup as you wish:
var win = open('', 'name', 'height=300, width=300'),
iframe = document.createElement('iframe'),
title = document.createElement('title'),
file = new Blob([data], { type: 'application/pdf' }),
fileUrl = URL.createObjectURL(file);
title.appendChild(document.createTextNode('Nice title :)'));
iframe.src = fileUrl;
iframe.width = '100%';
iframe.height = '100%';
iframe.style.border = 'none';
win.document.head.appendChild(title);
win.document.body.appendChild(iframe);
win.document.body.style.margin = 0;
DEMO: http://jsfiddle.net/MeY9e/

You can simply add a settimeout to change the page title after the blob has been loaded in the new tab like this -
newTab.location.href = URL.createObjectURL(blob);
setTimeout(function() {
newTab.document.title = blob.name;
}, 10);

Related

How can I send a copy of a user generated png to my backend?

I am building a site that allows users to create customized graphics and then download them directly from the page.
I am doing this via the user customizing an svg via a javascript powered form which is then made into a PNG before downloading.
However, now I want to store a copy of the png that the user created so that I can display it on the site's home page. What is the best way to store a copy of the dynamically created graphic? AJAX? HTTP Request? Both are very foreign topics to me so I am unsure how to go about it from here.
For reference here is the code that builds the PNG from the svg and then triggers the download for the user.
var svg = document.getElementById("bg2");
var canvas = document.querySelector("canvas");
function triggerDownload (imgURI) {
var evt = new MouseEvent('click', {
view: window,
bubbles: false,
cancelable: true
});
if(document.getElementById("name").value=="null" || document.getElementById("name").value=="") {
var un = "MakeAGraphic";
} else {
var enteredName = document.getElementById("name").value.replace(/[^a-zA-Z ]/g, "");
var un = `${enteredName}_MakeAGraphic`
}
var a = document.createElement('a');
a.setAttribute('download', `${un}.png`);
a.setAttribute('href', imgURI);
a.setAttribute('target', '_blank');
a.dispatchEvent(evt);
}
btn.addEventListener('click', function () {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = (new XMLSerializer()).serializeToString(svg);
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svgBlob);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
var imgURI = canvas
.toDataURL('image/png')
.replace('image/png', 'image/octet-stream');
triggerDownload(imgURI);
};
img.src = url;
});
agree to that answer mentioned by #showdev .
Call
canvas.toBlob(callback, mimeType, qualityArgument);
then call
formData.append("an-image", blob);
then upload formData using the AJAX or fetch API.
see the documents at
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

How to Download a PDF file in the background

How do I download a file in the background of a mobile browser without leaving the current page.
I've taken a look at this StackOverflow post: easiest way to open a download window without navigating away from the page
which works for displaying the file( in this case a pdf) in the same window using this code:
var file_path = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
This works fine if you want to display the PDF immediately in the current window.
However, how can you keep the current view and have the file download/display a dialogue showing a download in progress?
The goal is to not open a new tab or window to keep the user engaged with the current page. I've looked through S/O & on the web but haven't found a solution to this. Thanks for any solutions to this issue.
you can use HTML web worker https://www.w3schools.com/html/html5_webworkers.asp
var w;
function stopWorker() {
w.terminate();
w = undefined;
}
function downloadPDFBackground() {
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("pdf_workers.js");
}
w.onmessage = function(event) {
var file_path = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
stopWorker();
};
} else {
document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
}
}

open image in new window blank page appearing javascript

after taking the reference from this answer
Open image in new window
i did the the same code.
function openImage() {
var largeImage = document.getElementById('viewImage');
largeImage.style.display = 'block';
largeImage.style.width = 200 + "px";
largeImage.style.height = 200 + "px";
var url = largeImage.getAttribute('src');
window.open(url, 'Image', 'width=largeImage.stylewidth,height=largeImage.style.height,resizable=1');
}
but when this function executed, blank page is showing
when i view image src in console, it is showing proper data.
my img element is also showing me image properly,
but this is how my page is being shown
what do you think what is wrong in my code?
That solution is for image with actual url as src, in your case image src is a base64 encoded string not url.
Base64 support for Window.open is not same across all browsers, it works on firefox but it won't work on chrome and IE.
So, you can try this instead
function openImage() {
var largeImage = document.getElementById('viewImage');
largeImage.style.display = 'block';
largeImage.style.width = 200 + "px";
largeImage.style.height = 200 + "px";
var w = window.open("");
w.document.write(largeImage.outerHTML);
}

Open inline SVG in new window - Javascript

I have a <div> that contains an inline svg. I would like a function that opens that svg in a new tab/window. I only want to use the front-end js without having to save the svg anywhere.
If I use window.open(), it puts the svg inside an <html> tag which I'm trying to avoid.
I'm basically trying to change this answer but then only have the svg code left:
https://stackoverflow.com/a/21667339/1083923
//---print button---
var printSVG = function()
{
var popUpAndPrint = function()
{
var container = $('#svgDiv');
var width = parseFloat(container.getAttribute("width"))
var height = parseFloat(container.getAttribute("height"))
var printWindow = window.open('', 'PrintMap',
'width=' + width + ',height=' + height);
printWindow.document.writeln($(container).html());
printWindow.document.close();
printWindow.print();
printWindow.close();
};
setTimeout(popUpAndPrint, 500);
};
You can stringify your element into a valid SVG document and store it as a Blob, then point your new Window to that Blob using a blob:// URI:
// we need to handle a user gesture to use 'open'
document.getElementById("btn").onclick = (evt) => {
// grab your svg element
const svg = document.querySelector("svg");
// convert to a valid XML source
const as_text = new XMLSerializer().serializeToString(svg);
// store in a Blob
const blob = new Blob([as_text], { type: "image/svg+xml" });
// create an URI pointing to that blob
const url = URL.createObjectURL(blob);
const win = open(url);
// so the Garbage Collector can collect the blob
win.onload = (evt) => URL.revokeObjectURL(url);
};
JS-fiddle demo since StackSnippet's sand-boxed iframes don't allow opening new windows.

Save high-res image html5/threejs-canvas

I found and edited below code to save my html5 canvas as a .png-image. The canvas is generated by Three.js/Potree.
This code works perfectly. But, I want a higher resolution image as an output. Usually, the THREEjs renderer is sized according to the clients browser size. I have already manually enlarged it to 3000x2000. This edit will give a higher-resolution image, but when increasing more no effects are visible anymore.
Is there a simple (I'm not that into javascript..) workaround for downloading a high-resolution output image?
At first, the images are just for me. No user needs to download it or needs to pass it onto the server. Although, if its a neat solution, I'd like to give the user the possibility to save their image as well.
function saveAsImage() {
var strDownloadMime = "image/octet-stream";
//alert("function saveimage")
var imgData, imgNode;
try {
var strMime = "image/png";
imgData = viewer.renderer.domElement.toDataURL(strMime);
saveFile(imgData.replace(strMime, strDownloadMime), "test.png");
} catch (e) {
console.log(e);
return;
}
}
var saveFile = function (strData, filename) {
//alert("savefilefunction");
var link = document.createElement('a');
if (typeof link.download === 'string') {
document.body.appendChild(link); //Firefox requires the link to be in the body
link.download = filename;
link.href = strData;
link.click();
document.body.removeChild(link); //remove the link when done
} else {
location.replace(uri);
}
}
THREE Renderer settings:
let width = 3000;
let height= 2000;
this.renderer = new THREE.WebGLRenderer({premultipliedAlpha: false, preserveDrawingBuffer: true});
this.renderer.setSize(width, height);

Categories

Resources