How to Send image using org.apache.velocity.VelocityContext for email - spring

MimeMessagePreparator mimeMessagePreparator=new MimeMessagePreparator() {
#Override
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage);
mimeMessageHelper.setTo(requestQuotationPojo.getEmailId().toString());
mimeMessageHelper.setFrom("vikasglobaljapan#gmail.com");
mimeMessageHelper.setText("Your Request Quotation Number"+requestQuotationPojo.getRfqId());
mimeMessageHelper.setSubject("Request Quotation Details");
VelocityContext velocityContext = new VelocityContext();
requestQuotationPojo.setImage(new StringBuffer(application_url.concat(requestQuotationPojo.getImage().toString())));
requestQuotationPojo.setRfqId(new StringBuffer(rfqId));
velocityContext.put("image", requestQuotationPojo.getImage());
velocityContext.put("rfqDetails", requestQuotationPojo);
velocityContext.put("image",application_url.concat(requestQuotationPojo.getImage().toString()));
StringWriter stringWriter = new StringWriter();
velocityEngine.mergeTemplate("com/gjcp/dao/daoImpl/customer/templateName.vm", "UTF-8", velocityContext, stringWriter);
mimeMessageHelper.setText(stringWriter.toString(), true);
}
template.vm
<!doctype html>
<html lang="en">
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<table style="width:100%">
  <tr>
    <th>Product Name</th>
    <th>Quote Number</th>
    <th>Image</th>
<th>Quantity</th>
  </tr>
<tr>
<td>${rfqDetails.productName}</td>
<td> ${rfqDetails.rfqId}</td>
<td><img src="${rfqDetails.image}" border="0" width="50" height="50"></td>
<td>${rfqDetails.quantity}</td>
</tr>
</table>
</body>
</html>

I suppose that your image is a byte array. So you should add image to velocity context as base64 string.
velocityContext.put("image", Base64.encode(requestQuotationPojo.getImage()));
And use this img tag in your template file.
<img src="data:image/jpg;base64,${image}" border="0" width="50" height="50"/>

${websitename} : Write Your website name.
${rfqDetails.image} : your image path.
Like Your image url: http://test.com/folder/abc.png
#set($imgsrc="http://${websitename}/${rfqDetails.image})
<img width="50" src="$imgsrc" border="0" height="50" alt="test">

Related

Why is the string not added to the property via Model.addObject?

I created #ControllerAdvice to handle BindException:
#ControllerAdvice
class globalControllerAdvice {
#ExceptionHandler(BindException.class)
public ModelAndView handleMyException(HttpServletRequest req, Exception e) {
ModelAndView model = new ModelAndView();
model.addObject("myerror",e.getErrCode());
model.addObject("message",e.getMessage());
model.addObject("exception","bind exception");
model.setViewName("error");
return model;
}
}
And created error.html :
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handing Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
table td{
vertical-align:top;
border:solid 1px #888;
padding:10px;
}
</style>
</head>
<body>
<h1>Error Page</h1>
<table>
<tr>
<td>Error</td>
<td th:text="${myerror}"/>
</tr>
<tr>
<td>Message</td>
<td th:text="${message}"/>
</tr>
<tr>
<td>Exception</td>
<td th:text="${exception}"/>
</tr>
</table>
</body>
</html>
And when executing, when I make a mistake on purpose, the page appears normally,but the properties are not filled in .That is, a table is created, but the text "${myerror}" , "${message}" , "${exception}" are not filled in with e.getErrCode() , e.getMessage() ,
"bind exception". Can anyone tell me what the problem is? thanks

Thymeleaf can't see For-each variable

Here is my Service ( It just gets a list of entities )
#Service
public class ProcedureService {
#Autowired
ProcedureRepository procedureRepository;
public List getProceduresList() {
List<Procedure> procedureList;
procedureList = procedureRepository.findAll();
return procedureList;
}
}
Here is my Controller. It just puts list he gets to view.
#Controller
public class ServicesController {
#Autowired
ProcedureService procedureService;
#GetMapping("/services")
public String getCustomer(Model model) {
List<Procedure> procedures = procedureService.getProceduresList();
model.addAttribute("procedures", procedures);
return "services";
}
}
And here is my real problem. Thyme leaf just doesn't see the entity in a List ( it sees the list though ). Here is my screen and full code of View
<!DOCTYPE html>
<html lang="en">
<head>
<title>SpringMVC + Thymeleaf + Bootstrap 4 Table Example</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Customer Table</h1>
<div class="row col-md-7 table-responsive">
<table id="customerTable" class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Street</th>
<th>Postcode</th>
</tr>
</thead>
<tbody>
<tr th:each="procedure: ${procedures}">
<td th:text="${procedure.}" />
<td th:text="${procedure.getId}" />
</tr>
</tr>
</tbody>
</table>
</div>
</div>
I forgot about html lang="en" xmlns:th="http://www.thymeleaf.org" in html so th wasn't really working.

Search page in spring mvc doesn't work

