Image is not rendering from dynamic image path while using express html-pdf package - mongodb

I'm using the Html-pdf package to generate and download pdf in an express-MongoDB application. Here is the route, where I've used the Html-pdf package.
//#route - GET /generate PDF
router.get("/generateReport/:id", async (req, res) => {
const tableDataById = await newsModel.findById(req.params.id);
ejs.renderFile(path.join(__dirname, '../views/pages/', "pdf.ejs"), {output:tableDataById}, (err, data) => {
if (err) {
res.send(err);
} else {
var assesPath = path.join('file://',__dirname,'../public/');
assesPath = assesPath.replace(new RegExp(/\\/g), '/');
var options = {
"height": "11.25in",
"width": "8.5in",
"header": {
"height": "20mm",
},
"footer": {
"height": "20mm",
},
"base": "file:///" + assesPath
};
pdf.create(data, options).toBuffer(function (err, buffer) {
if (err) {
res.send(err);
} else {
res.type('pdf');
res.end(buffer,'binary')
}
});
}
});
});
I've used ejs template engine. Here is the code of the "pdf.ejs" file which I rendered in the before mentioned route.
<div class="container">
<div class="row">
<div class="col-md-4">
<img class="card-img-top" src="<%= output.newspapers[0].logo %>">
<h1><%= output.newspapers[0].newsPaperName %></h1>
</div>
<div class="text-center">
<img class="img-fluid" id="test" src="<%= output.image %>" alt="">
</div>
</div>
</div>
Here is the screenshot of my application, which failed to render the dynamic image path
Here, I've also included a screenshot of the sample JSON data, in which the path of the images is included

