How to add image dynamically in the jasper reports in java - image

Hii Guys !!!
I designed a jasper report to export into pdf which contains image that is stored in my local machine.Now As per my need i need to add the image dynamically from the projects classpath .Below I am posting my code.plz guys help me how to add image dynamically ...
File tempFile = File.createTempFile(getClass().getName(), ".pdf");
try {
FileOutputStream fos = new FileOutputStream(tempFile);
try {
ServletOutputStream servletOutputStream = response.getOutputStream();
InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("jasperpdf.jasper");
try {
String datum1 = request.getParameter("fromdate");
String datum2 = request.getParameter("todate");
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdfSource.parse(datum1);
Date date2 = sdfSource.parse(datum2);
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
datum1 = sdfDestination.format(date);
System.out.println(datum1);
datum2 = sdfDestination.format(date2);
System.out.println(datum2);
String strQuery = "";
ResultSet rs = null;
conexion conexiondb = new conexion();
conexiondb.Conectar();
strQuery = "Select calldate,src,dst,duration,disposition,cdrcost from cdrcost where date(calldate) between '" + datum1 + "' and '" + datum2 + "'";
rs = conexiondb.Consulta(strQuery);
JRResultSetDataSource resultSetDataSource = new JRResultSetDataSource(rs);
JasperRunManager.runReportToPdfStream(reportStream, fos, new HashMap(), resultSetDataSource);
rs.close();

Is it working when you have provided the relative path of the image? i.e. images/image.jpg You should have a folder named images in your project and inside that there should be the file image.jpg ..

i'm newbie for jasper report, may be this code useful for you
private static JRDesignImage getImage(int x_postion, int y_position, int width, int height,ScaleImageEnum scale_type, HorizontalAlignEnum align_type,
JRDesignExpression expression) {
JRDesignImage image = new JRDesignImage(null);
image.setX(0);
image.setY(8);
image.setWidth(97);
image.setHeight(50);
image.setScaleImage(ScaleImageEnum.RETAIN_SHAPE);
image.setHorizontalAlignment(HorizontalAlignEnum.LEFT);
image.setExpression(expression);
// TODO Auto-generated method stub
return image;
}
then add
band = new JRDesignBand();
band.setHeight(73);
expression = new JRDesignExpression();
expression.setValueClass(java.lang.String.class);
expression.setText("$P{imagePath}");
// jasperDesign.addField();
band.addElement(getImage(0,8,97,50,ScaleImageEnum.RETAIN_SHAPE,HorizontalAlignEnum.LEFT,expression));

Related

Access to wwwroot - Asp.Net Core MVC working well on local host but not in published app

I'm having a lot of trouble trying to get my App to work when
published. Basically, the code is supposed to create a doc from
template using Open XML sdk, then save to wwwroot and then upload to
blob storage.
It's working fine using local host. Have read and tried some stuff re
accessing static files - but nothing seems to work. Any help would be
very much appreciated. Relevant code is below:
[HttpGet]
public IActionResult GenerateDocxBrowser(MemoryStream mem, string filepath, string inputLastName, string inputTitle, string requestID, string dateReceived, string complaintType, string complaintDetails, string nameString, string no, string street, string town, string postcode)
{
var list = _context.Complaints.Where(s => s.ComplaintId.ToString().Contains(requestID)).ToList();
using (mem = new MemoryStream())
{
filepath = #"wwwroot\RequestTemplate.docx";
nameString = list.Select(s => s.NameString).FirstOrDefault();
complaintDetails = list.Select(s => s.Complaint).FirstOrDefault();
street = list.Select(s => s.AddressStreet).FirstOrDefault();
town = list.Select(s => s.AddressTown).FirstOrDefault();
using (WordprocessingDocument document = WordprocessingDocument.Open(filepath,true))
{
document.GetMergeFields("LastName").ReplaceWithText(inputLastName);
document.GetMergeFields("Title").ReplaceWithText(inputTitle);
document.GetMergeFields("ComplaintID").ReplaceWithText(requestID);
document.GetMergeFields("DateReceived").ReplaceWithText(dateReceived);
document.GetMergeFields("ComplaintType").ReplaceWithText(complaintType);
document.GetMergeFields("ComplaintDetails").ReplaceWithText(complaintDetails);
document.GetMergeFields("NameString").ReplaceWithText(nameString);
document.GetMergeFields("AddressLn1").ReplaceWithText(no + " " + street);
document.GetMergeFields("AddressLn2").ReplaceWithText(town + " TAS " + postcode);
document.SaveAs(#"wwwroot\" + requestID + ".docx");
document.MainDocumentPart.Document.Save();
document.Close();
}
}
const string StorageAccountName = "xxx";
const string StorageAccountKey = "xxxxxx";
var storageAccount = new CloudStorageAccount(
new StorageCredentials(StorageAccountName, StorageAccountKey), true);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("tasman/Request Images");
CloudBlockBlob blockBlob = container.GetBlockBlobReference(requestID + ".docx");
blockBlob.UploadFromFileAsync(#"wwwroot\" + requestID + ".docx");
return View();
}
Your .SaveAs() field should be relative, currently its literally saving to wwwroot somewhere on the drive. You can specify the relative path a few different ways - one of them is below:
var saveToFolder = Path.Combine(Environment.CurrentDirectory, $"/wwwroot/{requestID}.docx");

Unity, loading image from Sqlite

hi guys this is my first time using Sqlite, i managed to retrieve the text and display it, however the image shows a red question mark even tho i followed this : unity sqlite tutorial
here is my code :
private void readQuestionsFromDB(){
string conn = "URI=file:" + Application.dataPath + "/quizdb.s3db"; //Path to database.
IDbConnection dbconn;
dbconn = (IDbConnection) new SqliteConnection(conn);
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand();
string sqlQuery = "SELECT id, statement, answer, image " + "FROM questions";
dbcmd.CommandText = sqlQuery;
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read())
{
string statement = reader.GetString(1);
answerint = reader.GetInt32(2);
byte[] img = (byte[])reader["image"];
Question q = new Question(statement, answer, img);
questions.Add(q);
}
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbconn.Close();
dbconn = null;
}
Then i try to display the image from the start method :
readQuestionsFromDB();
statement.text = questions[0].statement;
Texture2D tex = new Texture2D(800,400); //image is 800/400
tex.LoadImage(questions[0].image);
image.GetComponent<Image>().sprite = Sprite.Create(tex, new Rect(0,0,tex.width,tex.height),new Vector2(0.5f, 0.5f));
Here is the outcome :
image
Thank you in advance for your help!

ImageProcessorCore: Attempt to resample image results in zero-length response

I am trying to resample a JPG image from 300dpi to 150dpi and am getting back a zero-length file.
Controller's ActionResult:
public ActionResult ViewImage(string file, int dpi = 300, bool log = true)
{
FileExtensions fileExtensions = new FileExtensions();
ImageExtensions imageExtensions = new ImageExtensions();
FileModel fileModel = fileExtensions.GetFileModel(file);
string contentType = fileModel.FileType;
byte[] fileData = fileModel.FileData;
string fileName = Path.GetFileNameWithoutExtension(fileModel.FileName) + "_" + dpi + "DPI" + Path.GetExtension(fileModel.FileName);
FileStreamResult resampledImage = imageExtensions.ResampleImage(fileData, contentType, dpi);
resampledImage.FileDownloadName = fileName;
return resampledImage;
}
ResampleImage method:
public FileStreamResult ResampleImage(byte[] fileData, string contentType, int targetDPI)
{
MemoryStream outputStream = new MemoryStream();
using (Stream sourceStream = new MemoryStream(fileData))
{
Image image = new Image(sourceStream);
image.HorizontalResolution = targetDPI;
image.VerticalResolution = targetDPI;
JpegEncoder jpegEncoder = new JpegEncoder();
jpegEncoder.Quality = 100;
image.Save(outputStream, jpegEncoder);
}
FileStreamResult file = new FileStreamResult(outputStream, contentType);
return file;
}
I thought I best answer here since we've already dealt with it on the issue tracker.
ImageProcessorCore at present (2016-08-03) is alpha software and as such is unfinished. When you were having the issue, horizontal and vertical resolution was not settable in jpeg images. This is now solved.
Incidentally there are overloads that allow saving as jpeg without having to create your own JpegEncoder instance.
image.SaveAsJpeg(outputStream);

how to add a folder in the apk

I wanna to know how to add a folder in the apk.don't give me a solution about using the compress software directly. The apk was recompiled by the 'apktool.jar'. I need some code to achieve this problem. Hope one can solve my question as soon as possible.Thank you~
public static int zipMetaInfFolderToApk(String apkName, String folderName) throws IOException {
if(!new File(apkName).exists()){
return ConstantValue.ISQUESTION;
}
String zipName = apkName.substring(0, apkName.lastIndexOf(".")) + "."
+ "zip";
String bak_zipName = apkName.substring(0, apkName.lastIndexOf("."))
+ "_bak." + "zip";
FileUtils.renameFile(apkName, zipName);
ZipFile war = new ZipFile(zipName);
ZipOutputStream append = new ZipOutputStream(new FileOutputStream(
bak_zipName));
Enumeration<? extends ZipEntry> entries = war.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
System.out.println("copy: " + e.getName());
append.putNextEntry(e);
if (!e.isDirectory()) {
copy(war.getInputStream(e), append);
}
append.closeEntry();
}
String name = "";
if(folderName.equals("")){
name = "META-INF/" + folderName;
}else{
name = "META-INF/" + folderName + "/";
}
ZipEntry e = new ZipEntry(name);
try{
append.putNextEntry(e);
}catch(ZipException e1){
append.closeEntry();
war.close();
append.close();
FileUtils.renameFile(zipName,apkName);
FileUtils.deleteFolder(bak_zipName);
e1.printStackTrace();
return ConstantValue.ISQUESTION;
}
append.closeEntry();
war.close();
append.close();
FileUtils.deleteFolder(zipName);
FileUtils.renameFile(bak_zipName, apkName);
return ConstantValue.ISNORMAL;
}

ASP.NET DynamicData Import Datas from Excel

I am using ASP.NET DynamicData v4.5 to allow admin to insert/update the records in the database.
My requirement is, -- Allow admin to import records for table from EXCEL file.
Source for the table may be available in excel files also. so i want admin to import data from file.
Is there any way i can achieve this in DynamicData ?
Yes you can do it, I've done it many times.
There is no built-in feature in Dynamic Data doing this but that's not a problem since it's pretty easy to implement.
The fact that you use ASP.NET Dynamic Data (like I do) is not really important for this task. As you probably know, you can create a regular ASP.NET form within a Dynamic Data project. You can also use a folder named /DynamicData/CustomPages to customize a Dynamic Data page. I suggest creating a new regular ASP.NET form called ImportingTool.aspx where your users will be able to import spreadsheets into your database. Once imported, they can use other dynamic data pages to edit the data.
Here is what you will need :
1- You need the user to upload a file, you will need
asp:fileupload or ajaxToolkit:AjaxFileUpload
2- You need to open that file, it will look like :
public void Import(FileUpload fileUpload)
{
if (fileUpload.HasFile)
{
string FileName = Path.GetFileName(fileUpload.PostedFile.FileName);
string Extension = Path.GetExtension(fileUpload.PostedFile.FileName);
string FilePath = HttpRuntime.AppDomainAppPath + "/Uploaded/" + FileName;
fileUpload.SaveAs(FilePath);
Import(FilePath, Extension);
}
}
3- You will need to import that file in your database, it will look like :
public Boolean Import(string FilePath, string Extension)
{
if (String.IsNullOrEmpty(FilePath) || String.IsNullOrEmpty(Extension))
{
return false;
}
string conStr;
string conStrNoHDR;
GetConnectionString(FilePath, Extension, out conStr, out conStrNoHDR);
OleDbConnection connection = new OleDbConnection(conStr);
OleDbConnection connectionNoHDR = new OleDbConnection(conStrNoHDR);
// depending on file extension, you might want to use connectionNoHDR
Import(connection);
connection.Close();
connectionNoHDR.Close();
}
private static void GetConnectionString(string FilePath, string Extension, out string conStr, out string conStrNoHDR)
{
conStr = "";
conStrNoHDR = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 8.0;HDR=YES\"";
conStrNoHDR = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 8.0;HDR=NO\"";
break;
case ".xlsx": //Excel 07
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=Excel 12.0 ";
conStrNoHDR = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 12.0;HDR=NO\"";
break;
case ".csv":
conStr = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + Path.GetDirectoryName(FilePath) + ";Extended Properties=\"Text;FMT=Delimited;HDR=NO\"";
break;
}
}
public static void Import(OleDbConnection connection)
{
String query = "SELECT * From [Report-LANG_VOCALLS$]";
DataTable dt = ImportUtils.GetData(connection, query);
string table = "Dialer";
string conn = ConfigurationManager.ConnectionStrings["Telecom"].ConnectionString;
SqlBulkCopy bulkCopy = new SqlBulkCopy(conn);
bulkCopy.ColumnMappings.Add("Phone", "Phone");
bulkCopy.ColumnMappings.Add("portfolio", "Portfolio_eng");
bulkCopy.ColumnMappings.Add("dept", "Department_eng");
ImportUtils.BulkCopy(dt, table, bulkCopy);
}
public static DataTable GetData(OleDbConnection connection, String query)
{
DataTable dt = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter();
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.CommandText = query;
cmdExcel.Connection = connection;
connection.Open();
adapter.SelectCommand = cmdExcel;
adapter.Fill(dt);
Debug.WriteLine(dt.Rows.Count);
connection.Close();
return dt;
}

Resources