use of net.sf.jasperreports.engine.JasperPrint in project dwoss by gg-net.
the class DocumentRendererTryout method main.
public static void main(String[] args) {
DocumentSupporterOperation documentSupporter = new DocumentSupporterOperation();
documentSupporter.setMandator(Sample.MANDATOR);
Dossier dos = new Dossier();
dos.setPaymentMethod(PaymentMethod.ADVANCE_PAYMENT);
dos.setDispatch(true);
dos.setCustomerId(1);
Document doc = new Document();
doc.setTaxType(TaxType.GENERAL_SALES_TAX_DE_SINCE_2007);
doc.setType(DocumentType.ORDER);
doc.setActive(true);
doc.setDirective(Document.Directive.WAIT_FOR_MONEY);
doc.setHistory(new DocumentHistory("JUnit", "Automatische Erstellung eines leeren Dokuments"));
Address a = new Address("Herr Muh\nMuhstrasse 7\n12345 Muhstadt");
doc.setInvoiceAddress(a);
doc.setShippingAddress(a);
dos.add(doc);
NaivBuilderUtil.overwriteTax(doc.getTaxType());
doc.append(NaivBuilderUtil.comment());
doc.append(NaivBuilderUtil.service());
doc.append(NaivBuilderUtil.shippingcost());
System.out.println("Tax: " + doc.getSingleTax());
System.out.println("Netto " + doc.getPrice());
System.out.println("Brutto: " + doc.toAfterTaxPrice());
System.out.println("SumTax: " + (doc.toAfterTaxPrice() - doc.getPrice()));
JasperPrint print = documentSupporter.render(doc, DocumentViewType.DEFAULT);
JRViewer viewer = new JRViewer(print);
JFrame frame = new JFrame("Viewer");
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(viewer, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
use of net.sf.jasperreports.engine.JasperPrint in project lar_361 by comitsrl.
the class ReportStarterWithTxtExporter method startProcess.
/**
* Start the process.
* Called then pressing the Process button in R_Request.
* It should only return false, if the function could not be performed
* as this causes the process to abort.
* @author rlemeill
* @param ctx context
* @param pi standard process info
* @param trx
* @return true if success
*/
public boolean startProcess(Properties ctx, ProcessInfo pi, Trx trx) {
processInfo = pi;
String Name = pi.getTitle();
int AD_PInstance_ID = pi.getAD_PInstance_ID();
int Record_ID = pi.getRecord_ID();
log.info("Name=" + Name + " AD_PInstance_ID=" + AD_PInstance_ID + " Record_ID=" + Record_ID);
String trxName = null;
if (trx != null) {
trxName = trx.getTrxName();
}
ReportData reportData = getReportData(pi, trxName);
if (reportData == null) {
reportResult(AD_PInstance_ID, "Can not find report data", trxName);
return false;
}
String reportPath = reportData.getReportFilePath();
if (Util.isEmpty(reportPath, true)) {
reportResult(AD_PInstance_ID, "Can not find report", trxName);
return false;
}
JasperData data = null;
File reportFile = null;
String fileExtension = "";
HashMap<String, Object> params = new HashMap<String, Object>();
addProcessParameters(AD_PInstance_ID, params, trxName);
addProcessInfoParameters(params, pi.getParameter());
reportFile = getReportFile(reportPath, (String) params.get("ReportType"));
if (reportFile == null || reportFile.exists() == false) {
log.severe("No report file found for given type, falling back to " + reportPath);
reportFile = getReportFile(reportPath);
}
if (reportFile == null || reportFile.exists() == false) {
String tmp = "Can not find report file at path - " + reportPath;
log.severe(tmp);
reportResult(AD_PInstance_ID, tmp, trxName);
}
if (reportFile != null) {
data = processReport(reportFile);
fileExtension = reportFile.getName().substring(reportFile.getName().lastIndexOf("."), reportFile.getName().length());
} else {
return false;
}
JasperReport jasperReport = data.getJasperReport();
String jasperName = data.getJasperName();
String name = jasperReport.getName();
File reportDir = data.getReportDir();
// Add reportDir to class path
ClassLoader scl = ClassLoader.getSystemClassLoader();
try {
java.net.URLClassLoader ucl = new java.net.URLClassLoader(new java.net.URL[] { reportDir.toURI().toURL() }, scl);
net.sf.jasperreports.engine.util.JRResourcesUtil.setThreadClassLoader(ucl);
} catch (MalformedURLException me) {
log.warning("Could not add report directory to classpath: " + me.getMessage());
}
if (jasperReport != null) {
File[] subreports;
// Subreports
if (reportPath.startsWith("http://") || reportPath.startsWith("https://")) {
// Locate and download subreports from remote webcontext
subreports = getHttpSubreports(jasperName + "Subreport", reportPath, fileExtension);
} else if (reportPath.startsWith("attachment:")) {
subreports = getAttachmentSubreports(reportPath);
} else if (reportPath.startsWith("resource:")) {
subreports = getResourceSubreports(name + "Subreport", reportPath, fileExtension);
} else // TODO: Implement file:/ lookup for subreports
{
// Locate subreports from local/remote filesystem
subreports = reportDir.listFiles(new FileFilter(jasperName + "Subreport", reportDir, fileExtension));
}
for (int i = 0; i < subreports.length; i++) {
// @Trifon - begin
if (subreports[i].getName().toLowerCase().endsWith(".jasper") || subreports[i].getName().toLowerCase().endsWith(".jrxml")) {
JasperData subData = processReport(subreports[i]);
if (subData.getJasperReport() != null) {
params.put(subData.getJasperName(), subData.getJasperFile().getAbsolutePath());
}
}
// @Trifon - end
}
if (Record_ID > 0)
params.put("RECORD_ID", new Integer(Record_ID));
// contribution from Ricardo (ralexsander)
// in iReports you can 'SELECT' AD_Client_ID, AD_Org_ID and AD_User_ID using only AD_PINSTANCE_ID
params.put("AD_PINSTANCE_ID", new Integer(AD_PInstance_ID));
// FR [3123850] - Add continuosly needed parameters to Jasper Starter - Carlos Ruiz - GlobalQSS
params.put("AD_CLIENT_ID", new Integer(Env.getAD_Client_ID(Env.getCtx())));
params.put("AD_ROLE_ID", new Integer(Env.getAD_Role_ID(Env.getCtx())));
params.put("AD_USER_ID", new Integer(Env.getAD_User_ID(Env.getCtx())));
Language currLang = Env.getLanguage(Env.getCtx());
String printerName = null;
MPrintFormat printFormat = null;
PrintInfo printInfo = null;
ProcessInfoParameter[] pip = pi.getParameter();
// Get print format and print info parameters
if (pip != null) {
for (int i = 0; i < pip.length; i++) {
if (ReportCtl.PARAM_PRINT_FORMAT.equalsIgnoreCase(pip[i].getParameterName())) {
printFormat = (MPrintFormat) pip[i].getParameter();
}
if (ReportCtl.PARAM_PRINT_INFO.equalsIgnoreCase(pip[i].getParameterName())) {
printInfo = (PrintInfo) pip[i].getParameter();
}
if (ReportCtl.PARAM_PRINTER_NAME.equalsIgnoreCase(pip[i].getParameterName())) {
printerName = (String) pip[i].getParameter();
}
}
}
if (printFormat != null) {
if (printInfo != null) {
// Set the language of the print format if we're printing a document
if (printInfo.isDocument()) {
currLang = printFormat.getLanguage();
}
}
// Set printer name unless already set.
if (printerName == null) {
printerName = printFormat.getPrinterName();
}
}
params.put("CURRENT_LANG", currLang.getAD_Language());
params.put(JRParameter.REPORT_LOCALE, currLang.getLocale());
// Resources
File resFile = null;
if (reportPath.startsWith("attachment:") && attachment != null) {
resFile = getAttachmentResourceFile(jasperName, currLang);
} else if (reportPath.startsWith("resource:")) {
resFile = getResourcesForResourceFile(jasperName, currLang);
// TODO: Implement file:/ for resources
} else {
resFile = new File(jasperName + "_" + currLang.getLocale().getLanguage() + ".properties");
if (!resFile.exists()) {
resFile = null;
}
if (resFile == null) {
resFile = new File(jasperName + ".properties");
if (!resFile.exists()) {
resFile = null;
}
}
}
if (resFile != null) {
try {
PropertyResourceBundle res = new PropertyResourceBundle(new FileInputStream(resFile));
params.put("RESOURCE", res);
} catch (IOException e) {
;
}
}
Connection conn = null;
try {
conn = getConnection();
jasperPrint = JasperFillManager.fillReport(jasperReport, params, conn);
// @Marcos Custom - begin
log.info("ReportStarterWithTxtExporter.startProcess print report -" + jasperPrint.getName());
String Param_Inicial;
String Param_Final;
if (params.containsKey("FECHA_INICIAL_Info1"))
Param_Inicial = params.get("FECHA_INICIAL_Info1").toString();
else
Param_Inicial = "";
if (params.containsKey("FECHA_FINAL_Info1"))
Param_Final = "_al_" + params.get("FECHA_FINAL_Info1").toString();
else
Param_Final = "";
String fileName = new String(jasperPrint.getName() + "_" + Param_Inicial.replace("/", "-") + Param_Final.replace("/", "-") + ".txt");
JRTextExporter jrtxt = new JRTextExporter();
File destFile = new File(fileName);
Integer PageWidth = jasperPrint.getPageWidth();
Integer CharWidth = 10;
Integer Par_PageWidth = PageWidth / CharWidth;
jrtxt.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
jrtxt.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());
jrtxt.setParameter(JRTextExporterParameter.CHARACTER_WIDTH, new Float(10));
jrtxt.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT, new Float(20));
jrtxt.setParameter(JRTextExporterParameter.PAGE_WIDTH, Par_PageWidth.floatValue());
try {
jrtxt.exportReport();
log.info("Archivo Exportado: ");
if (Env.getWindow(0) != null)
ADialog.info(0, Env.getWindow(0), "Archivo Exportado:", fileName);
} catch (JRException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// @Marcos Custom - end
if (reportData.isDirectPrint()) {
log.info("ReportStarterWithTxtExporter.startProcess print report -" + jasperPrint.getName());
// RF 1906632
if (!processInfo.isBatch()) {
// Get printer job
PrinterJob printerJob = org.compiere.print.CPrinter.getPrinterJob(printerName);
// Set print request attributes
// Paper Attributes:
PrintRequestAttributeSet prats = new HashPrintRequestAttributeSet();
// add: copies, job-name, priority
if (// @Trifon
printInfo == null || printInfo.isDocumentCopy() || printInfo.getCopies() < 1)
prats.add(new Copies(1));
else
prats.add(new Copies(printInfo.getCopies()));
Locale locale = Language.getLoginLanguage().getLocale();
// @Trifon
String printFormat_name = printFormat == null ? "" : printFormat.getName();
int numCopies = printInfo == null ? 0 : printInfo.getCopies();
prats.add(new JobName(printFormat_name + "_" + pi.getRecord_ID(), locale));
prats.add(PrintUtil.getJobPriority(jasperPrint.getPages().size(), numCopies, true));
// Create print service exporter
JRPrintServiceExporter exporter = new JRPrintServiceExporter();
;
// Set parameters
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, printerJob.getPrintService());
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, printerJob.getPrintService().getAttributes());
exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, prats);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);
exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.FALSE);
// Print report / document
exporter.exportReport();
} else {
// Used For the PH
try {
File PDF = File.createTempFile("mail", ".pdf");
JasperExportManager.exportReportToPdfFile(jasperPrint, PDF.getAbsolutePath());
processInfo.setPDFReport(PDF);
} catch (IOException e) {
log.severe("ReportStarterWithTxtExporter.startProcess: Can not make PDF File - " + e.getMessage());
}
}
// You can use JasperPrint to create PDF
// JasperExportManager.exportReportToPdfFile(jasperPrint, "BasicReport.pdf");
} else {
// @Marcos : ProcessCtl.java llama a ReportStarter y se vuelve a generar la visualizacion del reporte.
// log.info( "ReportStarterWithTxtExporter.startProcess run report -"+jasperPrint.getName());
// JRViewerProvider viewerLauncher = getReportViewerProvider();
// viewerLauncher.openViewer(jasperPrint, pi.getTitle()+" - " + reportPath);
}
} catch (JRException e) {
log.severe("ReportStarterWithTxtExporter.startProcess: Can not run report - " + e.getMessage());
} finally {
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
}
}
}
reportResult(AD_PInstance_ID, null, trxName);
return true;
}
use of net.sf.jasperreports.engine.JasperPrint in project dhis2-core by dhis2.
the class GridUtils method toJasperReport.
/**
* Writes a Jasper Reports representation of the given Grid to the given
* OutputStream.
*/
public static void toJasperReport(Grid grid, Map<String, Object> params, OutputStream out) throws Exception {
if (grid == null) {
return;
}
final StringWriter writer = new StringWriter();
render(grid, params, writer, JASPER_TEMPLATE);
String report = writer.toString();
JasperReport jasperReport = JasperCompileManager.compileReport(IOUtils.toInputStream(report, StandardCharsets.UTF_8));
JasperPrint print = JasperFillManager.fillReport(jasperReport, params, grid);
JasperExportManager.exportReportToPdfStream(print, out);
}
use of net.sf.jasperreports.engine.JasperPrint in project dhis2-core by dhis2.
the class ReportController method getReport.
// -------------------------------------------------------------------------
// Supportive methods
// -------------------------------------------------------------------------
private void getReport(HttpServletRequest request, HttpServletResponse response, String uid, String organisationUnitUid, String isoPeriod, Date date, String type, String contentType, boolean attachment) throws Exception {
Report report = reportService.getReport(uid);
if (report == null) {
throw new WebMessageException(notFound("Report not found for identifier: " + uid));
}
if (organisationUnitUid == null && report.hasVisualization() && report.getVisualization().hasReportingParams() && report.getVisualization().getReportingParams().isOrganisationUnitSet()) {
List<OrganisationUnit> rootUnits = organisationUnitService.getRootOrganisationUnits();
organisationUnitUid = !rootUnits.isEmpty() ? rootUnits.get(0).getUid() : null;
}
if (report.isTypeHtml()) {
contextUtils.configureResponse(response, ContextUtils.CONTENT_TYPE_HTML, report.getCacheStrategy());
reportService.renderHtmlReport(response.getWriter(), uid, date, organisationUnitUid);
} else {
date = date != null ? date : new DateTime().minusMonths(1).toDate();
Period period = isoPeriod != null ? PeriodType.getPeriodFromIsoString(isoPeriod) : new MonthlyPeriodType().createPeriod(date);
String filename = CodecUtils.filenameEncode(report.getName()) + "." + type;
contextUtils.configureResponse(response, contentType, report.getCacheStrategy(), filename, attachment);
JasperPrint print = reportService.renderReport(response.getOutputStream(), uid, period, organisationUnitUid, type);
if (ReportType.HTML.name().equalsIgnoreCase(type)) {
request.getSession().setAttribute(BaseHttpServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, print);
}
}
}
use of net.sf.jasperreports.engine.JasperPrint in project BibliotecaPraticas by athayyr.
the class IReport method iReport.
public void iReport() {
Connection connection = ConnectionFactory.getConnection();
String src = Properties.getConfiguracaoValue(Properties.IREPORT);
// String src = "src\\br\\com\\praticas\\iReport\\Relatorio.jasper";
JasperPrint jp = null;
try {
jp = JasperFillManager.fillReport(src, null, connection);
} catch (JRException ex) {
Logger.getLogger(IReport.class.getName()).log(Level.SEVERE, null, ex);
}
JasperViewer jV = new JasperViewer(jp, false);
jV.setVisible(true);
}
Aggregations