Render Svg to Pdf using jspdf - svg

I am having trouble in rendering svg element to pdf using jspdf . Iam using plugin https://github.com/CBiX/svgToPdf.js/ to do this.
Below is my code
// I recommend to keep the svg visible as a preview
var tmp = document.getElementById("chartContainer");
var svgDoc = tmp.getElementsByTagName("svg")[0];
var pdf = new jsPDF('p', 'pt', 'a4');
svgElementToPdf(svgDoc, pdf, {
scale: 72 / 96, // this is the ratio of px to pt units
removeInvalid: false // this removes elements that could not be translated to pdf from the source svg
});
pdf.output('datauri'); // use output() to get the jsPDF buffer
It is generarting blank pdf. Please help

You can do that using canvg.
Step1: Get "SVG" markup code from DOM
var svg = document.getElementById('svg-container').innerHTML;
if (svg)
svg = svg.replace(/\r?\n|\r/g, '').trim();
Step 2:
Use canvg to create canvas from svg.
var canvas = document.createElement('canvas');
canvg(canvas, svg);
Step 3:
Create image from canvas using .toDataURL()
var imgData = canvas.toDataURL('image/png');
// Generate PDF
var doc = new jsPDF('p', 'pt', 'a4');
doc.addImage(imgData, 'PNG', 40, 40, 75, 75);
doc.save('test.pdf');
Check the demo here http://jsfiddle.net/Purushoth/hvs91vpq/193/
Canvg Repo: https://github.com/gabelerner/canvg

I've tried both svg2pdf.js and addSvgAsImage using canvg internally.
Both didn't work well for me, the resulting images in the pdf where either incorrectly positioned or displayed.
I've ended up doing the following which works very well:
convert the SVG to PNG without any libraries, see my answer to "Convert SVG to image (JPEG, PNG, etc.) in the browser".
just add the result to the pdf using the normal addImage method

I think the current jspdf version (2.3.1) has an addSvgAsImage method, but it takes the svg as a string. I guess you could use an ajax call to retrieve the SVG content, but I just have the SVG in my code and pass it in that way.

Related

Threejs - How to correctly apply svg texture to .obj file

I've just started playing around with threejs and first thing I'm trying to do is applying textures to models. I am able to load a PNG texture with something like:
var material = new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture('textures/wood.png'),
});
object.material = material;
and it fits perfectly to the 3D model without doing anything else. I assume to have exported the .obj with the correct options (as PNG fits perfectly), so I attempted to create the same texture from an SVG instead.
var canvasElement = document.getElementById('svgTexture');
var img = new Image();
img.onload = function() {
canvasElement.getContext('2d').drawImage(img, 0, 0);
var texture = new THREE.CanvasTexture(
canvasElement,
THREE.UVMapping,
THREE.ClampToEdgeWrapping, THREE.ClampToEdgeWrapping,
THREE.LinearFilter, THREE.LinearFilter,
);
material = new THREE.MeshBasicMaterial({
map: texture
});
}
img.src = 'textures/wood.svg';
Unfortunately, the SVG texture gets loaded but mapping is all messed up. It seems Threejs is able to "use" the exported UVMaps if I do use a PNG, whereas It can't with the SVG.
NOTE: both files are the same texture, with same dimensions. Indeed, the PNG was created right from the SVG with SVG Converter (OS X).

I am having trouble in converting svg to PDF

I am trying to convert SVG to PDF which is working fine but it is returning me a blank PDF. How can i achieve my SVG in pdf?
var doc = new jsPDF('p', 'pt', 'letter');
var test = $.get('/BarCodeSmallTag.svg', function (svgText) {
var svgAsText = new XMLSerializer().serializeToString(svgText.documentElement);
doc.addSVG(svgAsText, 20, 20, doc.internal.pageSize.width - 20 * 2)
// Save the PDF
doc.save('TestSVG.pdf');
});
Check here to do that using canvg https://stackoverflow.com/a/35788928/2090459
Basically you need get base64 image to add into PDF(jsPDF). If we have canvas we can convert to base64 string using .toDataURL().
Check the demo here http://jsfiddle.net/Purushoth/hvs91vpq/

Can we apply image filters on new fabric.Image()?

I wish to apply an image filter on a fabric.Image object but I am unable to do so.
Here is my code:
(Approach: 1) Create an image and add to canvas
var canvas = new fabric.Canvas('canvas');
var img = document.querySelector('.images img.img_dragging');
var newImg = new fabric.Image(img, {
scaleX: .50,
scaleY:.50,
});
newImg.filters.push(new fabric.Image.filters.RemoveWhite({ threshold:10 ,distance: 100 }));
newImg.applyFilters(canvas.renderAll.bind(canvas));
canvas.add(newImg);
Html (Image src is just a random image from net, but our project images are somewhat similar)
<img draggable="true" src="http://cdn.homedit.com/wp-content/uploads/2011/01/blue-small-tufted-sofa.jpg" width="250" height="250"></img>
With above I am able to add the image to the canvas and maneuver the image on the canvas.
My requirement is to remove the extra white spaces from the background of the above image.
As per my reading over net we can implement the above like:
(Approach: 2):
fabric.Image.fromURL('http://cdn.homedit.com/wp-content/uploads/2011/01/blue-small-tufted-sofa.jpg', function(img){
img.filters.push(new fabric.Image.filters.RemoveWhite({ threshold:10 ,distance: 100 }));
img.applyFilters(canvas.renderAll.bind(canvas));
img.scale(0.5);
canvas.add(img);
});
So I wish to seek whether I can use filters with approach 1 and if there is a snippet on how to implement it.
Or filters can only we applied to fromURL approach only.
Any pointers would be a great help.
Cheers!
AJ
P.S : Apologies for any typos.