Image src needs absolute path for rendering dynamic image path from the ejs file that you want to generate as a pdf file.
inside your controller, instead of doing this:
ejs.renderFile(path.join(__dirname, '../views/pages/', "pdf.ejs"), {output:tableDataById}
Do this: send a variable that contains the absolute path
ejs.renderFile(path.join(__dirname, '../views/pages/', "pdf.ejs"), {output:tableDataById,dirname: __dirname}
and inside the ejs file instead of doing this :
<img class="img-fluid" id="test" src="<%= output.image %>" alt="">
Do this : add the variable dirname and go one step back to get the public path where you are saving your image
<img class="img-fluid" id="test" src="<%= dirname %>/../public/<%= output.image %>" alt="">
Hope this will help solving your problem. Happy coding !!

Related

How to save an image to a specific folder with Cloudinary?

I want to save an image file in a specific folder on Cloudinary. The folder name is "userimg".
Here is my code to save without a folder.
My cloudinary and folder directory.
Cloudinary Upload API supports a folder parameter. See - https://cloudinary.com/documentation/image_upload_api_reference#upload
Please try adding:
formData.append('folder', 'userimg');
You can also include the folder in the public ID, e.g., 'myfolder/myimageid'.
Also, see:
https://support.cloudinary.com/hc/en-us/articles/202520902-Can-I-create-folders-in-my-Cloudinary-account-
the code of save an image file in specific folder on cloudinary:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div class="container">
<div class="card">
<img src="http://fillmurray.com/g/300/300" id="img-preview" />
<label class="file-upload-container" for="file-upload">
<input id="file-upload" type="file">
Select an Image
</label>
</div>
</div>
<script>
var cloudeinary_url = "your_cloudeinary_url";
var upload_presets = "your_upload_presets";
var ingpriview = document.getElementById("img-preview");
var fileupload = document.getElementById("file-upload");
fileupload.addEventListener('change',
function (event) {
var files = event.target.files[0];
var formData = new FormData();
formData.append('file', files);
formData.append('upload_preset', upload_presets);
formData.append('folder', 'itemimg'); // itemimg is folder name
axios({
url: cloudeinary_url,
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: formData
}).then(function (res) {
document.getElementById("img-preview").src = res.data.secure_url;
console.log(res);
}).catch(function (err) {
console.log(err);
});
});
</script>

Instafeed JS template

I am using instafeed js to get instagram images to display on my website. I want to pull 5 images and display it together like this example that I have created on codepen. However, the template feature for the instafeed js posed a constraint on how I can organize the images the way that I had on the codepen example since there isn't a way to specifically target each image to a div.
The code on codepen showing how I would want to place each of my images.
<div class="row1">
<div class="column1">
<img src="/assets/placeholder/c1.jpg" alt="placeholder 1" style="width:100%">
<img src="/assets/placeholder/c2.jpg" alt="placeholder 2" style="width:100%">
</div>
<div class="column1">
<img src="/assets/placeholder/c3.jpeg" alt="placeholder 3" style="width:100%">
<img src="/assets/placeholder/c4.jpg" alt="placeholder 4" style="width:100%">
</div>
<div class="column1">
<img src="/assets/placeholder/c5.jpg" alt="placeholder 5" style="width:100%">
</div>
</div>
Here's the code using instafeedjs
var feed = new Instafeed({
get: 'user',
userId: '3xxxxx01',
accessToken: '3xxxxx3446',
limit: 5,
resolution: 'standard_resolution',
template: '<img src="{{image}}" />'
});
feed.run();
You can use the mock option to fetch only the image data without updating the DOM. Then use the success option to do something with that data:
var feed = new Instafeed({
get: 'user',
userId: '3xxxxx01',
accessToken: '3xxxxx3446',
limit: 5,
clientId: 'xxxxxxxxxxxxxx',
resolution: 'standard_resolution',
mock: true,
success: function(images) {
//iterate over images and add them to the DOM as you wish
}
});
This allows you to display the images in any manner you wish.

Use different Login page for AdminLTE

I used AdminLTE for Laravel 5.3. But i want to use my login page with connect to we server.
When i replace my code with auth/login.blade.php page, when i put my username and password and connect to web service, after get response from we server, i try to redirect to another page with window.location.href = "/AddStudent";. but page refresh and stay in login page. How must i do? which setting must i change?
<link rel="stylesheet" href="FileOfLogin/css/style.css">
<div class="wrapper">
<div class="container">
<h1>Welcome</h1>
<form class="form">
<input id="username" type="text" placeholder="Username">
<input id="password" type="password" placeholder="Password">
<button id="loginsubmit" type="button" id="login-button">Login</button>
</form>
</div>
<ul class="bg-bubbles">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="FileOfLogin/js/index.js"></script>
<!-- jQuery 2.1.3 -->
<script src="{{ asset ("/bower_components/AdminLTE/plugins/jQuery/jQuery-2.2.3.min.js") }}"></script>
<!-- Sweet Alarm -->
<script src="SweetAlert/sweetalert-dev.js"></script>
<link rel="stylesheet" href="SweetAlert/sweetalert.css">
<script type="text/javascript">
$( "#loginsubmit" ).click(function() {
console.log('111');
var username=$('#username').val();
var password=$('#password').val();
// console.log(username);
// console.log(password);
$.ajax({
type: "POST",
url: "http://79.132.212.50:8080/SchoolServiceWebService/login",
contentType: 'application/json',
data: '{ "username": "'+username+'", "password": "'+password+'" }',
dataType: "json",
success: function (GetResult) {
// console.log(GetResult);
if (GetResult.result) {
console.log(GetResult);
console.log("8888888888888");
window.location.href = "/AddStudent";
// window.location.replace('/AddStudent');
} else {
sweetAlert("خطا", "ورود !!!!!!", "error");
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
})//ajax
});
</script>
One way to do it is to override the methods in "Auth\LoginController". This way, you can specify your own view and redirect to a custom page. For more information about Laravel Authentication Mechanism, check this oficial page

Unable to get mizzao/meteor-autocomplete to work with collection

I am using mizzao/meteor-autocomplete and am having problems in trying to get it to work.
When viewing the page in my browser, I am getting no results at all when typing any text. I've created the appropriate collection:
Institutions = new Mongo.Collection("institutions");
and know that there is data in the actual db, however still no success.
I've included my files below.
publications.js (located in the server folder)
Meteor.publish('institutions', function(args) {
return Institutions.find({}, args);
});
registrationStart.js
I've two helpers; one that actually powers the search and the other that should be returning the institutions. I have also tried this with the token: '#' argument with no success.
if (Meteor.isClient) {
Template.registrationStart.helpers({
settings: function() {
return {
position: "top",
limit: 7,
rules: [{
collection: Institutions,
field: "name",
options: '',
matchAll: true,
template: Template.institutionSelectDisplay
}]
};
},
institutions: function() {
return Instititions.find();
}
});
Template.registrationStart.events({
"autocompleteselect input": function(event, template, doc) {
// Session.set(event.target.name, event.target.value);
console.log("selected: ", doc);
console.log("event.target.name: ", event.target.name);
console.log("event.target.value: ", event.target.value);
}
});
}
registrationStart.html template
<template name="registrationStart">
<div class="panel-body" id="loginForm">
<h2 class="pageTitle">veClient Registration</h2>
<form>
<div> </div>
<fieldset>
{{> inputAutocomplete settings=settings id="institution" class="input-xlarge" placeholder="type institution here"}}
</fieldset>
<div> </div>
<button type="submit" class="btn btn-primary btn-sm">Continue Registration</button>
</form>
</div>
</template>
And the template to be rendered
<template name="institutionSelectDisplay">
<p class="inst-state">{{city}}, {{state}}</p>
<p class="inst-name">{{name}}</p>
<p class="inst-description">{{email}}</p>
</template>
Problem resulted because there was no subscription to the "institutions" publication. So need to add a subscribe statement to the registrationStart.js file:
Meteor.subscribe('institutions');

Load partial view in a modal pop-up window using jquery

I have images that are loaded from database. When I click on an image, I want to show that image in a Modal Pop-up. My problem is that, I am not able to call the partial view from jquery. In fact, that action is not getting called from JQuery. Please help... I am a fresher. Below is my code:
_Layout.cshtml
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>_Layout</title>
#Styles.Render("~/bundle/ProfileStyle")
#Scripts.Render("~/bundle/JQuery")
#Scripts.Render("~/bundle/JQueryUI")
#Scripts.Render("~/bundle/CustomJS")
</head>
<body>
<div>
#RenderBody()
</div>
<div id="dialog">
#Html.Partial("_ProfileDetail")
</div>
</body>
</html>
Index.cshtml
#model IEnumerable<Profile.Models.TestProfile>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div class="tableOuterBlock">
#foreach (var item in Model)
{
<div class="tableInnerBlock">
<span>
#*<a href="#Url.Action("Edit", "Profile", new {#item.upi_Id})">*#
<img id="imgOpenDialog" src="#Url.Content(#item.upi_ImgData)" alt="No Image" width="100" height="100" />
#*</a>*#
</span>
</div>
}
</div>
Partial view
#model Profile.Models.TestProfile
<div>
#if(Model != null)
{
<img id="imgOpenDialog" src="#Url.Content(#Model.upi_ImgData)" alt="No Image" width="80%" height="50%" />
}
</div>
JQuery
$(function () {
$("[id*=imgOpenDialog]").click(function () {
var imgDetail = $(this).prop("src");
$("#dialog").dialog({
autoOpen: true,
position: { my: "center" },
modal: true,
resizable: false,
open: function () {
//parameter to c# function
data: { strImg = imgDetail }
$(this).load('#Url.Action("ShowProfileDetail","Profile")');
}
});
});
});
Controller
public PartialViewResult ShowProfileDetail(string strImg)
{
strImg = strImg.Substring(strImg.IndexOf('/'));
List<TestProfile> tpList = db.TestProfiles.Where(x => x.upi_ImgData ==strImg).ToList();
TestProfile testProfile = db.TestProfiles.Find(tpList[0].upi_Id);
return PartialView("_ProfileDetail", testProfile);
}
it may be a bit late but if you check out this blog, and download his code, you will see his use of jquery to create a modal pop up from a partial view.