How to generate and download pdf with dynamic image path from database using any npm packages - node.js

I'm building a software using express-mongodb-ejs. I've tried some of the npm packages to generate and download pdf. But, I cant generate pdf which having the dynamic image path.
I've used html-pdf package, which seems pretty good. But, It can't render the dynamic image path from database.
Here is the screenshot where I used the html-pdf package.
Here is the detailed problem link where I asked about this package related question.
Can anyone provide me any detailed solution regarding the problem? Any npm package should be fine as long as it can help me to download pdf using express.

You may use a popular node module called pdfkit. Please run the below program and check it. You need an image with the name pro.jpg in the same folder that you run the script. It will generate an output.pdf file.
Here is the example:
const PDFDocument = require('pdfkit');
const fs = require('fs');
// Create a document
const doc = new PDFDocument();
// Pipe its output somewhere, like to a file or HTTP response
// See below for browser usage
doc.pipe(fs.createWriteStream('output.pdf'));
// Add an image, constrain it to a given size, and center it vertically and horizontally
doc.image('pro.jpg', {
fit: [250, 300],
align: 'center',
valign: 'center'
});
// Add another page
doc
.addPage()
.fontSize(25)
.text('Here is some vector graphics...', 100, 100);
// Draw a triangle
doc
.save()
.moveTo(100, 150)
.lineTo(100, 250)
.lineTo(200, 250)
.fill('#FF3300');
// Apply some transforms and render an SVG path with the 'even-odd' fill rule
doc
.scale(0.6)
.translate(470, -380)
.path('M 250,75 L 323,301 131,161 369,161 177,301 z')
.fill('red', 'even-odd')
.restore();
// Add some text with annotations
doc
.addPage()
.fillColor('blue')
.text('Here is a link!', 100, 100)
.underline(100, 100, 160, 27, { color: '#0000FF' })
.link(100, 100, 160, 27, 'http://google.com/');
// Finalize PDF file
doc.end();

Related

Cloudinary.url is not working as expected

I'm wanting to convert an image url so it can include the transformation properties (I want to change the width and height). Here is an example of what I store in my database (the url Cloudinary gives us when we upload an image)
https://res.cloudinary.com/blah/image/upload/v15/orsdrkjfddaqjlwsk0t.jpg
I'm using node.js and the cloudinary library gives us the following method: cloudinary.url().
It does not seem to work when I pass the cloudinary image URL to it:
cloudinary.url('https://res.cloudinary.com/blah/image/upload/v15/orsdrkjfddaqjlwsk0t.jpg',
{ width: 100, height: 100 });
It will just return the original url, it won't add any transformation values to it?!
Note: I what I did to get it to work was strip orsdrkjfddaqjlwsk0t.jpg from the url & pass it to the cloudinary.url method. However if the image stored in my database is not one from cloudinary, stripping the nameofimage.jpg from the url won't work! Cloudinary will create a cloudinary URL for it WHICH does not exist.
You need to specify a crop mode for the width and height to take into effect. For example,
cloudinary.url('https://res.cloudinary.com/blah/image/upload/v15/orsdrkjfddaqjlwsk0t.jpg',
{ width: 100, height: 100, crop: "scale"});

Integration fabricjs with requirejs

I want to use fabricjs with require. I have other projects where i'm using requirejs so everything is configured right.
fabricjs is build with require support. I'm not clear why in dist file i have generated fabric.require.js and fabric.js but i tested all and not work.
Sample code (essential part):
define(['fabric','jquery'], function (fabric,$) {
function Graph(config) {
var canvas = new fabric.Canvas('mycanvas');
var circle = new fabric.Circle({
radius: 20, fill: 'green', left: 100, top: 100
});
}
return Graph;
});
When i try to run this i got error: fabric.Canvas is not a function.
What is strange, when comment line where fabric.Canvas is invoked, code run without error so it's like fabric.Circle call is ok.
Where is the problem?
I found the answer. When i build fabric, need to add and interaction module, so right command was:
node build.js requirejs modules=interaction
Now error was gone!

Render Svg to Pdf using jspdf

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.

PDFKit - locate image in center

Using PDFKit on node.js:
var PDFDocument = require('pdfkit')
var doc = new PDFDocument()
doc.image('images/test.jpeg')
How can I centerize an image added to the PDF?
Is it optional to do it using PDFKit or do I need to use another library?
I've found an indirect way to solve the problem - simply calculate the center and locate the picture there:
doc.image('images/test.jpeg', (doc.page.width - imageWidth) /2 )
Using PDFKit on node.js: We can center the image using following code
doc.image('path/to/image.png', {
fit: [250, 300],
align: 'center',
valign: 'center'
});
You can use this, this code place your image at middle of the line
let imageWidth = 180 // what you wants
doc.image('path/to/image.png',
doc.page.width/2 - imageWidth/2,doc.y,{
width:imageWidth
});

How do I convert SVG with image links to PNG/JPEG?

I'm using fabric.js to add and manipulate images on canvas element. I'd like to export the final result to an image file (JPEG/PNG), and have tried several approaches, without much luck.
The first was using the HTML5 canvas.toDataURL callback - didn't work (apparently this cannot be done with cross-origin images).
I then tried to export the canvas to SVG and use convert utility:
$ convert file.svg file.png
The SVG looks a bit like this:
<svg>
...
<image xlink:href="http://example.com/images/image.png"
style="stroke: none; stroke-width: 1; stroke-dasharray: ; fill: rgb(0,0,0); opacity: 1;"
transform="translate(-160 -247.5)" width="320" height="495">
</image>
...
</svg>
That also didn't work, presumably because of the image links. I then tried to download the linked image and store it locally, replacing the http://...image.png link with /path/to/image.png. No luck.
Is there a way to make this happen? thanks.
UPDATE
I've since solved this by using fabric's node module (npm install fabric) and simply using fabric's JSON representation of the canvas (canvas.toJSON() in fabric) to generate an image (also uses canvas module - npm install canvas).
Here's a simple example on how to do this:
// import the fabric module
var fabric = require('fabric').fabric,
fs = require('fs');
// read the fabric json data as string
// (from file, db, etc)
var jsonString = readJSON(filepath);
// create canvas with specified dimensions
// (change to match your needs)
canvas = fabric.createCanvasForNode(100, 100);
// create output file to hold the png image
output = fs.createWriteStream("/tmp/image.png")
// load the json to the canvas and
// pipe the output to the png file
canvas.loadFromJSON(jsonString, function() {
var stream = canvas.createPNGStream();
stream.pipe(output)
});

Resources