I Have created simple mvc CRUD. All works fine except search page.
Im getting errorr as follows:
HTTP Status 500 - Request processing failed; nested exception is org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
Controller page is:
#RequestMapping(value="/search")
public ModelAndView search(){
return new ModelAndView("search","command", new Emp());
}
#RequestMapping(value="/jsp/searchemp",method = RequestMethod.POST)
public ModelAndView search1(#ModelAttribute("name") Emp emp){
String name = null;
name = dao.searchname(name);
return new ModelAndView("searchemp","name",name);
}
Search.jsp:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>z
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
label {
text-align: right;
clear: both;
float:left;
margin-right:15px;
}
.box{background-color: #e1e8f0;}
body{background:#f0eceb;}
</style>
</head>
<body>
<div style=" left: 30%; top: 25%; position: absolute;">
<div class="col-sm-12 col-sm-offset-3 box " >
<center> <h1>Add New Employee</h1> </center>
<form method="post" action="jsp/searchemp/" >
<div class="form-group"> <div class="col-xs-7">
<label ><h5>Name :</h5></label>
<input name="name" class="form-control" placeholder="Enter Name of the employee" />
<button type="submit" value="Save" class="btn btn-primary btn-lg">Search</button>
</div></div>
</form>
</div>
</div>
</body>
</head>
Searchemp.jsp:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>Employees List</h1>
<table class="table table-hover" border="1" width="70%" cellpadding="2">
<thead>
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><th>Edit</th><th>Delete</th></tr></thead>
<tbody><tr>
<td>${String.id}</td>
<td>${String.name}</td>
<td>${emp.salary}</td>
<td>${emp.designation}</td>
<td>Edit</td>
<td>Delete</td>
</tr> </tbody>
</table>
<br/>
Add New Employee
jdbctemplate query:
public String searchname(String name) {
String query = "select * from Emp99 where name=?";
Object[] inputs = new Object[] {name};
String empName = template.queryForObject(query, inputs, String.class);
return empName;
}
Dont know what goes wrong.
help me.
in order for jsp to consume an bean , your controller method should return data,in your jsp you are trying to utilize
{String.id} and {emp.id} which is never passed from the controller method search1.so you need to add your beans to a model and
return the page like this.
#RequestMapping(value="/jsp/searchemp",method = RequestMethod.POST)
public String search1(#ModelAttribute("name") Emp emp,Model model){
model.addAttribute("emp",emp); //passing the model name and the bean ,
//model.addAttribute("name",anotherBean); //you can add many attributes as you wish.
return "searchemp";
}
now inside the searchemp.jsp you can utilize the emp bean like this.
{emp.id}
remove the {String.id} part. inside the searchemp.jsp which will not work.

Spring MVC : Jsp file does not display data from the controller

This is my controller code
#RequestMapping(value="/testMvc")
public String testero(Model model ){
String nameClient="HENOCKE";
Long CodeClient=2L;
String Address="LONDO Street";
System.out.println("****End and outputting to Jsp page: ****");
return "rs";
}
And as you can see i want to display data to my jsp files and this is my jsp file:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" charset=UTF-8>
<title>Banque </title>
<link rel="stylesheet" type="text/css"
href="<%=request.getContextPath()%>/resources/CSS/style1.css">
</head>
<body>
<h2>Date Loaded from My controller....</h2>
<table>
<tr>
<th>Name : </th> <th><c:out value="${nameClient}"/></th>
</tr>
<tr>
<th>id Client: </th> <th> <c:out value=" ${CodeClient}" /> </th>
</tr>
<tr>
<th>Adress client: </th> <th> <c:out value="${Address}" /></th>
</tr>
</table>
</body>
</html>
How can i output data to my jsp? here rs is the Name of my Jsp file
You need to add the attributes to the model.
String nameClient = "Whatever";
model.addAttribute("nameClient",nameClient);
Read this:
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/mvc.html
You should create ModelAndView object to put values to view:
#RequestMapping(value="/testMvc")
public ModelAndView testero(){
ModelAndView mov = new ModelAndView("rs");
mov.addAttribute("nameClient", "HENOCKE");
mov.addAttribute("CodeClient", 2L);
mov.addAttribute("Address", "LONDO Street");
System.out.println("****End and outputting to Jsp page: ****");
return mov;
}

dompdf with special characters

I have following code:
$pdf = \App::make('dompdf');
$pdf->loadView('offers.pdf',compact('email','messages'));
return $pdf->stream();
pdf.blade.php:
<!doctype html>
<html class="no-js" lang="sk">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
* {
font-family: "Arial";
}
</style>
</head>
<body>
Rozpočet, Voliteľné časti
</body>
</html>
PDF document looks like:
Rozpo?et,Volite?né ?asti
But I need show special characters like in pdf.blade.php file, do you have some solutions for me?
This worked for me:
<html>
<head>
<meta http-equiv="Content-Type" content="charset=utf-8" />
<style type="text/css">
* {
font-family: "DejaVu Sans Mono", monospace;
}
</style>
</head>
<body>your content ćčžšđ...</body>
</html>
For Laravel 8, I solved my problem with the help of the https://github.com/mpdf/mpdf PHP package.
First of all, I've created a view template in my resources folder,
"pdfview.blade.php"
<!DOCTYPE HTML>
<html lang="fa">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<table dir="rtl">
<tr>
<th>ردیف</th>
<th>عنوان</th>
<th>توضیحات</th>
</tr>
#foreach ($items as $key => $item)
<tr style="padding: 5px">
<td style="padding: 10px">{{ ++$key }}</td>
<td style="background: #efefef; padding: 10px">{{ $item->title }}</td>
<td style="padding: 10px">{{ $item->body }}</td>
</tr>
#endforeach
</table>
</body>
and created a method in my controller:
public function pdfview()
{
$items = Post::get();
// change the root directory of fonts.
$fontDirs = public_path() . "/fonts/MY_FONT_NAME/";
// specify the font
$fontData = [
"MY_FONT_NAME" => [
'R' => 'MY_FONT_NAME.ttf'
],
];
$mpdf = new Mpdf([
'fontDir' => $fontDirs,
'fontdata' => $fontData,
'default_font' => 'MY_FONT_NAME'
]);
// render view as HTML
$html = view('pdfview', compact('items'))->render();
$mpdf->WriteHTML($html);
return $mpdf->Output();
}

Resources