List of usage examples for com.lowagie.text Image setAbsolutePosition
public void setAbsolutePosition(float absoluteX, float absoluteY)
Image
. From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java
License:Open Source License
private void handleGroup(PipelineContext pipelineContext, GroupContext groupContext, List<Element> statements, FunctionLibrary functionLibrary, PdfReader reader) throws DocumentException, IOException { final NodeInfo contextNode = (NodeInfo) groupContext.contextNodeSet.get(groupContext.contextPosition - 1); final Map<String, ValueRepresentation> variableToValueMap = new HashMap<String, ValueRepresentation>(); variableToValueMap.put("page-count", new Int64Value(reader.getNumberOfPages())); variableToValueMap.put("page-number", new Int64Value(groupContext.pageNumber)); variableToValueMap.put("page-height", new FloatValue(groupContext.pageHeight)); // Iterate through statements for (final Element currentElement : statements) { // Check whether this statement applies to the current page final String elementPage = currentElement.attributeValue("page"); if ((elementPage != null) && !Integer.toString(groupContext.pageNumber).equals(elementPage)) continue; final NamespaceMapping namespaceMapping = new NamespaceMapping( Dom4jUtils.getNamespaceContextNoDefault(currentElement)); final String elementName = currentElement.getName(); if (elementName.equals("group")) { // Handle group final GroupContext newGroupContext = new GroupContext(groupContext); final String ref = currentElement.attributeValue("ref"); if (ref != null) { final NodeInfo newContextNode = (NodeInfo) XPathCache.evaluateSingle( groupContext.contextNodeSet, groupContext.contextPosition, ref, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); if (newContextNode == null) continue; newGroupContext.contextNodeSet = Collections.singletonList((Item) newContextNode); newGroupContext.contextPosition = 1; }/*from ww w. jav a 2 s . c o m*/ final String offsetXString = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-x")); if (offsetXString != null) { newGroupContext.offsetX = groupContext.offsetX + Float.parseFloat(offsetXString); } final String offsetYString = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-y")); if (offsetYString != null) { newGroupContext.offsetY = groupContext.offsetY + Float.parseFloat(offsetYString); } final String fontPitch = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("font-pitch")); if (fontPitch != null) newGroupContext.fontPitch = Float.parseFloat(fontPitch); final String fontFamily = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("font-family")); if (fontFamily != null) newGroupContext.fontFamily = fontFamily; final String fontSize = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("font-size")); if (fontSize != null) newGroupContext.fontSize = Float.parseFloat(fontSize); handleGroup(pipelineContext, newGroupContext, Dom4jUtils.elements(currentElement), functionLibrary, reader); } else if (elementName.equals("repeat")) { // Handle repeat final String nodeset = currentElement.attributeValue("nodeset"); final List iterations = XPathCache.evaluate(groupContext.contextNodeSet, groupContext.contextPosition, nodeset, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); final String offsetXString = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-x")); final String offsetYString = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-y")); final float offsetIncrementX = (offsetXString == null) ? 0 : Float.parseFloat(offsetXString); final float offsetIncrementY = (offsetYString == null) ? 0 : Float.parseFloat(offsetYString); for (int iterationIndex = 1; iterationIndex <= iterations.size(); iterationIndex++) { final GroupContext newGroupContext = new GroupContext(groupContext); newGroupContext.contextNodeSet = iterations; newGroupContext.contextPosition = iterationIndex; newGroupContext.offsetX = groupContext.offsetX + (iterationIndex - 1) * offsetIncrementX; newGroupContext.offsetY = groupContext.offsetY + (iterationIndex - 1) * offsetIncrementY; handleGroup(pipelineContext, newGroupContext, Dom4jUtils.elements(currentElement), functionLibrary, reader); } } else if (elementName.equals("field")) { final String fieldNameStr = currentElement.attributeValue("acro-field-name"); if (fieldNameStr != null) { final String value = currentElement.attributeValue("value") == null ? currentElement.attributeValue("ref") : currentElement.attributeValue("value"); // Get value from instance final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, value, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); final String fieldName = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, fieldNameStr, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); groupContext.acroFields.setField(fieldName, text); } else { // Handle field final String leftAttribute = currentElement.attributeValue("left") == null ? currentElement.attributeValue("left-position") : currentElement.attributeValue("left"); final String topAttribute = currentElement.attributeValue("top") == null ? currentElement.attributeValue("top-position") : currentElement.attributeValue("top"); final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, leftAttribute); final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, topAttribute); final String size = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("size")); final String value = currentElement.attributeValue("value") == null ? currentElement.attributeValue("ref") : currentElement.attributeValue("value"); final FontAttributes fontAttributes = getFontAttributes(currentElement, pipelineContext, groupContext, variableToValueMap, contextNode); // Output value final BaseFont baseFont = BaseFont.createFont(fontAttributes.fontFamily, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); groupContext.contentByte.beginText(); { groupContext.contentByte.setFontAndSize(baseFont, fontAttributes.fontSize); final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX; final float yPosition = groupContext.pageHeight - (Float.parseFloat(topPosition) + groupContext.offsetY); // Get value from instance final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, value, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); // Iterate over characters and print them if (text != null) { int len = Math.min(text.length(), (size != null) ? Integer.parseInt(size) : Integer.MAX_VALUE); for (int j = 0; j < len; j++) groupContext.contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, text.substring(j, j + 1), xPosition + ((float) j) * fontAttributes.fontPitch, yPosition, 0); } } groupContext.contentByte.endText(); } } else if (elementName.equals("barcode")) { // Handle barcode final String leftAttribute = currentElement.attributeValue("left"); final String topAttribute = currentElement.attributeValue("top"); final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, leftAttribute); final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, topAttribute); // final String size = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("size")); final String value = currentElement.attributeValue("value") == null ? currentElement.attributeValue("ref") : currentElement.attributeValue("value"); final String type = currentElement.attributeValue("type") == null ? "CODE39" : currentElement.attributeValue("type"); final float height = currentElement.attributeValue("height") == null ? 10.0f : Float.parseFloat(currentElement.attributeValue("height")); final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX; final float yPosition = groupContext.pageHeight - (Float.parseFloat(topPosition) + groupContext.offsetY); final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, value, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); final FontAttributes fontAttributes = getFontAttributes(currentElement, pipelineContext, groupContext, variableToValueMap, contextNode); final BaseFont baseFont = BaseFont.createFont(fontAttributes.fontFamily, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); final Barcode barcode = createBarCode(type); barcode.setCode(text); barcode.setBarHeight(height); barcode.setFont(baseFont); barcode.setSize(fontAttributes.fontSize); final Image barcodeImage = barcode.createImageWithBarcode(groupContext.contentByte, null, null); barcodeImage.setAbsolutePosition(xPosition, yPosition); groupContext.contentByte.addImage(barcodeImage); } else if (elementName.equals("image")) { // Handle image // Read image final Image image; { final String hrefAttribute = currentElement.attributeValue("href"); final String inputName = ProcessorImpl.getProcessorInputSchemeInputName(hrefAttribute); if (inputName != null) { // Read the input final ByteArrayOutputStream os = new ByteArrayOutputStream(); readInputAsSAX(pipelineContext, inputName, new BinaryTextXMLReceiver(null, os, true, false, null, false, false, null, false)); // Create the image image = Image.getInstance(os.toByteArray()); } else { // Read and create the image final URL url = URLFactory.createURL(hrefAttribute); // Use ConnectionResult so that header/session forwarding takes place final ConnectionResult connectionResult = new Connection().open( NetUtils.getExternalContext(), new IndentedLogger(logger, ""), false, Connection.Method.GET.name(), url, null, null, null, null, Connection.getForwardHeaders()); if (connectionResult.statusCode != 200) { connectionResult.close(); throw new OXFException("Got invalid return code while loading image: " + url.toExternalForm() + ", " + connectionResult.statusCode); } // Make sure things are cleaned-up not too late pipelineContext.addContextListener(new PipelineContext.ContextListener() { public void contextDestroyed(boolean success) { connectionResult.close(); } }); // Here we decide to copy to temp file and load as a URL. We could also provide bytes directly. final String tempURLString = NetUtils.inputStreamToAnyURI( connectionResult.getResponseInputStream(), NetUtils.REQUEST_SCOPE); image = Image.getInstance(URLFactory.createURL(tempURLString)); } } final String fieldNameStr = currentElement.attributeValue("acro-field-name"); if (fieldNameStr != null) { // Use field as placeholder final String fieldName = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, fieldNameStr, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); final float[] positions = groupContext.acroFields.getFieldPositions(fieldName); if (positions != null) { final Rectangle rectangle = new Rectangle(positions[1], positions[2], positions[3], positions[4]); // This scales the image so that it fits in the box (but the aspect ratio is not changed) image.scaleToFit(rectangle.getWidth(), rectangle.getHeight()); final float yPosition = positions[2] + rectangle.getHeight() - image.getScaledHeight(); image.setAbsolutePosition( positions[1] + (rectangle.getWidth() - image.getScaledWidth()) / 2, yPosition); // Add image groupContext.contentByte.addImage(image); } } else { // Use position, etc. final String leftAttribute = currentElement.attributeValue("left"); final String topAttribute = currentElement.attributeValue("top"); final String scalePercentAttribute = currentElement.attributeValue("scale-percent"); final String dpiAttribute = currentElement.attributeValue("dpi"); final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, leftAttribute); final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, topAttribute); final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX; final float yPosition = groupContext.pageHeight - (Float.parseFloat(topPosition) + groupContext.offsetY); final String scalePercent = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, scalePercentAttribute); final String dpi = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, dpiAttribute); // Set image parameters image.setAbsolutePosition(xPosition, yPosition); if (scalePercent != null) { image.scalePercent(Float.parseFloat(scalePercent)); } if (dpi != null) { final int dpiInt = Integer.parseInt(dpi); image.setDpi(dpiInt, dpiInt); } // Add image groupContext.contentByte.addImage(image); } } else { // NOP } } }
From source file:org.oss.pdfreporter.pdf.Page.java
License:Open Source License
@Override public void draw(IImage image, float x, float y) throws DocumentException { try {/* ww w . ja va2 s . com*/ Image pdfImage = getImage(image); pdfImage.setAbsolutePosition(x, y); delegate.addImage(pdfImage); } catch (Exception e) { throw new DocumentException(e); } }
From source file:org.oss.pdfreporter.pdf.Page.java
License:Open Source License
@Override public void draw(IImage image, float x, float y, float width, float height, ScaleMode mode) throws DocumentException { try {//from w ww.j a v a 2s . co m Image pdfImage = null; switch (mode) { case NONE: pdfImage = getImage(image); PdfTemplate t = delegate.getPdfWriter().getDirectContent().createTemplate(width, height); t.addImage(pdfImage, pdfImage.getWidth(), 0, 0, pdfImage.getHeight(), 0, height - pdfImage.getHeight()); pdfImage = Image.getInstance(t); break; case SCALE: pdfImage = getImage(image); pdfImage.scaleAbsolute(width, height); break; case SIZE: pdfImage = getImage(image); pdfImage.scaleToFit(width, height); break; } pdfImage.setAbsolutePosition(x, y); delegate.addImage(pdfImage); } catch (Exception e) { throw new DocumentException(e); } }
From source file:org.oss.pdfreporter.pdf.Page.java
License:Open Source License
@Override public void drawCropped(IImage image, float xoffset, float yoffset, float x, float y, float width, float height) throws DocumentException { try {//from w w w . ja v a2s. co m Image pdfImage = getImage(image); PdfTemplate t = delegate.getPdfWriter().getDirectContent().createTemplate(width, height); t.addImage(pdfImage, pdfImage.getWidth(), 0, 0, pdfImage.getHeight(), xoffset, -yoffset + height - pdfImage.getHeight()); pdfImage = Image.getInstance(t); pdfImage.setAbsolutePosition(x, y); delegate.addImage(pdfImage); } catch (Exception e) { throw new DocumentException(e); } }
From source file:org.posterita.businesslogic.performanceanalysis.POSReportManager.java
License:Open Source License
public static String getCompleteOrderPDFReport(Properties ctx, int orderId, String trxName) throws OperationException { String docStatus = null;// w w w . j a va 2 s.c o m String dateOrdered = null; String orderType = null; String orgName = null; String orgAddress = null; String salesRep = null; String paymentBy = null; String customerName = null; String customerAddress = null; String documentNo = null; String currency = "Rs "; NumberFormat formatter = new DecimalFormat("###,###,##0.00"); currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol() + " "; MOrder order = new MOrder(ctx, orderId, trxName); // getting payment info int[] invoiceIds = MInvoice.getAllIDs(MInvoice.Table_Name, "AD_CLIENT_ID=" + Env.getAD_Client_ID(ctx) + " and C_ORDER_ID=" + order.get_ID(), null); double paymentByCash = 0.0; double paymentByCard = 0.0; double paymentByCheque = 0.0; MInvoice invoice = null; String paymentRule = null; boolean isMixed = false; for (int i = 0; i < invoiceIds.length; i++) { invoice = new MInvoice(ctx, invoiceIds[i], trxName); if (i == 0) { paymentRule = invoice.getPaymentRule(); } else { if (!paymentRule.equalsIgnoreCase(invoice.getPaymentRule())) { isMixed = true; } } if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_Cash)) { paymentByCash += invoice.getGrandTotal().doubleValue(); paymentBy = Constants.PAYMENT_RULE_CASH; } if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_CreditCard)) { paymentByCard += invoice.getGrandTotal().doubleValue(); paymentBy = Constants.PAYMENT_RULE_CARD; } if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_DirectDebit)) { paymentByCard += invoice.getGrandTotal().doubleValue(); paymentBy = Constants.PAYMENT_RULE_CARD; } if (invoice.getPaymentRule().equals(MOrder.PAYMENTRULE_Check)) { paymentByCheque += invoice.getGrandTotal().doubleValue(); paymentBy = Constants.PAYMENT_RULE_CHEQUE; } } // for if (isMixed) { paymentBy = "Mixed (Cash:" + formatter.format(paymentByCash) + " Card:" + formatter.format(paymentByCard) + " Cheque:" + formatter.format(paymentByCheque) + ")"; } // getting orgInfo MOrg org = new MOrg(ctx, order.getAD_Org_ID(), trxName); int location_id = org.getInfo().getC_Location_ID(); MLocation location = new MLocation(ctx, location_id, trxName); orgName = org.getName(); String address1 = (location.getAddress1() == null) ? " " : location.getAddress1(); String address2 = (location.getAddress2() == null) ? " " : location.getAddress2(); orgAddress = (address1 + " " + address2).trim(); // getting order type orderType = order.getOrderType(); // getting orderInfo docStatus = order.getDocStatusName(); documentNo = order.getDocumentNo(); Date d = new Date(order.getCreated().getTime()); SimpleDateFormat s = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1); dateOrdered = s.format(d); // getting salesrep int saleRep_id = order.getSalesRep_ID(); MUser user = new MUser(ctx, saleRep_id, trxName); salesRep = user.getName(); // getting customer info int bpartner_id = order.getBill_BPartner_ID(); BPartnerBean bean = BPartnerManager.getBpartner(ctx, bpartner_id, trxName); String name1 = (bean.getPartnerName() == null) ? " " : bean.getPartnerName(); String name2 = (bean.getName2() == null) ? " " : bean.getName2(); customerName = (name1 + " " + name2).trim(); address1 = (bean.getAddress1() == null) ? " " : bean.getAddress1(); address2 = (bean.getAddress2() == null) ? " " : bean.getAddress2(); customerAddress = (address1 + " " + address2).trim(); ArrayList<WebOrderLineBean> orderLineList = POSManager.populateOrderLines(ctx, order); // ----------------------------------- generating pdf // -------------------------------------- String reportName = RandomStringGenerator.randomstring() + ".pdf"; String reportPath = ReportManager.getReportPath(reportName); Font titleFont = new Font(Font.TIMES_ROMAN, 18, Font.BOLD); Font subtitleFont = new Font(Font.TIMES_ROMAN, 14, Font.BOLD); Font headerFont = new Font(Font.TIMES_ROMAN, 11, Font.BOLD); Font simpleFont = new Font(Font.TIMES_ROMAN, 10); float cellBorderWidth = 0.0f; // step 1: creation of a document-object Document document = new Document(PageSize.A4, 30, 30, 20, 40);// l,r,t,b // document.getPageSize().set; System.out.println(document.leftMargin()); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.getInstance(document, new FileOutputStream(reportPath)); // step 3: we open the document document.open(); // step 4: we add a paragraph to the document Image logo = null; String imageURI = PathInfo.PROJECT_HOME + "images/logo.gif"; // "images/pos/openBLUE_POS_Logo.gif"; try { byte logoData[] = OrganisationManager.getLogo(ctx, null); logo = Image.getInstance(logoData); } catch (LogoException ex) { logo = Image.getInstance(imageURI); } logo.setAbsolutePosition(document.left(), document.top() - logo.getHeight()); document.add(logo); PdfPTable table = new PdfPTable(2); PdfPCell cell = null; // table.getDefaultCell().setPadding(5.0f); table.setWidthPercentage(100.0f); // header cell Paragraph title = new Paragraph(); title.add(new Chunk(orgName, subtitleFont)); title.add(new Chunk("\n")); title.add(new Chunk(orgAddress, subtitleFont)); // cell = new PdfPCell(new Paragraph(new // Chunk("Title1",titleFont))); cell = new PdfPCell(title); cell.setColspan(2); cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setFixedHeight(logo.getHeight()); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); cell = new PdfPCell(new Paragraph("")); cell.setBorderWidth(cellBorderWidth); cell.setFixedHeight(10); cell.setColspan(2); table.addCell(cell); // doc type cell = new PdfPCell(new Paragraph(new Chunk(orderType, titleFont))); cell.setColspan(2); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // spacing cell = new PdfPCell(new Paragraph("")); cell.setBorderWidth(cellBorderWidth); cell.setFixedHeight(10); cell.setColspan(2); table.addCell(cell); // row 1 cell = new PdfPCell(new Paragraph(new Chunk(customerName, headerFont))); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); cell = new PdfPCell(new Paragraph(new Chunk("Sales Rep: " + salesRep, headerFont))); cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // row 2 cell = new PdfPCell(new Paragraph(new Chunk(customerAddress, headerFont))); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // spacing cell = new PdfPCell(new Paragraph("")); cell.setBorderWidth(cellBorderWidth); cell.setFixedHeight(10); cell.setColspan(2); table.addCell(cell); // row 3 cell = new PdfPCell(new Paragraph(new Chunk("Ref No: " + documentNo, headerFont))); cell.setColspan(2); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // row 4 cell = new PdfPCell(new Paragraph(new Chunk("Doc Status: " + docStatus, headerFont))); cell.setColspan(2); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // row 5 cell = new PdfPCell(new Paragraph(new Chunk("Payment By: " + paymentBy, headerFont))); cell.setColspan(2); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // row 6 cell = new PdfPCell(new Paragraph(new Chunk("Date: " + dateOrdered, headerFont))); cell.setColspan(2); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // spacing cell = new PdfPCell(new Paragraph("")); cell.setColspan(2); cell.setFixedHeight(10); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // spacing cell = new PdfPCell(new Paragraph("")); cell.setColspan(2); cell.setFixedHeight(10); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // ------------------------------------------------------ cell = new PdfPCell(); cell.setColspan(2); cell.setBorderWidth(cellBorderWidth); PdfPTable t = new PdfPTable(6); t.getDefaultCell().setPadding(3.0f); t.setWidthPercentage(100.0f); int[] widths = { 1, 4, 1, 2, 2, 2 }; t.setWidths(widths); // setting headers t.addCell(new Paragraph(new Chunk("SerNo", headerFont))); t.addCell(new Paragraph(new Chunk("Name", headerFont))); t.addCell(new Paragraph(new Chunk("Qty", headerFont))); t.addCell(new Paragraph(new Chunk("Price", headerFont))); t.addCell(new Paragraph(new Chunk("VAT", headerFont))); t.addCell(new Paragraph(new Chunk("Total", headerFont))); // setting table data // --------------------------------writing table // data------------------------------ int serNo = 0; int totalQty = 0; double totalAmt = 0.0; double totalTaxAmt = 0.0; double grandTotal = 0.0; BigDecimal qty = null; BigDecimal lineAmt = null; BigDecimal taxAmt = null; BigDecimal lineTotalAmt = null; for (WebOrderLineBean orderlineBean : orderLineList) { serNo++; qty = orderlineBean.getQtyOrdered(); lineAmt = orderlineBean.getLineNetAmt(); taxAmt = orderlineBean.getTaxAmt(); lineTotalAmt = orderlineBean.getLineTotalAmt(); totalQty += qty.intValue(); totalAmt += lineAmt.doubleValue(); totalTaxAmt += taxAmt.doubleValue(); grandTotal += lineTotalAmt.doubleValue(); t.addCell(new Paragraph(new Chunk(serNo + "", simpleFont))); t.addCell(new Paragraph(new Chunk(orderlineBean.getProductName(), simpleFont))); t.addCell(new Paragraph(new Chunk(qty.intValue() + "", simpleFont))); t.addCell(new Paragraph(new Chunk(formatter.format(lineAmt.doubleValue()), simpleFont))); t.addCell(new Paragraph(new Chunk(formatter.format(taxAmt.doubleValue()), simpleFont))); t.addCell(new Paragraph(new Chunk(formatter.format(lineTotalAmt.doubleValue()), simpleFont))); } // ----------------------------------------------------------------------------------- // setting table footer t.getDefaultCell().setBackgroundColor(new Color(240, 240, 240)); PdfPCell c = new PdfPCell(new Paragraph(new Chunk("ORDER TOTAL", headerFont))); c.setColspan(2); c.setBackgroundColor(new Color(240, 240, 240)); t.addCell(c); t.addCell(new Paragraph(new Chunk(totalQty + "", simpleFont))); t.addCell(new Paragraph(new Chunk(currency + formatter.format(totalAmt), simpleFont))); t.addCell(new Paragraph(new Chunk(currency + formatter.format(totalTaxAmt), simpleFont))); t.addCell(new Paragraph(new Chunk(currency + formatter.format(grandTotal), simpleFont))); t.setSplitRows(true); cell.addElement(t); // ------------------------------------------------------ // table.addCell(cell); table.setSplitRows(true); document.add(table); document.add(t); } catch (Exception e) { throw new OperationException(e); } // step 5: we close the document document.close(); return reportName; }
From source file:org.posterita.businesslogic.performanceanalysis.POSReportManager.java
License:Open Source License
public static String getShipmentPDFReport(Properties ctx, int minoutId, String trxName) throws OperationException { String docStatus = null;//from w w w .j a v a 2 s .c o m String dateOrdered = null; String docType = null; String orgName = null; String orgAddress = null; String salesRep = null; String phone = " "; String fax = " "; String customerName = null; String customerAddress = null; String documentNo = null; MInOut minout = MinOutManager.loadMInOut(ctx, minoutId, trxName); // getting orgInfo MOrg org = new MOrg(ctx, minout.getAD_Org_ID(), trxName); int location_id = org.getInfo().getC_Location_ID(); MLocation location = new MLocation(ctx, location_id, trxName); MBPartner orgPartner = new MBPartner(ctx, org.getLinkedC_BPartner_ID(trxName), trxName); MBPartnerLocation meLocation[] = MBPartnerLocation.getForBPartner(ctx, orgPartner.get_ID()); if (meLocation.length != 1) throw new OperationException("Should have only 1 location for organisation business partner!!"); MBPartnerLocation orgLocation = meLocation[0]; if (orgLocation.getPhone() != null) phone = orgLocation.getPhone(); if (orgLocation.getFax() != null) fax = orgLocation.getFax(); ; orgName = org.getName(); String address1 = (location.getAddress1() == null) ? " " : location.getAddress1(); String address2 = (location.getAddress2() == null) ? " " : location.getAddress2(); orgAddress = (address1 + " " + address2).trim(); // getting order type MDocType doctype = MDocType.get(ctx, minout.getC_DocType_ID()); docType = doctype.getName(); // getting orderInfo docStatus = minout.getDocStatusName(); documentNo = minout.getDocumentNo(); Date d = new Date(minout.getCreated().getTime()); SimpleDateFormat s = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1); dateOrdered = s.format(d); // getting salesrep int saleRep_id = minout.getSalesRep_ID(); MUser user = new MUser(ctx, saleRep_id, trxName); salesRep = user.getName(); // getting customer info int bpartner_id = minout.getC_BPartner_ID(); BPartnerBean bean = BPartnerManager.getBpartner(ctx, bpartner_id, trxName); String name1 = (bean.getPartnerName() == null) ? " " : bean.getPartnerName(); String name2 = (bean.getName2() == null) ? " " : bean.getName2(); customerName = (name1 + " " + name2).trim(); address1 = (bean.getAddress1() == null) ? " " : bean.getAddress1(); address2 = (bean.getAddress2() == null) ? " " : bean.getAddress2(); customerAddress = (address1 + " " + address2).trim(); ArrayList<WebMinOutLineBean> orderLineList = MinOutManager.getWebMinOutLines(ctx, minout); // ----------------------------------- generating pdf // -------------------------------------- String reportName = RandomStringGenerator.randomstring() + ".pdf"; String reportPath = ReportManager.getReportPath(reportName); Font titleFont = new Font(Font.TIMES_ROMAN, 18, Font.BOLD); Font subtitleFont = new Font(Font.TIMES_ROMAN, 14, Font.BOLD); Font headerFont = new Font(Font.TIMES_ROMAN, 11, Font.BOLD); Font simpleFont = new Font(Font.TIMES_ROMAN, 10); float cellBorderWidth = 0.0f; // step 1: creation of a document-object Document document = new Document(PageSize.A4, 30, 30, 20, 40);// l,r,t,b // document.getPageSize().set; System.out.println(document.leftMargin()); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.getInstance(document, new FileOutputStream(reportPath)); // step 3: we open the document document.open(); // step 4: we add a paragraph to the document Image logo = null; // TODO: make this part dynamic <------------------------------ // IMPORTANT !!!!!!!!!!!!!!!!!!!!!!!!!!! String imageURI = PathInfo.PROJECT_HOME + "images/pos/openBLUE_POS_Logo.gif"; logo = Image.getInstance(imageURI); // MAttachment attachment = new // MAttachment(ctx,MOrg.Table_ID,org.getID(),null); // logo = Image.getInstance(attachment.getEntries()[0].getData()); try { byte logoData[] = OrganisationManager.getLogo(ctx, null); logo = Image.getInstance(logoData); } catch (LogoException ex) { logo = Image.getInstance(imageURI); } logo.setAbsolutePosition(document.left(), document.top() - logo.getHeight()); document.add(logo); PdfPTable table = new PdfPTable(2); PdfPCell cell = null; // table.getDefaultCell().setPadding(5.0f); table.setWidthPercentage(100.0f); // header cell Paragraph title = new Paragraph(); title.add(new Chunk(orgName, subtitleFont)); title.add(new Chunk("\n")); title.add(new Chunk(orgAddress, subtitleFont)); title.add(new Chunk("\n")); title.add(new Chunk("Phone: " + phone, subtitleFont)); title.add(new Chunk("\n")); title.add(new Chunk("Fax: " + fax, subtitleFont)); // cell = new PdfPCell(new Paragraph(new // Chunk("Title1",titleFont))); cell = new PdfPCell(title); cell.setColspan(2); cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setFixedHeight(logo.getHeight()); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); cell = new PdfPCell(new Paragraph("")); cell.setBorderWidth(cellBorderWidth); cell.setFixedHeight(10); cell.setColspan(2); table.addCell(cell); // doc type cell = new PdfPCell(new Paragraph(new Chunk(docType, titleFont))); cell.setColspan(2); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // spacing cell = new PdfPCell(new Paragraph("")); cell.setBorderWidth(cellBorderWidth); cell.setFixedHeight(10); cell.setColspan(2); table.addCell(cell); // row 1 cell = new PdfPCell(new Paragraph(new Chunk(customerName, headerFont))); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); cell = new PdfPCell(new Paragraph(new Chunk("Sales Rep: " + salesRep, headerFont))); cell.setHorizontalAlignment(PdfPCell.ALIGN_RIGHT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // row 2 cell = new PdfPCell(new Paragraph(new Chunk(customerAddress, headerFont))); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // spacing cell = new PdfPCell(new Paragraph("")); cell.setBorderWidth(cellBorderWidth); cell.setFixedHeight(10); cell.setColspan(2); table.addCell(cell); // row 3 cell = new PdfPCell(new Paragraph(new Chunk("No: " + documentNo, headerFont))); cell.setColspan(2); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // row 4 cell = new PdfPCell(new Paragraph(new Chunk("Doc Status: " + docStatus, headerFont))); cell.setColspan(2); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); /* * //row 5 cell = new PdfPCell(new Paragraph(new Chunk("Payment By: * "+paymentBy,headerFont))); cell.setColspan(2); * cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); * cell.setBorderWidth(cellBorderWidth); table.addCell(cell); */ // row 6 cell = new PdfPCell(new Paragraph(new Chunk("Date: " + dateOrdered, headerFont))); cell.setColspan(2); cell.setHorizontalAlignment(PdfPCell.ALIGN_LEFT); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // spacing cell = new PdfPCell(new Paragraph("")); cell.setColspan(2); cell.setFixedHeight(10); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // spacing cell = new PdfPCell(new Paragraph("")); cell.setColspan(2); cell.setFixedHeight(10); cell.setBorderWidth(cellBorderWidth); table.addCell(cell); // ------------------------------------------------------ cell = new PdfPCell(); cell.setColspan(2); cell.setBorderWidth(cellBorderWidth); PdfPTable t = new PdfPTable(3); t.getDefaultCell().setPadding(3.0f); t.setWidthPercentage(100.0f); int[] widths = { 1, 10, 1 }; t.setWidths(widths); // setting headers t.addCell(new Paragraph(new Chunk("SerNo", headerFont))); t.addCell(new Paragraph(new Chunk("Name", headerFont))); t.addCell(new Paragraph(new Chunk("Qty", headerFont))); // setting table data // --------------------------------writing table // data------------------------------ int serNo = 0; BigDecimal qty = null; for (WebMinOutLineBean orderlineBean : orderLineList) { serNo++; qty = orderlineBean.getQtyOrdered(); t.addCell(new Paragraph(new Chunk(serNo + "", simpleFont))); t.addCell(new Paragraph(new Chunk(orderlineBean.getProductName(), simpleFont))); t.addCell(new Paragraph(new Chunk(qty.intValue() + "", simpleFont))); } // ----------------------------------------------------------------------------------- // table.addCell(cell); table.setSplitRows(true); document.add(table); document.add(t); } catch (Exception e) { throw new OperationException(e); } // step 5: we close the document document.close(); return reportName; }
From source file:org.saiku.web.rest.resources.ExporterResource.java
License:Apache License
/** * Export chart to a file./* w w w .j av a2s . co m*/ * @summary Export Chart. * @param type The export type (png, svg, jpeg) * @param svg The SVG * @param size The size * @param name The name * @return A reponse containing the chart export. */ @POST @Produces({ "image/*" }) @Path("/saiku/chart") public Response exportChart(@FormParam("type") @DefaultValue("png") String type, @FormParam("svg") String svg, @FormParam("size") Integer size, @FormParam("name") String name) { try { final String imageType = type.toUpperCase(); Converter converter = Converter.byType("PDF"); if (converter == null) { throw new Exception("Image convert is null"); } // resp.setContentType(converter.getContentType()); // resp.setHeader("Content-disposition", "attachment; filename=chart." + converter.getExtension()); // final Integer size = req.getParameter("size") != null? Integer.parseInt(req.getParameter("size")) : null; // final String svgDocument = req.getParameter("svg"); // if (svgDocument == null) // { // resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'svg' parameter"); // return; // } if (StringUtils.isBlank(svg)) { throw new Exception("Missing 'svg' parameter"); } final InputStream in = new ByteArrayInputStream(svg.getBytes("UTF-8")); final ByteArrayOutputStream out = new ByteArrayOutputStream(); converter.convert(in, out, size); out.flush(); byte[] doc = out.toByteArray(); byte[] b = null; if (getVersion() != null && !getVersion().contains("EE")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfReader reader = new PdfReader(doc); PdfStamper pdfStamper = new PdfStamper(reader, baos); URL dir_url = ExporterResource.class.getResource("/org/saiku/web/svg/watermark.png"); Image image = Image.getInstance(dir_url); for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfContentByte content = pdfStamper.getOverContent(i); image.setAbsolutePosition(450f, 280f); /*image.setAbsolutePosition(reader.getPageSize(1).getWidth() - image.getScaledWidth(), reader.getPageSize (1).getHeight() - image.getScaledHeight());*/ //image.setAlignment(Image.MIDDLE); content.addImage(image); } pdfStamper.close(); b = baos.toByteArray(); } else { b = doc; } if (!type.equals("pdf")) { PDDocument document = PDDocument.load(new ByteArrayInputStream(b), null); PDPageTree pdPages = document.getDocumentCatalog().getPages(); PDPage page = pdPages.get(0); BufferedImage o = new PDFRenderer(document).renderImage(0); ByteArrayOutputStream imgb = new ByteArrayOutputStream(); String ct = ""; String ext = ""; if (type.equals("png")) { ct = "image/png"; ext = "png"; } else if (type.equals("jpg")) { ct = "image/jpg"; ext = "jpg"; } ImageIO.write(o, type, imgb); byte[] outfile = imgb.toByteArray(); if (name == null || name.equals("")) { name = "chart"; } return Response.ok(outfile).type(ct) .header("content-disposition", "attachment; filename = " + name + "." + ext) .header("content-length", outfile.length).build(); } else { if (name == null || name.equals("")) { name = "chart"; } return Response.ok(b).type(converter.getContentType()) .header("content-disposition", "attachment; filename = " + name + "." + converter.getExtension()) .header("content-length", b.length).build(); } } catch (Exception e) { log.error("Error exporting Chart to " + type, e); return Response.serverError().entity(e.getMessage()).status(Status.INTERNAL_SERVER_ERROR).build(); } }
From source file:org.silverpeas.core.util.PdfUtil.java
License:Open Source License
/** * Add a image under or over content on each page of a PDF file. * @param pdfSource the source pdf file, this content is not modified by this method * @param imageToAdd the image file/*from w ww . ja v a 2 s .c o m*/ * @param pdfDestination the destination pdf file, with the image under or over content * @param isBackground indicates if image is addes under or over the content of the pdf source * file */ private static void addImageOnEachPage(InputStream pdfSource, File imageToAdd, OutputStream pdfDestination, final boolean isBackground) { // Verify given arguments if (imageToAdd == null || !imageToAdd.isFile()) { throw new SilverpeasRuntimeException("The image file doesn't exist"); } else if (!FileUtil.isImage(imageToAdd.getPath())) { throw new SilverpeasRuntimeException("The picture to add is not an image file"); } PdfReader reader = null; try { // Get a reader of PDF content reader = new PdfReader(pdfSource); // Obtain the total number of pages int pdfNbPages = reader.getNumberOfPages(); PdfStamper stamper = new PdfStamper(reader, pdfDestination); // Load the image Image image = Image.getInstance(imageToAdd.getPath()); float imageWidth = image.getWidth(); float imageHeigth = image.getHeight(); // Adding the image on each page of the PDF for (int i = 1; i <= pdfNbPages; i++) { // Page sizes Rectangle rectangle = reader.getPageSize(i); // Compute the scale of the image float scale = Math.min(100, (rectangle.getWidth() / imageWidth * 100)); image.scalePercent(Math.min(scale, (rectangle.getHeight() / imageHeigth * 100))); // Setting the image position for the current page image.setAbsolutePosition(computeImageCenterPosition(rectangle.getWidth(), image.getScaledWidth()), computeImageCenterPosition(rectangle.getHeight(), image.getScaledHeight())); // Adding image PdfContentByte imageContainer = isBackground ? stamper.getUnderContent(i) : stamper.getOverContent(i); imageContainer.addImage(image); } // End of the treatment : closing the stamper stamper.close(); } catch (Exception e) { SilverLogger.getLogger(PdfUtil.class).error(e); throw new SilverpeasRuntimeException( "A problem has occurred during the adding of an image into a pdf file", e); } finally { if (reader != null) { reader.close(); } } }
From source file:org.silverpeas.util.PdfUtil.java
License:Open Source License
/** * Add a image under or over content on each page of a PDF file. * @param pdfSource the source pdf file, this content is not modified by this method * @param imageToAdd the image file//ww w .j a v a 2 s .c o m * @param pdfDestination the destination pdf file, with the image under or over content * @param isBackground indicates if image is addes under or over the content of the pdf source * file */ private static void addImageOnEachPage(InputStream pdfSource, File imageToAdd, OutputStream pdfDestination, final boolean isBackground) { // Verify given arguments if (imageToAdd == null || !imageToAdd.isFile()) { throw new RuntimeException("The image file doesn't exist"); } else if (!FileUtil.isImage(imageToAdd.getPath())) { throw new RuntimeException("The picture to add is not an image file"); } PdfReader reader = null; try { // Get a reader of PDF content reader = new PdfReader(pdfSource); // Obtain the total number of pages int pdfNbPages = reader.getNumberOfPages(); PdfStamper stamper = new PdfStamper(reader, pdfDestination); // Load the image Image image = Image.getInstance(imageToAdd.getPath()); float imageWidth = image.getWidth(); float imageHeigth = image.getHeight(); // Adding the image on each page of the PDF for (int i = 1; i <= pdfNbPages; i++) { // Page sizes Rectangle rectangle = reader.getPageSize(i); // Compute the scale of the image float scale = Math.min(100, (rectangle.getWidth() / imageWidth * 100)); image.scalePercent(Math.min(scale, (rectangle.getHeight() / imageHeigth * 100))); // Setting the image position for the current page image.setAbsolutePosition(computeImageCenterPosition(rectangle.getWidth(), image.getScaledWidth()), computeImageCenterPosition(rectangle.getHeight(), image.getScaledHeight())); // Adding image PdfContentByte imageContainer = isBackground ? stamper.getUnderContent(i) : stamper.getOverContent(i); imageContainer.addImage(image); } // End of the treatment : closing the stamper stamper.close(); } catch (Exception e) { SilverTrace.error("util", "PdfUtil.stamp", "EX_ERROR_PDF_ADD_WATERWARK", e); throw new RuntimeException("A problem has occured during the adding of an image into a pdf file", e); } finally { if (reader != null) { reader.close(); } } }
From source file:org.sipfoundry.faxrx.FaxProcessor.java
License:Open Source License
private File tiff2Pdf(File tiffFile) { Pattern pattern = Pattern.compile("(.*).tiff"); Matcher matcher = pattern.matcher(tiffFile.getName()); boolean matchFound = matcher.find(); // check if tiffFile is actually a TIFF file, just in case if (matchFound) { // located at default tmp-file directory File pdfFile = new File(System.getProperty("java.io.tmpdir"), matcher.group(1) + ".pdf"); try {//w ww . j av a 2 s . co m // read TIFF file RandomAccessFileOrArray tiff = new RandomAccessFileOrArray(tiffFile.getAbsolutePath()); // get number of pages of TIFF file int pages = TiffImage.getNumberOfPages(tiff); // create PDF file Document pdf = new Document(PageSize.LETTER, 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(pdf, new FileOutputStream(pdfFile)); writer.setStrictImageSequence(true); // open PDF filex pdf.open(); PdfContentByte contentByte = writer.getDirectContent(); // write PDF file page by page for (int page = 1; page <= pages; page++) { Image temp = TiffImage.getTiffImage(tiff, page); temp.scalePercent(7200f / temp.getDpiX(), 7200f / temp.getDpiY()); pdf.setPageSize(new Rectangle(temp.getScaledWidth(), temp.getScaledHeight())); temp.setAbsolutePosition(0, 0); contentByte.addImage(temp); pdf.newPage(); } // close PDF file pdf.close(); } catch (Exception e) { LOG.error("faxrx::tiff2Pdf error " + e.getMessage()); e.printStackTrace(); return null; } return pdfFile; } else { return null; } }