List of usage examples for com.lowagie.text Document close
boolean close
To view the source code for com.lowagie.text Document close.
Click Source Link
From source file:ispyb.common.util.export.PdfExporterSample.java
License:Open Source License
/** * Exports the file for viewSample for shipment * //www. j a va 2 s. co m * @return * @throws Exception */ public ByteArrayOutputStream exportAsPdf() throws Exception { // create simple doc and write to a ByteArrayOutputStream Document document = new Document(PageSize.A4.rotate(), 20, 20, 20, 20); document.addTitle("exportSamplesView"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); HeaderFooter header; // header + footer if (viewName != null) header = new HeaderFooter(new Phrase("Samples for Proposal: " + proposalDesc + " --- " + viewName), false); else header = new HeaderFooter(new Phrase("Samples for Proposal: " + proposalDesc), false); header.setAlignment(Element.ALIGN_CENTER); header.setBorderWidth(1); header.getBefore().getFont().setSize(8); HeaderFooter footer = new HeaderFooter(new Phrase("Page n."), true); footer.setAlignment(Element.ALIGN_RIGHT); footer.setBorderWidth(1); footer.getBefore().getFont().setSize(6); document.setHeader(header); document.setFooter(footer); document.open(); if (aList.isEmpty()) { document.add(new Paragraph("There is no samples in this report")); document.close(); return baos; } // Create first table for samples int NumColumns = 19; PdfPTable table = new PdfPTable(NumColumns); int headerwidths[] = { 6, 6, 6, 6, 6, 4, 6, 4, 4, 4, 4, 4, 4, 8, 5, 5, 5, 10, 6 }; // percentage table.setWidths(headerwidths); table.setWidthPercentage(100); // percentage table.getDefaultCell().setPadding(3); table.getDefaultCell().setBorderWidth(1); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // header PdfPCell cell = new PdfPCell(); table.addCell(new Paragraph("Protein", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Sample name", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Smp code", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Dewar", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Container", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Loc. in cont.", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Space group", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Cell a", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Cell b", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Cell c", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Cell alpha", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Cell beta", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Cell gamma", new Font(Font.HELVETICA, 8))); cell = new PdfPCell(new Paragraph("Crystal comments", new Font(Font.HELVETICA, 8))); table.addCell(cell); table.addCell(new Paragraph("Already observed resol.", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Required resol.", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Min. resol.", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Sample comments", new Font(Font.HELVETICA, 8))); table.addCell(new Paragraph("Sample status", new Font(Font.HELVETICA, 8))); table.setHeaderRows(1); // this is the end of the table header table.getDefaultCell().setBorderWidth(1); DecimalFormat df1 = new DecimalFormat("#####0.0"); DecimalFormat df2 = new DecimalFormat("#####0.00"); Iterator it = aList.iterator(); int i = 1; String currentContainer = "next"; String nextContainer = "next"; while (it.hasNext()) { table.getDefaultCell().setGrayFill(0.99f); if (i % 2 == 1) { table.getDefaultCell().setGrayFill(0.9f); } BLSample3VO samplefv = (BLSample3VO) it.next(); LOG.debug("table of datacollections pdf " + samplefv.getBlSampleId()); if (samplefv.getContainerVO() != null && samplefv.getContainerVO().getCode() != null) nextContainer = samplefv.getContainerVO().getCode(); else nextContainer = "next"; // in the case of view sorted by dewar/container, we add a page break afetr each container if (sortView.equals("2") && !currentContainer.equals(nextContainer)) { document.add(table); table.deleteBodyRows(); document.newPage(); } if (samplefv.getCrystalVO().getProteinVO().getAcronym() != null) table.addCell(new Paragraph(samplefv.getCrystalVO().getProteinVO().getAcronym(), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getName() != null) table.addCell(new Paragraph(samplefv.getName(), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getCode() != null) table.addCell(new Paragraph(samplefv.getCode(), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getContainerVO() != null && samplefv.getContainerVO().getDewarVO() != null && samplefv.getContainerVO().getDewarVO().getCode() != null) table.addCell(new Paragraph(samplefv.getContainerVO().getDewarVO().getCode(), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getContainerVO() != null && samplefv.getContainerVO().getCode() != null) { currentContainer = samplefv.getContainerVO().getCode(); table.addCell(new Paragraph(currentContainer, new Font(Font.HELVETICA, 8))); } else { currentContainer = "current"; table.addCell(""); } if (samplefv.getLocation() != null) table.addCell(new Paragraph(samplefv.getLocation(), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getCrystalVO().getSpaceGroup() != null) table.addCell(new Paragraph(samplefv.getCrystalVO().getSpaceGroup(), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getCrystalVO().getCellA() != null) table.addCell( new Paragraph(df1.format(samplefv.getCrystalVO().getCellA()), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getCrystalVO().getCellB() != null) table.addCell( new Paragraph(df1.format(samplefv.getCrystalVO().getCellB()), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getCrystalVO().getCellC() != null) table.addCell( new Paragraph(df1.format(samplefv.getCrystalVO().getCellC()), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getCrystalVO().getCellAlpha() != null) table.addCell(new Paragraph(df1.format(samplefv.getCrystalVO().getCellAlpha()), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getCrystalVO().getCellBeta() != null) table.addCell(new Paragraph(df1.format(samplefv.getCrystalVO().getCellBeta()), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getCrystalVO().getCellGamma() != null) table.addCell(new Paragraph(df1.format(samplefv.getCrystalVO().getCellGamma()), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getCrystalVO().getComments() != null) table.addCell(new Paragraph(samplefv.getCrystalVO().getComments(), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getDiffractionPlanVO() != null && samplefv.getDiffractionPlanVO().getObservedResolution() != null) { table.addCell(new Paragraph(df2.format(samplefv.getDiffractionPlanVO().getObservedResolution()), new Font(Font.HELVETICA, 8))); } else if (samplefv.getCrystalVO().getDiffractionPlanVO() != null && samplefv.getCrystalVO().getDiffractionPlanVO().getObservedResolution() != null) table.addCell(new Paragraph( df2.format(samplefv.getCrystalVO().getDiffractionPlanVO().getObservedResolution()), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getDiffractionPlanVO() != null && samplefv.getDiffractionPlanVO().getRequiredResolution() != null) { table.addCell(new Paragraph(df2.format(samplefv.getDiffractionPlanVO().getRequiredResolution()), new Font(Font.HELVETICA, 8))); } else if (samplefv.getCrystalVO().getDiffractionPlanVO() != null && samplefv.getCrystalVO().getDiffractionPlanVO().getRequiredResolution() != null) table.addCell(new Paragraph( df2.format(samplefv.getCrystalVO().getDiffractionPlanVO().getRequiredResolution()), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getDiffractionPlanVO() != null && samplefv.getDiffractionPlanVO().getMinimalResolution() != null) { table.addCell(new Paragraph(df2.format(samplefv.getDiffractionPlanVO().getMinimalResolution()), new Font(Font.HELVETICA, 8))); } else if (samplefv.getCrystalVO().getDiffractionPlanVO() != null && samplefv.getCrystalVO().getDiffractionPlanVO().getMinimalResolution() != null) table.addCell(new Paragraph( df2.format(samplefv.getCrystalVO().getDiffractionPlanVO().getMinimalResolution()), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getComments() != null && samplefv.getComments() != "") table.addCell(new Paragraph(samplefv.getComments(), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (samplefv.getBlSampleStatus() != null) table.addCell(new Paragraph(samplefv.getBlSampleStatus(), new Font(Font.HELVETICA, 8))); else table.addCell(""); if (i % 2 == 1) { table.getDefaultCell().setGrayFill(0.0f); } i++; } document.add(table); document.close(); return baos; }
From source file:it.eng.spagobi.engines.chart.Utilities.ExportCharts.java
License:Mozilla Public License
public static void transformSVGIntoPDF(InputStream inputStream, OutputStream outputStream) throws IOException, DocumentException { FileOutputStream imageFileOutputStream = null; File imageFile = null;// w w w . j a v a 2 s . c o m try { imageFile = File.createTempFile("chart", ".jpg"); imageFileOutputStream = new FileOutputStream(imageFile); transformSVGIntoPNG(inputStream, imageFileOutputStream); Document pdfDocument = new Document(PageSize.A4.rotate()); PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, outputStream); pdfDocument.open(); Image jpg = Image.getInstance(imageFile.getPath()); fitImage(jpg); pdfDocument.add(jpg); pdfDocument.close(); docWriter.close(); } finally { if (imageFileOutputStream != null) { try { imageFileOutputStream.close(); } catch (IOException e) { logger.error(e); } } if (imageFile.exists()) { imageFile.delete(); } } }
From source file:it.eng.spagobi.engines.documentcomposition.exporterUtils.PdfCreator.java
License:Mozilla Public License
public FileOutputStream createPdfFile(FileOutputStream fileOutputStream, Map<String, DocumentContainer> documentsMap, boolean defaultStyle) throws MalformedURLException, IOException, DocumentException { logger.debug("IN"); Document document = new Document(PageSize.A4.rotate()); Rectangle rect = document.getPageSize(); docWidth = rect.getWidth();//from w ww.j av a2s. c o m docHeight = rect.getHeight(); logger.debug("document size width: " + docWidth + " height: " + docHeight); //PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream("C:/comp/SpagoBIProva.pdf")); PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream); document.open(); int documentsNumber = documentsMap.keySet().size(); int columnnsNumber = 2; if (defaultStyle == true) { logger.debug("use default style"); int cellsCounter = 0; PdfPTable table = new PdfPTable(columnnsNumber); table.setWidthPercentage(100); for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) { String label = (String) iterator.next(); DocumentContainer docContainer = documentsMap.get(label); byte[] content = docContainer.getContent(); if (content != null) { Image img = null; try { img = Image.getInstance(content); table.addCell(img); } catch (Exception e) { logger.debug("Trying to evaluate response as a PDF file... "); table.addCell(""); // try { // PdfReader reader = new PdfReader(content); // PdfImportedPage page = writer.getImportedPage(reader, 1); // writer.addPage(page); // table.addCell(""); // } catch (Exception x) { // logger.error("Error in inserting image for document " + label, e); // logger.error("Error in inserting pdf file for document " + label, x); // table.addCell(""); // } } } cellsCounter++; } // if cell counter is not pair make it pair if (cellsCounter % 2 != 0) { table.addCell(""); } document.add(table); } else { // ************* NO DEFAULT STYLE ***************** logger.debug("No default style"); // I want to calculate total height of scaled heights!! //int totalScaledHeight=calculateTotaleScaledHeights(documentsMap, defaultStyle); // run on all documents for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) { String label = (String) iterator.next(); logger.debug("document with label " + label); DocumentContainer docContainer = documentsMap.get(label); MetadataStyle style = docContainer.getStyle(); // one table for each image, set at absolute position PdfPTable table = new PdfPTable(1); // width and height specified for the container by style attribute int widthStyle = style.getWidth(); int heightStyle = style.getHeight(); logger.debug("style for document width: " + widthStyle + " height: " + heightStyle); // width and height for the table scaled to the document size int tableWidth = calculatePxSize(docWidth, widthStyle, videoWidth); int tableHeight = calculatePxSize(docHeight, heightStyle, videoHeight); logger.debug("table for document width: " + tableWidth + " height: " + tableHeight); // x and y position as specified for the container by the style attribute int yStyle = style.getY(); int xStyle = style.getX(); // width and height scaled to the document size int xPos = (calculatePxPos(docWidth, xStyle, videoWidth)); int yPos = (int) docHeight - (calculatePxPos(docHeight, yStyle, videoHeight)); logger.debug("Table position at x: " + xPos + " y: " + yPos); // get the image byte[] content = docContainer.getContent(); if (content != null) { Image img = null; try { img = Image.getInstance(content); } catch (Exception e) { logger.debug("Trying to evaluate response as a PDF file... "); try { PdfReader reader = new PdfReader(content); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage page = writer.getImportedPage(reader, 1); float[] tm = getTransformationMatrix(page, xPos, yPos, tableWidth, tableHeight); cb.addTemplate(page, tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]); } catch (Exception x) { logger.error("Error in inserting image for document " + label, e); logger.error("Error in inserting pdf file for document " + label, x); } continue; } //if it is a REPORT and has more than one page, too large, you have to resize the image, but how to understand it? // if image size is more than double of the container size cut the first part,otherwise scale it if (docContainer.getDocumentType().equals("REPORT")) { boolean cutImageWIdth = isToCutWidth(img, tableWidth); boolean cutImageHeight = isToCutHeight(img, tableWidth); if (cutImageWIdth == true || cutImageHeight == true) { logger.debug( "Report will be cut to width " + tableWidth + " and height " + tableHeight); try { img = cutImage(content, cutImageHeight, cutImageWIdth, tableHeight, tableWidth, (int) img.getWidth(), (int) img.getHeight()); } catch (Exception e) { logger.error( "Error in image cut, cutt will be ignored and image will be drawn anyway ", e); } } } // this is percentage to resize // The image must be size within the cell int percToResize = percentageToResize((int) img.getWidth(), (int) img.getHeight(), tableWidth, tableHeight); logger.debug("image will be scaled of percentage " + percToResize); img.scalePercent(percToResize); PdfPCell cell = new PdfPCell(img); cell.setNoWrap(true); cell.setFixedHeight(tableHeight); cell.setBorderWidth(0); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_CENTER); table.addCell(cell); //table.setWidthPercentage(tableWidthPerc); table.setTotalWidth(tableWidth); table.setLockedWidth(true); } else { // TODO: setALT! } logger.debug("Add table"); table.writeSelectedRows(0, -1, xPos, yPos, writer.getDirectContent()); logger.debug("Document added"); } } document.close(); logger.debug("OUT"); return fileOutputStream; }
From source file:it.eng.spagobi.engines.exporters.ChartExporter.java
License:Mozilla Public License
public File getChartPDF(String uuid, boolean multichart, String orientation) throws Exception { logger.debug("IN"); File tmpFile;//from ww w. j ava 2s . c om try { tmpFile = null; String dir = System.getProperty("java.io.tmpdir"); String path = (new StringBuilder(String.valueOf(dir))).append("/").append(uuid).append(".png") .toString(); File dirF = new File(dir); tmpFile = File.createTempFile("tempPDFExport", ".pdf", dirF); Document pdfDocument = new Document(); PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(tmpFile)); //pdfDocument.open(); if (multichart) { pdfDocument.open(); List images = new ArrayList(); for (int i = 0; i < MAX_NUM_IMG; i++) { String imgName = (new StringBuilder(String.valueOf(path.substring(0, path.indexOf(".png"))))) .append(i).append(".png").toString(); Image png = Image.getInstance(imgName); if (png == null) { break; } images.add(png); } Table table = new Table(images.size()); for (int i = 0; i < images.size(); i++) { Image png = (Image) images.get(i); if (HORIZONTAL_ORIENTATION.equalsIgnoreCase(orientation)) { Cell pngCell = new Cell(png); pngCell.setBorder(0); table.setBorder(0); table.addCell(pngCell); } else { png.setAlignment(5); pdfDocument.add(png); } } pdfDocument.add(table); } else { Image jpg = Image.getInstance(path); float height = jpg.getHeight(); float width = jpg.getWidth(); // if in need to change layout if (width > MAX_WIDTH || height > MAX_HEIGHT) { changeLayout(pdfDocument, jpg, width, height); } pdfDocument.open(); pdfDocument.add(jpg); } pdfDocument.close(); docWriter.close(); logger.debug("OUT"); return tmpFile; } catch (Throwable e) { logger.error("An exception has occured", e); throw new Exception(e); } finally { //tmpFile.delete(); } }
From source file:it.eng.spagobi.engines.geo.service.DrawMapAction.java
License:Mozilla Public License
public void service(SourceBean serviceRequest, SourceBean serviceResponse) { String outputFormat = null;// ww w.ja v a 2s . c o m String executionId = null; File maptmpfile = null; boolean inlineResponse; String responseFileName; Monitor totalTimeMonitor = null; Monitor totalTimePerFormatMonitor = null; Monitor flushingResponseTotalTimeMonitor = null; Monitor errorHitsMonitor = null; logger.debug("IN"); try { super.service(serviceRequest, serviceResponse); totalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.totalTime"); executionId = getAttributeAsString("SBI_EXECUTION_ID"); outputFormat = getAttributeAsString(OUTPUT_FORMAT); logger.debug("Parameter [" + OUTPUT_FORMAT + "] is equal to [" + outputFormat + "]"); inlineResponse = getAttributeAsBoolean(INLINE_RESPONSE, true); logger.debug("Parameter [" + INLINE_RESPONSE + "] is equal to [" + inlineResponse + "]"); if (getAuditServiceProxy() != null) getAuditServiceProxy().notifyServiceStartEvent(); if (outputFormat == null) { logger.info("Parameter [" + outputFormat + "] not specified into request"); outputFormat = (String) getGeoEngineInstance().getEnv().get(GeoEngineConstants.ENV_OUTPUT_TYPE); logger.debug("Env Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] is equal to [" + outputFormat + "]"); } if (outputFormat == null) { logger.info( "Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] not specified into environment"); outputFormat = DEFAULT_OUTPUT_TYPE; } totalTimePerFormatMonitor = MonitorFactory .start("GeoEngine.drawMapAction." + outputFormat + "totalTime"); try { if (outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)) { maptmpfile = getGeoEngineInstance().renderMap(GeoEngineConstants.JPEG); } else { maptmpfile = getGeoEngineInstance().renderMap(outputFormat); } } catch (Throwable t) { throw new DrawMapServiceException(getActionName(), "Impossible to render map", t); } responseFileName = "map.svg"; IStreamEncoder encoder = null; File tmpFile = null; if (outputFormat.equalsIgnoreCase(GeoEngineConstants.JPEG)) { encoder = new SVGMapConverter(); responseFileName = "map.jpeg"; } else if (outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)) { encoder = new SVGMapConverter(); BufferedInputStream bis = null; String dirS = System.getProperty("java.io.tmpdir"); File imageFile = null; bis = new BufferedInputStream(new FileInputStream(maptmpfile)); try { int contentLength = 0; int b = -1; String contentFileName = "tempJPEGExport"; freezeHttpResponse(); File dir = new File(dirS); imageFile = File.createTempFile("tempJPEGExport", ".jpeg", dir); FileOutputStream stream = new FileOutputStream(imageFile); encoder.encode(bis, stream); stream.flush(); stream.close(); File dirF = new File(dirS); tmpFile = File.createTempFile("tempPDFExport", ".pdf", dirF); Document pdfDocument = new Document(); PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(tmpFile)); pdfDocument.open(); Image jpg = Image.getInstance(imageFile.getPath()); jpg.setRotation(new Double(Math.PI / 2).floatValue()); jpg.scaleAbsolute(770, 520); pdfDocument.add(jpg); pdfDocument.close(); docWriter.close(); maptmpfile = tmpFile; } finally { bis.close(); if (imageFile != null) imageFile.delete(); } responseFileName = "map.pdf"; encoder = null; } try { flushingResponseTotalTimeMonitor = MonitorFactory .start("GeoEngine.drawMapAction.flushResponse.totalTime"); writeBackToClient(maptmpfile, encoder, inlineResponse, responseFileName, getContentType(outputFormat)); } catch (IOException e) { logger.error("error while flushing output", e); if (getAuditServiceProxy() != null) getAuditServiceProxy().notifyServiceErrorEvent("Error while flushing output"); throw new DrawMapServiceException(getActionName(), "Error while flushing output", e); } if (getAuditServiceProxy() != null) getAuditServiceProxy().notifyServiceEndEvent(); maptmpfile.delete(); if (tmpFile != null) tmpFile.delete(); } catch (Throwable t) { errorHitsMonitor = MonitorFactory.start("GeoEngine.errorHits"); errorHitsMonitor.stop(); DrawMapServiceException wrappedException; if (t instanceof DrawMapServiceException) { wrappedException = (DrawMapServiceException) t; } else { wrappedException = new DrawMapServiceException(getActionName(), "An unpredicted error occurred while executing " + getActionName() + " service", t); } wrappedException.setDescription(wrappedException.getRootCause()); Throwable rootException = wrappedException.getRootException(); if (rootException instanceof SpagoBIEngineRuntimeException) { wrappedException.setHints(((SpagoBIEngineRuntimeException) rootException).getHints()); } throw wrappedException; } finally { if (flushingResponseTotalTimeMonitor != null) flushingResponseTotalTimeMonitor.stop(); if (totalTimePerFormatMonitor != null) totalTimePerFormatMonitor.stop(); if (totalTimeMonitor != null) totalTimeMonitor.stop(); } logger.debug("OUT"); }
From source file:it.eng.spagobi.engines.geo.service.initializer.ExecutionProxyGeoEngineStartAction.java
License:Mozilla Public License
public void service(SourceBean serviceRequest, SourceBean serviceResponse) throws GeoEngineException { GeoEngineInstance geoEngineInstance; Map env;//from w w w. j a v a2 s . c o m byte[] analysisStateRowData; GeoEngineAnalysisState analysisState = null; String executionContext; String executionId; String documentLabel; String outputType; Monitor hitsPrimary = null; Monitor hitsByDate = null; Monitor hitsByUserId = null; Monitor hitsByDocumentId = null; Monitor hitsByExecutionContext = null; logger.debug("IN"); try { setEngineName(ENGINE_NAME); super.service(serviceRequest, serviceResponse); //if(true) throw new SpagoBIEngineStartupException(getEngineName(), "Test exception"); logger.debug("User Id: " + getUserId()); logger.debug("Audit Id: " + getAuditId()); logger.debug("Document Id: " + getDocumentId()); logger.debug("Template: " + getTemplateAsSourceBean()); hitsPrimary = MonitorFactory.startPrimary("GeoEngine.requestHits"); hitsByDate = MonitorFactory.start( "GeoEngine.requestHits." + DateFormat.getDateInstance(DateFormat.SHORT).format(new Date())); hitsByUserId = MonitorFactory.start("GeoEngine.requestHits." + getUserId()); hitsByDocumentId = MonitorFactory.start("GeoEngine.requestHits." + getDocumentId()); executionContext = getAttributeAsString(EXECUTION_CONTEXT); logger.debug("Parameter [" + EXECUTION_CONTEXT + "] is equal to [" + executionContext + "]"); executionId = getAttributeAsString(EXECUTION_ID); logger.debug("Parameter [" + EXECUTION_ID + "] is equal to [" + executionId + "]"); documentLabel = getAttributeAsString(DOCUMENT_LABEL); logger.debug("Parameter [" + DOCUMENT_LABEL + "] is equal to [" + documentLabel + "]"); outputType = getAttributeAsString(OUTPUT_TYPE); logger.debug("Parameter [" + OUTPUT_TYPE + "] is equal to [" + outputType + "]"); logger.debug("Execution context: " + executionContext); String isDocumentCompositionModeActive = (executionContext != null && executionContext.equalsIgnoreCase("DOCUMENT_COMPOSITION")) ? "TRUE" : "FALSE"; logger.debug("Document composition mode active: " + isDocumentCompositionModeActive); hitsByExecutionContext = MonitorFactory.start("GeoEngine.requestHits." + (isDocumentCompositionModeActive.equalsIgnoreCase("TRUE") ? "compositeDocument" : "singleDocument")); env = getEnv("TRUE".equalsIgnoreCase(isDocumentCompositionModeActive), documentLabel, executionId); if (outputType != null) { env.put(GeoEngineConstants.ENV_OUTPUT_TYPE, outputType); } geoEngineInstance = GeoEngine.createInstance(getTemplateAsSourceBean(), env); geoEngineInstance.setAnalysisMetadata(getAnalysisMetadata()); analysisStateRowData = getAnalysisStateRowData(); if (analysisStateRowData != null) { logger.debug("AnalysisStateRowData: " + new String(analysisStateRowData)); analysisState = new GeoEngineAnalysisState(); analysisState.load(analysisStateRowData); logger.debug("AnalysisState: " + analysisState.toString()); } else { logger.debug("AnalysisStateRowData: NULL"); } if (analysisState != null) { geoEngineInstance.setAnalysisState(analysisState); } String selectedMeasureName = getAttributeAsString("default_kpi"); logger.debug("Parameter [" + "default_kpi" + "] is equal to [" + selectedMeasureName + "]"); if (!StringUtilities.isEmpty(selectedMeasureName)) { geoEngineInstance.getMapRenderer().setSelectedMeasureName(selectedMeasureName); } if ("TRUE".equalsIgnoreCase(isDocumentCompositionModeActive)) { setAttribute(DynamicPublisher.PUBLISHER_NAME, "SIMPLE_UI_PUBLISHER"); } else { setAttribute(DynamicPublisher.PUBLISHER_NAME, "AJAX_UI_PUBLISHER"); } String id = getAttributeAsString("SBI_EXECUTION_ID"); setAttributeInSession(GEO_ENGINE_INSTANCE, geoEngineInstance); } catch (Exception e) { SpagoBIEngineStartupException serviceException = null; if (e instanceof SpagoBIEngineStartupException) { serviceException = (SpagoBIEngineStartupException) e; } else { Throwable rootException = e; while (rootException.getCause() != null) { rootException = rootException.getCause(); } String str = rootException.getMessage() != null ? rootException.getMessage() : rootException.getClass().getName(); String message = "An unpredicted error occurred while executing " + getEngineName() + " service." + "\nThe root cause of the error is: " + str; serviceException = new SpagoBIEngineStartupException(getEngineName(), message, e); } throw serviceException; } finally { if (hitsByExecutionContext != null) hitsByExecutionContext.stop(); if (hitsByDocumentId != null) hitsByDocumentId.stop(); if (hitsByUserId != null) hitsByUserId.stop(); if (hitsByDate != null) hitsByDate.stop(); if (hitsPrimary != null) hitsPrimary.stop(); } // Put draw Map Action String outputFormat = null; File maptmpfile = null; boolean inlineResponse; String responseFileName; Monitor totalTimeMonitor = null; Monitor totalTimePerFormatMonitor = null; Monitor flushingResponseTotalTimeMonitor = null; Monitor errorHitsMonitor = null; logger.debug("IN"); try { super.service(serviceRequest, serviceResponse); totalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.totalTime"); //executionId = getAttributeAsString( "SBI_EXECUTION_ID" ); outputFormat = getAttributeAsString(OUTPUT_FORMAT); logger.debug("Parameter [" + OUTPUT_FORMAT + "] is equal to [" + outputFormat + "]"); inlineResponse = getAttributeAsBoolean(INLINE_RESPONSE, true); logger.debug("Parameter [" + INLINE_RESPONSE + "] is equal to [" + inlineResponse + "]"); if (getAuditServiceProxy() != null) getAuditServiceProxy().notifyServiceStartEvent(); IEngineInstance iEngInst = (IEngineInstance) getAttributeFromSession(EngineConstants.ENGINE_INSTANCE); GeoEngineInstance geoInstance = (GeoEngineInstance) iEngInst; if (outputFormat == null) { logger.info("Parameter [" + outputFormat + "] not specified into request"); //outputFormat = (String)((GeoEngineInstance)).getEnv().get(GeoEngineConstants.ENV_OUTPUT_TYPE); outputFormat = (String) geoInstance.getEnv().get(GeoEngineConstants.ENV_OUTPUT_TYPE); logger.debug("Env Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] is equal to [" + outputFormat + "]"); } if (outputFormat == null) { logger.info( "Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] not specified into environment"); outputFormat = DEFAULT_OUTPUT_TYPE; } totalTimePerFormatMonitor = MonitorFactory .start("GeoEngine.drawMapAction." + outputFormat + "totalTime"); try { if (outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)) { maptmpfile = geoInstance.renderMap(GeoEngineConstants.JPEG); } else { maptmpfile = geoInstance.renderMap(outputFormat); } } catch (Throwable t) { throw new DrawMapServiceException(getActionName(), "Impossible to render map", t); } responseFileName = "map.svg"; IStreamEncoder encoder = null; File tmpFile = null; if (outputFormat.equalsIgnoreCase(GeoEngineConstants.JPEG)) { encoder = new SVGMapConverter(); responseFileName = "map.jpeg"; } else if (outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)) { encoder = new SVGMapConverter(); BufferedInputStream bis = null; String dirS = System.getProperty("java.io.tmpdir"); File imageFile = null; bis = new BufferedInputStream(new FileInputStream(maptmpfile)); try { int contentLength = 0; int b = -1; String contentFileName = "tempJPEGExport"; freezeHttpResponse(); File dir = new File(dirS); imageFile = File.createTempFile("tempJPEGExport", ".jpeg", dir); FileOutputStream stream = new FileOutputStream(imageFile); encoder.encode(bis, stream); stream.flush(); stream.close(); File dirF = new File(dirS); tmpFile = File.createTempFile("tempPDFExport", ".pdf", dirF); Document pdfDocument = new Document(); PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(tmpFile)); pdfDocument.open(); Image jpg = Image.getInstance(imageFile.getPath()); jpg.setRotation(new Double(Math.PI / 2).floatValue()); jpg.scaleAbsolute(770, 520); pdfDocument.add(jpg); pdfDocument.close(); docWriter.close(); maptmpfile = tmpFile; } finally { bis.close(); if (imageFile != null) imageFile.delete(); } responseFileName = "map.pdf"; encoder = null; } try { flushingResponseTotalTimeMonitor = MonitorFactory .start("GeoEngine.drawMapAction.flushResponse.totalTime"); writeBackToClient(maptmpfile, encoder, inlineResponse, responseFileName, getContentType(outputFormat)); } catch (IOException e) { logger.error("error while flushing output", e); if (getAuditServiceProxy() != null) getAuditServiceProxy().notifyServiceErrorEvent("Error while flushing output"); throw new DrawMapServiceException(getActionName(), "Error while flushing output", e); } if (getAuditServiceProxy() != null) getAuditServiceProxy().notifyServiceEndEvent(); maptmpfile.delete(); if (tmpFile != null) tmpFile.delete(); } catch (Throwable t) { errorHitsMonitor = MonitorFactory.start("GeoEngine.errorHits"); errorHitsMonitor.stop(); DrawMapServiceException wrappedException; if (t instanceof DrawMapServiceException) { wrappedException = (DrawMapServiceException) t; } else { wrappedException = new DrawMapServiceException(getActionName(), "An unpredicted error occurred while executing " + getActionName() + " service", t); } wrappedException.setDescription(wrappedException.getRootCause()); Throwable rootException = wrappedException.getRootException(); if (rootException instanceof SpagoBIEngineRuntimeException) { wrappedException.setHints(((SpagoBIEngineRuntimeException) rootException).getHints()); } throw wrappedException; } finally { if (flushingResponseTotalTimeMonitor != null) flushingResponseTotalTimeMonitor.stop(); if (totalTimePerFormatMonitor != null) totalTimePerFormatMonitor.stop(); if (totalTimeMonitor != null) totalTimeMonitor.stop(); } logger.debug("OUT"); logger.debug("OUT"); }
From source file:it.eng.spagobi.engines.worksheet.services.export.ExportChartAction.java
License:Mozilla Public License
private void transformSVGIntoPDF(InputStream inputStream, OutputStream outputStream) throws IOException, DocumentException { FileOutputStream imageFileOutputStream = null; File imageFile = null;/*from ww w.j av a 2 s.c o m*/ try { imageFile = File.createTempFile("chart", ".jpg"); imageFileOutputStream = new FileOutputStream(imageFile); transformSVGIntoPNG(inputStream, imageFileOutputStream); Document pdfDocument = new Document(PageSize.A4.rotate()); PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, outputStream); pdfDocument.open(); Image jpg = Image.getInstance(imageFile.getPath()); fitImage(jpg); pdfDocument.add(jpg); pdfDocument.close(); docWriter.close(); } finally { if (imageFileOutputStream != null) { try { imageFileOutputStream.close(); } catch (IOException e) { logger.error(e); } } if (imageFile.exists()) { imageFile.delete(); } } }
From source file:it.govpay.web.console.pagamenti.gde.exporter.PdfExporter.java
License:Open Source License
public static void exportAsPdf(List<EventoBean> eventi, ByteArrayOutputStream baos, IEventiService eventiService) throws DocumentException, UtilsException { Document document = new Document(); PdfWriter.getInstance(document, baos); document.open();/* w w w . java 2 s. co m*/ addMetaData(document); addTitlePage(document); // Start a new page document.newPage(); addContent(document, eventi, eventiService); document.close(); }
From source file:it.pdfsam.console.tools.pdf.PdfAlternateMix.java
License:Open Source License
/** * Execute the mix command. On error an exception is thrown. * @throws AlternateMixException/*from www. jav a 2s .c o m*/ */ public void execute() throws AlternateMixException { try { workingIndeterminate(); out_message = ""; Document pdf_document = null; PdfCopy pdf_writer = null; File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_file.getParent()); PdfReader pdf_reader1; PdfReader pdf_reader2; pdf_reader1 = new PdfReader(new RandomAccessFileOrArray(input_file1.getAbsolutePath()), null); pdf_reader1.consolidateNamedDestinations(); limits1[1] = pdf_reader1.getNumberOfPages(); pdf_reader2 = new PdfReader(new RandomAccessFileOrArray(input_file2.getAbsolutePath()), null); pdf_reader2.consolidateNamedDestinations(); limits2[1] = pdf_reader2.getNumberOfPages(); pdf_document = new Document(pdf_reader1.getPageSizeWithRotation(1)); pdf_writer = new PdfCopy(pdf_document, new FileOutputStream(tmp_o_file)); if (compressed_boolean) { pdf_writer.setFullCompression(); } out_message += LogFormatter.formatMessage("Temporary file created-\n"); MainConsole.setDocumentCreator(pdf_document); pdf_document.open(); PdfImportedPage page; //importo boolean finished1 = false; boolean finished2 = false; int current1 = (reverseFirst) ? limits1[1] : limits1[0]; int current2 = (reverseSecond) ? limits2[1] : limits2[0]; while (!finished1 || !finished2) { if (!finished1) { if (current1 >= limits1[0] && current1 <= limits1[1]) { page = pdf_writer.getImportedPage(pdf_reader1, current1); pdf_writer.addPage(page); current1 = (reverseFirst) ? (current1 - 1) : (current1 + 1); } else { out_message += LogFormatter.formatMessage("First file processed-\n"); finished1 = true; } } if (!finished2) { if (current2 >= limits2[0] && current2 <= limits2[1] && !finished2) { page = pdf_writer.getImportedPage(pdf_reader2, current2); pdf_writer.addPage(page); current2 = (reverseSecond) ? (current2 - 1) : (current2 + 1); } else { out_message += LogFormatter.formatMessage("Second file processed-\n"); finished2 = true; } } } pdf_reader1.close(); pdf_writer.freeReader(pdf_reader1); pdf_reader2.close(); pdf_writer.freeReader(pdf_reader2); pdf_document.close(); // step 6: temporary buffer moved to output file renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean); out_message += LogFormatter.formatMessage("Alternate mix completed-\n"); } catch (Exception e) { throw new AlternateMixException(e); } finally { workCompleted(); } }
From source file:it.pdfsam.console.tools.pdf.PdfConcat.java
License:Open Source License
/** * Execute the concat command. On error an exception is thrown. * @throws ConcatException/* www. jav a2s . c o m*/ */ public void execute() throws ConcatException { try { percentageChanged(0, 0); out_message = ""; String file_name; int pageOffset = 0; ArrayList master = new ArrayList(); int f = 0; Document pdf_document = null; PdfConcatenator pdf_writer = null; int total_processed_pages = 0; String[] page_selection = u_string.split(":"); File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_file.getParent()); PdfReader pdf_reader; for (Iterator f_list_itr = f_list.iterator(); f_list_itr.hasNext();) { String current_p_selection; //get page selection. If arrayoutofbounds default behaviour is "all" try { current_p_selection = page_selection[f].toLowerCase(); if (current_p_selection.equals("")) current_p_selection = "all"; } catch (Exception e) { current_p_selection = "all"; } //validation if (!(Pattern.compile("([0-9]+[-][0-9]+)|(all)", Pattern.CASE_INSENSITIVE) .matcher(current_p_selection).matches())) { String errorMsg = ""; try { tmp_o_file.delete(); } catch (Exception e) { errorMsg = " Unable to delete temporary file."; } throw new ConcatException( "ValidationError: Syntax error on " + current_p_selection + "." + errorMsg); } file_name = f_list_itr.next().toString(); //reader creation pdf_reader = new PdfReader(new RandomAccessFileOrArray(file_name), null); pdf_reader.consolidateNamedDestinations(); int pdf_number_of_pages = pdf_reader.getNumberOfPages(); //default behaviour int start = 0; int end_page = pdf_number_of_pages; if (!(current_p_selection.equals("all"))) { boolean valid = true; String exceptionMsg = ""; String[] limits = current_p_selection.split("-"); try { start = Integer.parseInt(limits[0]); end_page = Integer.parseInt(limits[1]); } catch (Exception ex) { valid = false; exceptionMsg += "ValidationError: Syntax error on " + current_p_selection + "."; try { tmp_o_file.delete(); } catch (Exception e) { exceptionMsg += " Unable to delete temporary file."; } } if (valid) { //validation if (start < 0) { valid = false; exceptionMsg = "ValidationError: Syntax error. " + (start) + " must be positive in " + current_p_selection + "."; try { tmp_o_file.delete(); } catch (Exception e) { exceptionMsg += " Unable to delete temporary file."; } } else if (end_page > pdf_number_of_pages) { valid = false; exceptionMsg = "ValidationError: Cannot merge at page " + end_page + ". No such page."; try { tmp_o_file.delete(); } catch (Exception e) { exceptionMsg += " Unable to delete temporary file."; } } else if (start > end_page) { valid = false; exceptionMsg = "ValidationError: Syntax error. " + (start) + " is bigger than " + end_page + " in " + current_p_selection + "."; try { tmp_o_file.delete(); } catch (Exception e) { exceptionMsg += " Unable to delete temporary file."; } } } if (!valid) { throw new ConcatException(exceptionMsg); } } List bookmarks = SimpleBookmark.getBookmark(pdf_reader); if (bookmarks != null) { //if the end page is not the end of the doc, delete bookmarks after it if (end_page < pdf_number_of_pages) { SimpleBookmark.eliminatePages(bookmarks, new int[] { end_page + 1, pdf_number_of_pages }); } // if start page isn't the first page of the document, delete bookmarks before it if (start > 0) { SimpleBookmark.eliminatePages(bookmarks, new int[] { 1, start }); //bookmarks references must be taken back SimpleBookmark.shiftPageNumbers(bookmarks, -start, null); } if (pageOffset != 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); } master.addAll(bookmarks); } pageOffset += (end_page - start); out_message += LogFormatter.formatMessage(file_name + ": " + end_page + " pages-\n"); if (f == 0) { if (copyfields_boolean) { // step 1: we create a writer pdf_writer = new PdfCopyFieldsConcatenator(new FileOutputStream(tmp_o_file), compressed_boolean); HashMap meta = pdf_reader.getInfo(); meta.put("Creator", MainConsole.CREATOR); } else { // step 1: creation of a document-object pdf_document = new Document(pdf_reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document pdf_writer = new PdfSimpleConcatenator(pdf_document, new FileOutputStream(tmp_o_file), compressed_boolean); // step 3: we open the document MainConsole.setDocumentCreator(pdf_document); pdf_document.open(); } out_message += LogFormatter.formatMessage("Temporary file created-\n"); } // step 4: we add content pdf_reader.selectPages(start + "-" + end_page); pdf_writer.addDocument(pdf_reader); //fix 03/07 //pdf_reader = null; pdf_reader.close(); pdf_writer.freeReader(pdf_reader); total_processed_pages += end_page - start + 1; out_message += LogFormatter.formatMessage((end_page - start) + " pages processed correctly-\n"); f++; try { percentageChanged((f * 100) / f_list.size(), (end_page - start)); } catch (RuntimeException re) { out_message += LogFormatter.formatMessage("RuntimeException: " + re.getMessage() + "\n"); } } if (master.size() > 0) { pdf_writer.setOutlines(master); } out_message += LogFormatter.formatMessage("Total processed pages: " + total_processed_pages + "-\n"); // step 5: we close the document if (pdf_document != null) { pdf_document.close(); } pdf_writer.close(); // step 6: temporary buffer moved to output file renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean); } catch (Exception e) { throw new ConcatException(e); } finally { workCompleted(); } }