How do I fill/stroke an SVG file on my website?

I Googled this issue for about 30 minutes and was surprised nobody has asked so maybe it's not possible.
I'm using this line to embed the SVG file that I made in AI (note that when I saved the SVG, I had no fill OR stroke on the paths):
<object type="image/svg+xml" data="example.svg" height=600px width=600px>Your browser does not support SVG</object>
This obviously comes up with no image because the SVG file has no fill or stroke.
I tried adding in
...fill=yellow>
or
...style="fill:yellow;">
but I'm not having any luck. Thanks!
Have a nice trick: Embed it as <img> and use javascript to convert it into inline <svg> with this code (that came from SO I think). Now you can manipulate this SVG object
CODE::
/*
* Replace all SVG images with inline SVG
*/
jQuery('img.svg').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
});
});
Are you trying to add the fill or style on the object element? If so, that's not going to work. Those properties are not supported on the object element. You're going to have to add it into the SVG in the SVG file.

yui How to make in tag image does not necessarily will been to specify its size?

Good day.
I use script Imagecropper
Script:
<img src="http://test.com/img/1362244329.jpg" id="yui_img" height="768" width="1024">
<script>
(function() {
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event;
var crop = new YAHOO.widget.ImageCropper('yui_img');
})();
</script>
result:
But if i do not specify the image size, then i get next(see image):
<img src="http://test.com/img/1362244329.jpg" id="yui_img">
result:
And if i specify the wrong picture size, the window will increase the portion of the image:
<img src="http://test.com/img/1362244329.jpg" id="yui_img" height="333" width="500">
result:
How to make in tag image does not necessarily will been to specify its size?
First of all I'd like to point you to YUI 3 since YUI 2 is no longer supported. You shouldn't write new code using YUI 2. There's an ImageCropper component I wrote for YUI 3 that works just like the YUI 2 version in the YUI Gallery: http://yuilibrary.com/gallery/show/imagecropper. Since it copies what the YUI 2 ImageCropper did, it shares these issues with the older version.
What to do when the size of the image isn't specified
The reason why you're getting a small ImageCropper is that you're creating the widget before the image has been fetched and so the browser doesn't know its size yet. What you can do is wait for the image's onload event. You can listen to that event and create the ImageCropper after it fires:
(function() {
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event;
var yui_img = Dom.get('yui_img');
Event.addListener(yui_img, 'load', function () {
var crop = new YAHOO.widget.ImageCropper(yui_img);
});
})();
Why the ImageCropper doesn't work with images with the wrong size
Neither the YUI 2 ImageCropper nor my YUI 3 version work with images when they don't have the right size. The reason is that both use the background: url() CSS style for showing the image inside the crop area (the non-darkened part of the widget). CSS backgrounds don't let you use a resized/zoomed image.
I plan on using another strategy at some point for the YUI 3 version that will fix the issue. However, you need to keep in mind that the ImageCropper component is designed so that you send the crop coordinates to the server for it to actually crop the image. That means that if you have the wrong size set to the image, the coordinates that the image cropper returns with its getCropCoords method wouldn't be the coordinates that match with the full sized image. Instead you'd also have to send the server the size of the image you've been using and do extra math to crop the image correctly.
In conclusion, you shouldn't use the image with the wrong size. You can fix the size of the image in two ways:
Use the HTML5 naturalWidth and naturalHeight attributes of the image. Those return the real size of the image even if it's resized. Unfortunately these attributes are not yet supported by all browsers.
Create a new image with JS, set it the same src as the image you're using, listen to its load event and get that image's size.
Something like this:
(function () {
var Dom = YAHOO.util.Dom;
var yui_img = Dom.get('yui_img'),
new_img = new Image();
new_img.onload = function () {
yui_img.width = new_img.width;
yui_img.height = new_img.height;
// create the ImageCropper
};
new_img.src = yui_img.src;
}());
A YUI3 version
You can easily do all this with YUI3:
YUI().use('gallery-imagecropper', function (Y) {
var img = Y.one('#yui_img');
img.on('load', function () {
var cropper = new Y.ImageCroper({
srcNode: img,
width: img.get('width'),
height: img.get('height')
});
cropper.render();
});
});
Typo in code. Should be
var cropper = new Y.ImageCropper({
You missed a letter "p".

Resources