List of usage examples for java.io ByteArrayOutputStream writeTo
public synchronized void writeTo(OutputStream out) throws IOException
From source file:org.vasanti.controller.DropZoneFileUpload.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) { File file = new File(ImagefileUploadPath, request.getParameter("getfile")); if (file.exists()) { int bytes = 0; ServletOutputStream op = response.getOutputStream(); response.setContentType(getMimeType(file)); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); byte[] bbuf = new byte[1024]; DataInputStream in = new DataInputStream(new FileInputStream(file)); while ((in != null) && ((bytes = in.read(bbuf)) != -1)) { op.write(bbuf, 0, bytes); }// w w w.j a v a 2 s . c o m in.close(); op.flush(); op.close(); } } // else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) { // File file = new File(request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("delfile")); // if (file.exists()) { // file.delete(); // TODO:check and report success // } // } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) { File file = new File(ImagefileUploadPath, request.getParameter("getthumb")); if (file.exists()) { String mimetype = getMimeType(file); if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg") || mimetype.endsWith("gif")) { BufferedImage im = ImageIO.read(file); if (im != null) { BufferedImage thumb = Scalr.resize(im, 75); ByteArrayOutputStream os = new ByteArrayOutputStream(); if (mimetype.endsWith("png")) { ImageIO.write(thumb, "PNG", os); response.setContentType("image/png"); } else if (mimetype.endsWith("jpeg")) { ImageIO.write(thumb, "jpg", os); response.setContentType("image/jpeg"); } else if (mimetype.endsWith("jpg")) { ImageIO.write(thumb, "jpg", os); response.setContentType("image/jpeg"); } else { ImageIO.write(thumb, "GIF", os); response.setContentType("image/gif"); } ServletOutputStream srvos = response.getOutputStream(); response.setContentLength(os.size()); response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); os.writeTo(srvos); srvos.flush(); srvos.close(); } } } // TODO: check and report success } else { PrintWriter writer = response.getWriter(); writer.write("call POST with multipart form data"); } }
From source file:com.google.code.configprocessor.ConfigProcessor.java
/** * Processes a file.//www . j a v a 2 s. c o m * * @param resolver * @param inputName Symbolic name of the input file to read from. * @param input Input file to read from. * @param output Output file to write to. * @param configName Symbolic name of the file containing rules to process the input. * @param action Action to be performed on the input file. * @param type Type of the input file. Properties, XML or null if it is to be auto-detected. * @throws ConfigProcessorException If processing cannot be performed. */ protected void process(ExpressionResolver resolver, String inputName, File input, File output, String configName, Action action, String type) throws ConfigProcessorException { getLog().info("Processing file [" + inputName + "] using config [" + configName + "], outputing to [" + output + "]"); InputStream inputStream = null; ByteArrayOutputStream outputStream = null; InputStreamReader inputStreamReader = null; OutputStreamWriter outputStreamWriter = null; try { inputStream = new FileInputStream(input); outputStream = new ByteArrayOutputStream(); inputStreamReader = new InputStreamReader(inputStream, encoding); outputStreamWriter = new OutputStreamWriter(outputStream, encoding); ActionProcessor processor = getActionProcessor(resolver, type); processor.process(inputStreamReader, outputStreamWriter, action); } catch (ParsingException e) { throw new ConfigProcessorException( "Error processing file [" + inputName + "] using configuration [" + configName + "]", e); } catch (IOException e) { throw new ConfigProcessorException("Error reading/writing files. Input is [" + inputName + "], configuration is [" + configName + "]", e); } finally { close(inputStreamReader, getLog()); } FileOutputStream fileOut = null; try { fileOut = new FileOutputStream(output); outputStream.writeTo(fileOut); } catch (FileNotFoundException e) { getLog().error("Error opening file [" + output + "]", e); } catch (IOException e) { getLog().error("Error writing file [" + output + "]", e); } finally { close(outputStreamWriter, getLog()); close(fileOut, getLog()); } }
From source file:org.apache.hadoop.hbase.io.encoding.EncodedDataBlock.java
/** * Do the encoding, but do not cache the encoded data. * @return encoded data block with header and checksum *//*from w w w . j ava 2 s. com*/ public byte[] encodeData() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { baos.write(HConstants.HFILEBLOCK_DUMMY_HEADER); DataOutputStream out = new DataOutputStream(baos); this.dataBlockEncoder.startBlockEncoding(encodingCtx, out); ByteBuffer in = getUncompressedBuffer(); in.rewind(); int klength, vlength; short tagsLength = 0; long memstoreTS = 0L; KeyValue kv = null; while (in.hasRemaining()) { int kvOffset = in.position(); klength = in.getInt(); vlength = in.getInt(); ByteBufferUtils.skip(in, klength + vlength); if (this.meta.isIncludesTags()) { tagsLength = in.getShort(); ByteBufferUtils.skip(in, tagsLength); } if (this.meta.isIncludesMvcc()) { memstoreTS = ByteBufferUtils.readVLong(in); } kv = new KeyValue(in.array(), kvOffset, (int) KeyValue.getKeyValueDataStructureSize(klength, vlength, tagsLength)); kv.setMvccVersion(memstoreTS); this.dataBlockEncoder.encode(kv, encodingCtx, out); } BufferGrabbingByteArrayOutputStream stream = new BufferGrabbingByteArrayOutputStream(); baos.writeTo(stream); this.dataBlockEncoder.endBlockEncoding(encodingCtx, out, stream.buf); } catch (IOException e) { throw new RuntimeException(String.format("Bug in encoding part of algorithm %s. " + "Probably it requested more bytes than are available.", toString()), e); } return baos.toByteArray(); }
From source file:org.sakaiproject.site.tool.SiteInfoToolServlet.java
/** * generate PDF file containing all site participant * @param data/*ww w . ja v a2 s . co m*/ */ public void print_participant(String siteId) { HttpServletResponse res = (HttpServletResponse) ThreadLocalManager.get(RequestFilter.CURRENT_HTTP_RESPONSE); ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); res.addHeader("Content-Disposition", "inline; filename=\"participants.pdf\""); res.setContentType("application/pdf"); Document document = docBuilder.newDocument(); // get the participant xml document generateParticipantXMLDocument(document, siteId); generatePDF(document, outByteStream); res.setContentLength(outByteStream.size()); if (outByteStream.size() > 0) { // Increase the buffer size for more speed. res.setBufferSize(outByteStream.size()); } /* // output xml for debugging purpose try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (Exception e) { }*/ OutputStream out = null; try { out = res.getOutputStream(); if (outByteStream.size() > 0) { outByteStream.writeTo(out); } res.setHeader("Refresh", "0"); out.flush(); out.close(); } catch (Throwable ignore) { } finally { if (out != null) { try { out.close(); } catch (Throwable ignore) { } } } }
From source file:org.kuali.ole.module.purap.document.web.struts.PrintAction.java
@Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //get parameters String poDocNumber = request.getParameter("poDocNumber"); Integer vendorQuoteId = new Integer(request.getParameter("vendorQuoteId")); if (StringUtils.isEmpty(poDocNumber) || StringUtils.isEmpty(poDocNumber)) { throw new RuntimeException(); }/*from ww w. jav a2 s . c o m*/ // doc service - get this doc PurchaseOrderDocument po = (PurchaseOrderDocument) SpringContext.getBean(DocumentService.class) .getByDocumentHeaderId(poDocNumber); DocumentAuthorizer documentAuthorizer = SpringContext.getBean(DocumentHelperService.class) .getDocumentAuthorizer(po); if (!documentAuthorizer.canInitiate(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER, GlobalVariables.getUserSession().getPerson())) { throw new DocumentInitiationException(OLEKeyConstants.AUTHORIZATION_ERROR_DOCUMENT, new String[] { GlobalVariables.getUserSession().getPerson().getPrincipalName(), "print", "Purchase Order" }); } // get the vendor quote PurchaseOrderVendorQuote poVendorQuote = null; for (PurchaseOrderVendorQuote vendorQuote : po.getPurchaseOrderVendorQuotes()) { if (vendorQuote.getPurchaseOrderVendorQuoteIdentifier().equals(vendorQuoteId)) { poVendorQuote = vendorQuote; break; } } if (poVendorQuote == null) { throw new RuntimeException(); } ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); poVendorQuote.setTransmitPrintDisplayed(false); try { StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_PO_QUOTE_"); sbFilename.append(po.getPurapDocumentIdentifier()); sbFilename.append("_"); sbFilename.append(System.currentTimeMillis()); sbFilename.append(".pdf"); // call the print service boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po, poVendorQuote, baosPDF); if (!success) { poVendorQuote.setTransmitPrintDisplayed(true); if (baosPDF != null) { baosPDF.reset(); } return mapping.findForward(OLEConstants.MAPPING_BASIC); } response.setHeader("Cache-Control", "max-age=30"); response.setContentType("application/pdf"); StringBuffer sbContentDispValue = new StringBuffer(); // sbContentDispValue.append("inline"); sbContentDispValue.append("attachment"); sbContentDispValue.append("; filename="); sbContentDispValue.append(sbFilename); response.setHeader("Content-disposition", sbContentDispValue.toString()); response.setContentLength(baosPDF.size()); ServletOutputStream sos; sos = response.getOutputStream(); baosPDF.writeTo(sos); sos.flush(); } finally { if (baosPDF != null) { baosPDF.reset(); } } return null; }
From source file:org.kuali.kfs.module.purap.document.web.struts.PrintAction.java
@Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //get parameters String poDocNumber = request.getParameter("poDocNumber"); Integer vendorQuoteId = new Integer(request.getParameter("vendorQuoteId")); if (StringUtils.isEmpty(poDocNumber) || StringUtils.isEmpty(poDocNumber)) { throw new RuntimeException(); }/*from www . j ava 2 s .c o m*/ // doc service - get this doc PurchaseOrderDocument po = (PurchaseOrderDocument) SpringContext.getBean(DocumentService.class) .getByDocumentHeaderId(poDocNumber); DocumentAuthorizer documentAuthorizer = SpringContext.getBean(DocumentHelperService.class) .getDocumentAuthorizer(po); if (!(documentAuthorizer.canInitiate(KFSConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER, GlobalVariables.getUserSession().getPerson()) || documentAuthorizer.canInitiate( KFSConstants.FinancialDocumentTypeCodes.CONTRACT_MANAGER_ASSIGNMENT, GlobalVariables.getUserSession().getPerson()))) { throw new DocumentInitiationException(KFSKeyConstants.AUTHORIZATION_ERROR_DOCUMENT, new String[] { GlobalVariables.getUserSession().getPerson().getPrincipalName(), "print", "Purchase Order" }); } // get the vendor quote PurchaseOrderVendorQuote poVendorQuote = null; for (PurchaseOrderVendorQuote vendorQuote : po.getPurchaseOrderVendorQuotes()) { if (vendorQuote.getPurchaseOrderVendorQuoteIdentifier().equals(vendorQuoteId)) { poVendorQuote = vendorQuote; break; } } if (poVendorQuote == null) { throw new RuntimeException(); } ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); poVendorQuote.setTransmitPrintDisplayed(false); try { StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_PO_QUOTE_"); sbFilename.append(po.getPurapDocumentIdentifier()); sbFilename.append("_"); sbFilename.append(System.currentTimeMillis()); sbFilename.append(".pdf"); // call the print service boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po, poVendorQuote, baosPDF); if (!success) { poVendorQuote.setTransmitPrintDisplayed(true); if (baosPDF != null) { baosPDF.reset(); } return mapping.findForward(KFSConstants.MAPPING_BASIC); } response.setHeader("Cache-Control", "max-age=30"); response.setContentType("application/pdf"); StringBuffer sbContentDispValue = new StringBuffer(); // sbContentDispValue.append("inline"); sbContentDispValue.append("attachment"); sbContentDispValue.append("; filename="); sbContentDispValue.append(sbFilename); response.setHeader("Content-disposition", sbContentDispValue.toString()); response.setContentLength(baosPDF.size()); ServletOutputStream sos; sos = response.getOutputStream(); baosPDF.writeTo(sos); sos.flush(); } finally { if (baosPDF != null) { baosPDF.reset(); } } return null; }
From source file:org.kuali.kfs.module.purap.document.web.struts.BulkReceivingAction.java
public ActionForward printReceivingTicket(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String blkDocId = request.getParameter("docId"); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try {/* w w w . ja v a2s .co m*/ // will throw validation exception if errors occur SpringContext.getBean(BulkReceivingService.class).performPrintReceivingTicketPDF(blkDocId, baosPDF); response.setHeader("Cache-Control", "max-age=30"); response.setContentType("application/pdf"); StringBuffer sbContentDispValue = new StringBuffer(); String useJavascript = request.getParameter("useJavascript"); if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) { sbContentDispValue.append("attachment"); } else { sbContentDispValue.append("inline"); } StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_RECEIVING_TICKET_"); sbFilename.append(blkDocId); sbFilename.append("_"); sbFilename.append(System.currentTimeMillis()); sbFilename.append(".pdf"); sbContentDispValue.append("; filename="); sbContentDispValue.append(sbFilename); response.setHeader("Content-disposition", sbContentDispValue.toString()); response.setContentLength(baosPDF.size()); ServletOutputStream sos = response.getOutputStream(); baosPDF.writeTo(sos); sos.flush(); } finally { if (baosPDF != null) { baosPDF.reset(); } } return null; }
From source file:com.eucalyptus.blockstorage.S3SnapshotTransfer.java
/** * Compresses the snapshot and uploads it to a bucket in objectstorage gateway as a single or multipart upload based on the configuration in * {@link StorageInfo}. Bucket name should be configured before invoking this method. It can be looked up and initialized by {@link #prepareForUpload()} or * explicitly set using {@link #setBucketName(String)} * //from w ww . j a va 2 s . co m * @param sourceFileName * absolute path to the snapshot on the file system */ @Override public void upload(String sourceFileName) throws SnapshotTransferException { validateInput(); // Validate input loadTransferConfig(); // Load the transfer configuration parameters from database SnapshotProgressCallback progressCallback = new SnapshotProgressCallback(snapshotId); // Setup the progress callback Boolean error = Boolean.FALSE; ArrayBlockingQueue<SnapshotPart> partQueue = null; SnapshotPart part = null; SnapshotUploadInfo snapUploadInfo = null; Future<List<PartETag>> uploadPartsFuture = null; Future<String> completeUploadFuture = null; byte[] buffer = new byte[READ_BUFFER_SIZE]; Long readOffset = 0L; Long bytesRead = 0L; Long bytesWritten = 0L; int len; int partNumber = 1; try { // Get the uncompressed file size for uploading as metadata Long uncompressedSize = getFileSize(sourceFileName); // Setup the snapshot and part entities. snapUploadInfo = SnapshotUploadInfo.create(snapshotId, bucketName, keyName); Path zipFilePath = Files.createTempFile(keyName + '-', '-' + String.valueOf(partNumber)); part = SnapshotPart.createPart(snapUploadInfo, zipFilePath.toString(), partNumber, readOffset); FileInputStream inputStream = new FileInputStream(sourceFileName); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzipStream = new GZIPOutputStream(baos); FileOutputStream outputStream = new FileOutputStream(zipFilePath.toString()); try { LOG.debug("Reading snapshot " + snapshotId + " and compressing it to disk in chunks of size " + partSize + " bytes or greater"); while ((len = inputStream.read(buffer)) > 0) { bytesRead += len; gzipStream.write(buffer, 0, len); if ((bytesWritten + baos.size()) < partSize) { baos.writeTo(outputStream); bytesWritten += baos.size(); baos.reset(); } else { gzipStream.close(); baos.writeTo(outputStream); // Order is important. Closing the gzip stream flushes stuff bytesWritten += baos.size(); baos.reset(); outputStream.close(); if (partNumber > 1) {// Update the part status part = part.updateStateCreated(bytesWritten, bytesRead, Boolean.FALSE); } else {// Initialize multipart upload only once after the first part is created LOG.info("Uploading snapshot " + snapshotId + " to objectstorage using multipart upload"); progressCallback.setUploadSize(uncompressedSize); uploadId = initiateMulitpartUpload(uncompressedSize); snapUploadInfo = snapUploadInfo.updateUploadId(uploadId); part = part.updateStateCreated(uploadId, bytesWritten, bytesRead, Boolean.FALSE); partQueue = new ArrayBlockingQueue<SnapshotPart>(queueSize); uploadPartsFuture = Threads.enqueue(serviceConfig, UploadPartTask.class, poolSize, new UploadPartTask(partQueue, progressCallback)); } // Check for the future task before adding part to the queue. if (uploadPartsFuture != null && uploadPartsFuture.isDone()) { // This task shouldn't be done until the last part is added. If it is done at this point, then something might have gone wrong throw new SnapshotUploadPartException( "Error uploading parts, aborting part creation process. Check previous log messages for the exact error"); } // Add part to the queue partQueue.put(part); // Prep the metadata for the next part readOffset += bytesRead; bytesRead = 0L; bytesWritten = 0L; // Setup the part entity for next part zipFilePath = Files.createTempFile(keyName + '-', '-' + String.valueOf((++partNumber))); part = SnapshotPart.createPart(snapUploadInfo, zipFilePath.toString(), partNumber, readOffset); gzipStream = new GZIPOutputStream(baos); outputStream = new FileOutputStream(zipFilePath.toString()); } } gzipStream.close(); baos.writeTo(outputStream); bytesWritten += baos.size(); baos.reset(); outputStream.close(); inputStream.close(); // Update the part status part = part.updateStateCreated(bytesWritten, bytesRead, Boolean.TRUE); // Update the snapshot upload info status snapUploadInfo = snapUploadInfo.updateStateCreatedParts(partNumber); } catch (Exception e) { LOG.error("Failed to upload " + snapshotId + " due to: ", e); error = Boolean.TRUE; throw new SnapshotTransferException("Failed to upload " + snapshotId + " due to: ", e); } finally { if (inputStream != null) { inputStream.close(); } if (gzipStream != null) { gzipStream.close(); } if (outputStream != null) { outputStream.close(); } baos.reset(); } if (partNumber > 1) { // Check for the future task before adding the last part to the queue. if (uploadPartsFuture != null && uploadPartsFuture.isDone()) { // This task shouldn't be done until the last part is added. If it is done at this point, then something might have gone wrong throw new SnapshotUploadPartException( "Error uploading parts, aborting part upload process. Check previous log messages for the exact error"); } // Add the last part to the queue partQueue.put(part); // Kick off the completion task completeUploadFuture = Threads.enqueue(serviceConfig, CompleteMpuTask.class, poolSize, new CompleteMpuTask(uploadPartsFuture, snapUploadInfo, partNumber)); } else { try { LOG.info("Uploading snapshot " + snapshotId + " to objectstorage as a single object. Compressed size of snapshot (" + bytesWritten + " bytes) is less than minimum part size (" + partSize + " bytes) for multipart upload"); PutObjectResult putResult = uploadSnapshotAsSingleObject(zipFilePath.toString(), bytesWritten, uncompressedSize, progressCallback); markSnapshotAvailable(); try { part = part.updateStateUploaded(putResult.getETag()); snapUploadInfo = snapUploadInfo.updateStateUploaded(putResult.getETag()); } catch (Exception e) { LOG.debug("Failed to update status in DB for " + snapUploadInfo); } LOG.info("Uploaded snapshot " + snapshotId + " to objectstorage"); } catch (Exception e) { error = Boolean.TRUE; LOG.error("Failed to upload snapshot " + snapshotId + " due to: ", e); throw new SnapshotTransferException("Failed to upload snapshot " + snapshotId + " due to: ", e); } finally { deleteFile(zipFilePath); } } } catch (SnapshotTransferException e) { error = Boolean.TRUE; throw e; } catch (Exception e) { error = Boolean.TRUE; LOG.error("Failed to upload snapshot " + snapshotId + " due to: ", e); throw new SnapshotTransferException("Failed to upload snapshot " + snapshotId + " due to: ", e); } finally { if (error) { abortUpload(snapUploadInfo); if (uploadPartsFuture != null && !uploadPartsFuture.isDone()) { uploadPartsFuture.cancel(true); } if (completeUploadFuture != null && !completeUploadFuture.isDone()) { completeUploadFuture.cancel(true); } } } }
From source file:com.mirth.connect.connectors.doc.DocumentDispatcher.java
private String writeDocument(String template, DocumentDispatcherProperties documentDispatcherProperties, ConnectorMessage connectorMessage) throws Exception { // add tags to the template to create a valid HTML document StringBuilder contents = new StringBuilder(); if (template.lastIndexOf("<html") < 0) { contents.append("<html>"); if (template.lastIndexOf("<body") < 0) { contents.append("<body>"); contents.append(template);//from www .jav a2 s . c om contents.append("</body>"); } else { contents.append(template); } contents.append("</html>"); } else { contents.append(template); } String stringContents = getAttachmentHandlerProvider().reAttachMessage(contents.toString(), connectorMessage); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (documentDispatcherProperties.getDocumentType().toLowerCase().equals("pdf")) { createPDF(new StringReader(stringContents), outputStream, documentDispatcherProperties); boolean encrypt = documentDispatcherProperties.isEncrypt(); String password = documentDispatcherProperties.getPassword(); if (encrypt && password != null) { ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); outputStream = new ByteArrayOutputStream(); encryptPDF(inputStream, outputStream, password); } } else if (documentDispatcherProperties.getDocumentType().toLowerCase().equals("rtf")) { createRTF(new ByteArrayInputStream(stringContents.getBytes()), outputStream, documentDispatcherProperties); } if (StringUtils.isBlank(documentDispatcherProperties.getOutput()) || !documentDispatcherProperties.getOutput().equalsIgnoreCase("attachment")) { FileOutputStream fileOutputStream = null; try { File file = createFile(documentDispatcherProperties.getHost() + "/" + documentDispatcherProperties.getOutputPattern()); logger.info("Writing document to: " + file.getAbsolutePath()); fileOutputStream = new FileOutputStream(file); outputStream.writeTo(fileOutputStream); } catch (Exception e) { throw e; } finally { IOUtils.closeQuietly(fileOutputStream); } } if (StringUtils.isNotBlank(documentDispatcherProperties.getOutput()) && !documentDispatcherProperties.getOutput().equalsIgnoreCase("file")) { Attachment attachment = MessageController.getInstance().createAttachment( new String(Base64Util.encodeBase64(outputStream.toByteArray(), false), "US-ASCII"), documentDispatcherProperties.getDocumentType().contains("pdf") ? "application/pdf" : "application/rtf"); MessageController.getInstance().insertAttachment(attachment, connectorMessage.getChannelId(), connectorMessage.getMessageId()); return attachment.getAttachmentId(); } return null; }
From source file:org.webguitoolkit.ui.util.export.PDFTableExport.java
public void writeTo(Table table, OutputStream out) { TableExportOptions exportOptions = table.getExportOptions(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // set the page orientation Din-A4 Portrait or Landscape Rectangle page = PageSize.A4; if (exportOptions.getPdfPosition() != null && exportOptions.getPdfPosition().equals(TableExportOptions.PDF_LANDSCAPE)) { // landscape position page = PageSize.A4.rotate();//www. j a va 2 s . co m } else if (exportOptions.getPdfPosition() != null && exportOptions.getPdfPosition().equals(TableExportOptions.PDF_PORTRAIT)) { // portrait position page = PageSize.A4; } if (exportOptions.getPdfPageColour() != null) { // page.setBackgroundColor(exportOptions.getPdfPageColour()); } Document document = new Document(page); document.setMargins(36f, 36f, 50f, 40f); try { PdfWriter writer = PdfWriter.getInstance(document, baos); writer.setPageEvent(new PDFEvent(table)); document.open(); if (StringUtils.isNotEmpty(exportOptions.getHeadline())) { Font titleFont = new Font(Font.UNDEFINED, 18, Font.BOLD); Paragraph paragraph = new Paragraph(exportOptions.getHeadline(), titleFont); paragraph.setAlignment(Element.ALIGN_CENTER); document.add(paragraph); document.add(new Paragraph(" ")); document.add(new Paragraph(" ")); } PdfPTable pdftable = pdfExport(table); document.add(pdftable); document.newPage(); document.close(); baos.writeTo(out); out.flush(); baos.close(); } catch (DocumentException e) { logger.error("Error creating document!", e); throw new RuntimeException(e); } catch (IOException e) { logger.error("Error creating document!", e); throw new RuntimeException(e); } finally { } }