Birt Report .rptdesign file to PDF in java - birt

I have designed .rptdesign file from Eclipse . It has XML Data Source. It is working fine from there. Now what I want to generate PDF file from that .rptdesign in Java application.
Can anyone guide me how to do that ?

BIRT Designer studio gives us .rptdesign files like you rightly mentioned.
However , when we need to develop reports at runtime from our java/web applications , we need :
DEAPI (Design Engine API) : for creating Design Files during runtime
IReportEngine : for creating different format (
html/pdf.
.) reports during runtime
Its a total study with emphasize on integrating BIRT engine with java application.
Refer the following link/code for a head start.
EngineConfig config = null;
try{
config = new EngineConfig( );
config.setBIRTHome("C:/birt/birt-runtime-2.3RC3/birt-runtime-2_3_0/ReportEngine");
//config.setLogConfig(null, Level.FINE);
//config.setResourcePath("C:/work/workspaces/2.3rc3srcexamples/APIs/Reports");
Platform.startup( config );
IReportEngineFactory factory = (IReportEngineFactory) Platform
.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
engine = factory.createReportEngine( config );
IDesignEngineFactory dfactory = (IDesignEngineFactory) Platform
.createFactoryObject( IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY );
dengine = dfactory.createDesignEngine( new DesignConfig() );
IReportRunnable design = null;
//Open the report design
SessionHandle session = dengine.newSessionHandle(ULocale.ENGLISH );
// design = engine.openReportDesign("C:/Workspace_Reporting/DEAPI/src/deapi/firstTemplate.rpttemplate");
design = engine.openReportDesign("C:/designTemplate.rpttemplate");
ReportDesignHandle report = (ReportDesignHandle) design.getDesignHandle( );
println( " REPORT dataset :"+report.getDataSets());
// report.saveAs("Template1.rptdesign");
if(!(params.templateQuery).equals(null))
changeDataSet(report);
//ds_interestRateCode
//Create task to run and render the report,
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
task.setParameterValue("templateTitle",params.templateTitle);
task.validateParameters();
HTMLRenderOption options = new HTMLRenderOption();
options.setOutputFileName("C:/Reports/"+params.templateTitle);
options.setOutputFormat("html");
options.setImageDirectory("images");
task.setRenderOption(options);
task.run();
task.close();
session.closeAll(false);
engine.destroy();
Platform.shutdown();
System.out.println("Finished Generation !");
// redirect(action: index(),controller: GenericReportGeneratorController)
renderFile((params.templateTitle))
}catch( Exception ex){
ex.printStackTrace();
}
}
def renderFile(def fileName)
{
String profileImagePath = "C:/Reports/"
response.setContentType("APPLICATION/OCTET-STREAM")
//response.setContentType("text/html;charset=UTF-8")
response.setHeader("Content-Disposition", "Attachment;Filename="+(fileName))
def file = new File(profileImagePath+fileName)
def fileInputStream = new FileInputStream(file)
def outputStream = response.getOutputStream()
byte[] buffer = new byte[4096];
int len;
while ((len = fileInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
outputStream.flush()
outputStream.close()
fileInputStream.close()
}
https://wiki.eclipse.org/Java_-_Simple_Design_Engine_API_(BIRT)

Related

CreateChooser is not working in Android v5.1

I am using intent to share pdf files. I am restricting apps when share file. I want to share the file to Good document, Kindle and drop box alone. I am using the below code to achieve this.But the below code is not working in android v5.1. The device have the required app to share. But it is showing "No apps can perform this action" when share. Can you anyone suggest your ideas to resolve this?
var pathFile = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var m_documentMobiNames = shortName + "." + fileType;
var mobileFileName = Path.Combine(pathFile, m_documentMobiNames);
var shareIntentsLists = new List<Intent>();
Intent sendIntent = new Intent();
sendIntent.SetAction(Intent.ActionSend);
sendIntent.SetType("application/pdf");
var resInfos = context.PackageManager.QueryIntentActivities(sendIntent, 0);
if (resInfos.Count > 0)
{
foreach (var resInfo in resInfos)
{
string packageName = resInfo.ActivityInfo.PackageName;
if (packageName.Contains("com.google.android.apps.docs") || packageName.Contains("com.dropbox.android") || packageName.Contains("com.amazon.kindle"))
{
Intent intent = new Intent();
intent.SetComponent(new ComponentName(packageName, resInfo.ActivityInfo.Name));
intent.SetAction(Intent.ActionSend);
intent.SetType("application/pdf");
intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file://" + mobileFileName));
intent.SetPackage(packageName);
shareIntentsLists.Add(intent);
}
}
}
if (shareIntentsLists.Count > 0)
{
chooserIntent = Intent.CreateChooser(new Intent(), "Share with");
chooserIntent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse(mobileFileName));
chooserIntent.PutExtra(Intent.ExtraInitialIntents, shareIntentsLists.ToArray());
chooserIntent.SetFlags(ActivityFlags.ClearTop);
chooserIntent.SetFlags(ActivityFlags.NewTask);
context.StartActivity(chooserIntent);
await Task.FromResult(true);
}

Brother Printer SDK in Xamarin.Android Printing Issue

I'm Working on Brother Label Printer QL-710W using Xamarin.Android.
I have created a Android bindings project and Added jar files and .so files as shown below.
I'm using Visual Studio.
Jars >
BrotherPrintLibrary.jar; BuildAction: EmbeddedJar
MobilePrintLib.jar; BuildAction: ReferenceJar
NativeLibraries > armeabi >
libAndrJFPDFEMB.so; BuildAction: EmbeddedNativeLibrary
libcreatedata.so; BuildAction: EmbeddedNativeLibrary
Additions
ClassTest.cs
public bool PrintFile(string fileurl, NetPrinter printer)
{
Task <bool> printTask = new Task<bool>(() => {
bool success = true;
try
{
Printer myPrinter = new Printer();
PrinterInfo myPrinterInfo = new PrinterInfo();
PrinterStatus status = new PrinterStatus();
LabelInfo mLabelInfo = new LabelInfo();
myPrinterInfo.PrinterModel = PrinterInfo.Model.Ql710w;
myPrinterInfo.IpAddress = printer.IpAddress;
myPrinterInfo.MacAddress = printer.MacAddress;
myPrinterInfo.Port = PrinterInfo.PortEnum.Net;
myPrinterInfo.PrintMode=PrinterInfo.PrintModeEnum.FitToPage;
myPrinterInfo.PaperSize = PrinterInfo.PaperSizeEnum.Custom;
myPrinterInfo.Orientation = PrinterInfo.OrientationEnum.Portrait;
myPrinterInfo.LabelNameIndex = LabelInfo.QL700.W62.Ordinal();
myPrinterInfo.ScaleValue = 1;
mLabelInfo.LabelNameIndex = LabelInfo.QL700.ValueOf("W62").Ordinal();
mLabelInfo.IsAutoCut = true;
mLabelInfo.IsEndCut = true;
myPrinter.SetPrinterInfo(myPrinterInfo);
myPrinter.SetLabelInfo(mLabelInfo);
myPrinter.StartCommunication();
status = myPrinter.PrintFile(fileurl);
if (status.ErrorCode != PrinterInfo.ErrorCode.ErrorNone)
success = false;
myPrinter.EndCommunication();
}catch(Exception ex)
{
Console.WriteLine("ERROR : {0}",ex.Message);
success = false;
}
return success;
});
printTask.Start();
var isSuccess = printTask.Result;
return isSuccess;
}
I'm getting printers list successfully from network. But when I'm calling above method it is getting exception at myPrinter.SetPrinterInfo(myPrinterInfo); as "Couldn't load createdata from loader dalvik.system.PathClassLoader[DexPathList[[zip file \"/data/app/PocAndroidArchieve.PocAndroidArchieve-2.apk\"],nativeLibraryDirectories=[/data/app-lib/PocAndroidArchieve.PocAndroidArchieve-2, /vendor/lib, /system/lib]]]: findLibrary returned null"
Please suggest me if any one has idea to work with jar's and dependent .so files.
Thanks in advance.

Unexpected Behavior with Parallel.For() - file not found

I am trying to use Parallel.For() to load n # of flat files into a database. Each iteration needs to create 2 config files in a folder and then run another process that uses the config files to know how to load the flat file into Oracle. Before I decided to use a parallel option, I tested the performance benefits by iterating 1000 times, each time creating the config files. I had better than a 2x increase in speed.
I then added the part where I call the other process, and I am getting periodic errors that some of the config files I am trying to create per iteration aren't there.
Here is my stripped-down code:
public static void FindFilesToLoad(int monitorId)
{
//left out code here that calls a stored procedure to get a list of ids
fileCount = idList.Count;
if (fileCount != 0)
{
Parallel.For(0, fileCount,
i =>
{
fileId = Convert.ToInt32(idList[i]);
//do the work here...
LoadFileIntoDatabase(monitorId, fileId);
});
}
}
public static void LoadFileIntoDatabase(int monitorId, int fileId)
{
stamp = Guid.NewGuid().ToString();
controlFile = CreateSqlLoaderControlFile(monitorId,stamp);
controlFileName = Path.GetFileName(controlFile);
parFile = CreateParFile(monitorId, controlFileName, stamp);
myCommand = #"CMD.EXE";
ProcessStartInfo startInfo = new ProcessStartInfo(myCommand)
{
WorkingDirectory = #"c:\temp\",
Arguments = #"/c SQLLDR CONTROL=" + controlFile + " PARFILE=" + parFile ,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
exitCode = process.ExitCode;
}
Error example:
SQLLoader-500: Unable to open file (6f46ccfd-986e-427e-ab63-b7ce2396488e.ctl)
SQLLoader-553: file not found
SQL*Loader-509: System error: The system cannot find the file specified

Writing CSV to MemoryStream using LinqToCSV does not return any data

I've verified using System.Text.Encoding.ASCII.GetString(ms.ToArray)); that my memorystream has the expected data.
However using the LinqToCSV nuget library will not generate my csv file. I get no errors or exceptions thrown. I just get an empty file when I'm prompted to open the file.
Here is my Action Method
public FileStreamResult Export(){
var results = _service.GetProperties().Take(3);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.TextWriter txt = new System.IO.StreamWriter(ms);
CsvFileDescription inputFileDescription = new CsvFileDescription{
SeparatorChar =',',
FirstLineHasColumnNames = true
}
;
CsvContext csv = new CsvContext();
csv.Write(results,txt,inputFileDescription);
return File(ms , "application/x-excel");
}
I find it interesting, if I change the return type to contentResult, and the return method to Content() and pass it System.Text.Encoding.ASCII.GetString(ms.ToArray)); I do get a browser window showing my data.
Make sure you reset stream position to 0. Also make sure you flush your StreamWriter before that.
Calling the Web API method to return CVS file from JavaScript.
public HttpResponseMessage Bidreport([FromBody]int formData).....
Fill in your IEnumerable<YourObject>query = from LINQ query
....
This is how to return it:
using (var ms = new MemoryStream())
{
using (TextWriter txt = new StreamWriter(ms))
{
var cc = new CsvContext();
cc.Write(query, txt, outputFileDescription);
txt.Flush();
ms.Position = 0;
var fileData = Encoding.ASCII.GetString(ms.ToArray());
var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(fileData)};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-excel");
return result;
}
}

How to add image dynamically in the jasper reports in java

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));

Resources