List of usage examples for com.lowagie.text.pdf Barcode setBarHeight
public void setBarHeight(float barHeight)
From source file:org.jaffa.modules.printing.services.FormPrintEngineIText.java
License:Open Source License
/** * This will fill in the page with data, * m_currentPageData contains the details of the current page being printed * @throws FormPrintException Thrown if there is any form processing problems *//*from w w w . j a va 2 s.c o m*/ protected void fillPageFields() throws FormPrintException { log.debug("fillPageFields: Page=" + getCurrentPage()); try { PdfContentByte cb = m_writer.getDirectContent(); PageDetailsExtended page = (PageDetailsExtended) getCurrentPageData(); // // Test code to throw a barcode on the page... // Barcode39 code39 = new Barcode39(); // code39.setCode("CODE39-1234567890"); // code39.setStartStopText(false); // code39.setSize(0); // Image image39 = code39.createImageWithBarcode(cb, null, null); // com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(2); // table.setWidthPercentage(100); // table.getDefaultCell().setBorder(com.lowagie.text.Rectangle.NO_BORDER); // table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); // table.getDefaultCell().setFixedHeight(70); // table.addCell("CODE 39"); // table.addCell(new Phrase(new Chunk(image39, 0, 0))); // m_generatedDoc.add(table); // //-------------------------------------------------- // Loop through each field to be inserted for (Iterator i = page.fieldList.iterator(); i.hasNext();) { String fieldname = (String) i.next(); // Get the properties for displaying this field FieldProperties props = (FieldProperties) page.fieldProperties.get(fieldname); // Get the data to display FormPrintEngine.DomValue data = new FormPrintEngine.DomValue(fieldname, props.sampleData); // Caluclate Clipping Region float x1 = Math.min(props.x1, props.x2); float x2 = Math.max(props.x1, props.x2); float y1 = Math.min(props.y1, props.y2); float y2 = Math.max(props.y1, props.y2); float w = Math.abs(props.x1 - props.x2) + 1; float h = Math.abs(props.y1 - props.y2) + 1; if (log.isDebugEnabled()) log.debug("Print Field " + fieldname + "=" + data.getObject() + " @ [(" + x1 + "," + y1 + ")->(" + x2 + "," + y2 + ")]"); // Default the font if not specified String font = BaseFont.HELVETICA; if (props.fontFace != null) font = props.fontFace; // Handle Barcodes diffently withing iText, don't just use fonts if (font.startsWith("Barcode")) { String bcClassName = "com.lowagie.text.pdf." + font; Object bcode = null; String dataStr = data.getValue(); if (dataStr != null) { log.debug("Barcode Data String = " + dataStr); // Try and create the correct Barcode Object try { Class bcClass = Class.forName(bcClassName); bcode = bcClass.newInstance(); } catch (Exception e) { String err = "Can't Create Barcode Object for barcode type '" + font + "' on field " + fieldname; log.error(err, e); } // Only continue if the barcode object was created if (bcode != null) { // Generate and Print barcode, based on common interface if (bcode instanceof Barcode) { Barcode b = (Barcode) bcode; // Set some default output a barcode b.setCode(dataStr); if (props.fontSize <= 0) { // Hide text if font size is 0, and make the barcode height the size of the box b.setBarHeight(h); b.setFont(null); } else { b.setSize(props.fontSize); // size of text under barcode b.setBarHeight(h - props.fontSize - 5); // Adjust Bar Height to allow for font size } b.setN(2); // Wide Bars // Set custom parameters setBarcodeParams(fieldname, bcode, props.style); // Print out barcode Image image = ((Barcode) bcode).createImageWithBarcode(cb, null, null); printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate); } else // Print PDF417 barcode, not based on common interface if (bcode instanceof BarcodePDF417) { BarcodePDF417 b = (BarcodePDF417) bcode; // Set some default output a barcode b.setText(dataStr); b.setErrorLevel(5); // Set custom parameters setBarcodeParams(fieldname, bcode, props.style); log.debug("PDF417 Settings\n" + "BitColumns=" + b.getBitColumns() + "\n" + "CodeColumns=" + b.getCodeColumns() + "\n" + "CodeRows=" + b.getCodeRows() + "\n" + "ErrorLevel=" + b.getErrorLevel() + "\n" + "YHeight=" + b.getYHeight() + "\n" + "AspectRatio=" + b.getAspectRatio() + "\n" + "Options=" + b.getOptions() + "\n" + "LenCodewords=" + b.getLenCodewords()); // Print out barcode //image = b.getImage(); printImage(b.getImage(), cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate); } else { // Error, unknown barcode String err = "Error, No print handler for barcode object " + bcode.getClass().getName(); log.error(err); //throw new EngineProcessingException(err); } } } else log.debug("SKIPPED BARCODE : No data for " + fieldname); // Handle Images differently within iText, native support for JFreeChart } else if ("image".equalsIgnoreCase(font)) { try { java.awt.Image image = data.getDomImage(); // Add an image to the page if (image != null) { if (fieldname.startsWith("watermark")) { // Add an image-based watermark to the under content layer PdfContentByte contentUnder = m_writer.getDirectContentUnder(); if (props.opacity != 1f) { PdfGState gs = new PdfGState(); gs.setFillOpacity(props.opacity); contentUnder.setGState(gs); } printImage(image, contentUnder, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate); } else { // Add an image to main page layer printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate); } } } catch (IOException e) { // Add Error on page. Phrase text = new Phrase("Image Error", FontFactory .getFont(FontFactory.HELVETICA_BOLDOBLIQUE, 8f, 0, ColorHelper.getColor("red"))); ColumnText ct = new ColumnText(cb); ct.setSimpleColumn(text, x1, y1, x2, y2, 8f, Element.ALIGN_LEFT); } } else if (fieldname.startsWith("watermark")) { // Add a text-based watermark String text = data.getValue(); PdfContentByte contentUnder = m_writer.getDirectContentUnder(); if (props.opacity != 1f) { PdfGState gs = new PdfGState(); gs.setFillOpacity(props.opacity); contentUnder.setGState(gs); } // The text aligns (left, center, right) on the pivot point. // Default to align left. float pivotX = x1; float pivotY = y1; if (Element.ALIGN_CENTER == props.align) { pivotX = (x1 / 2) + (x2 / 2); pivotY = y1; } else if (Element.ALIGN_RIGHT == props.align) { pivotX = x2; pivotY = y1; } Phrase watermark = new Phrase(text, FontFactory.getFont(props.fontFace, props.fontSize, decodeFontStyle(props.style), ColorHelper.getColor(defaultWatermarkColor))); ColumnText.showTextAligned(contentUnder, props.align, watermark, pivotX, pivotY, props.rotate); } else { // Handle printing of basic Text float lineHeight = props.fontSize; String str = data.getValue(); if (str != null) { // Add a bounded column to add text to. Phrase text = new Phrase(str, FontFactory.getFont(props.fontFace, props.fontSize, decodeFontStyle(props.style), ColorHelper.getColor(props.color))); ColumnText ct = new ColumnText(cb); if (props.fitMethod == FIT_METHOD_CLIP) // set up column with height/width restrictions ct.setSimpleColumn(text, x1, y1, x2, y2, lineHeight, props.align); else // set up column without (i.e. large) height/width restrictions ct.setSimpleColumn(text, x1, y1, 1000, 0, lineHeight, props.align); ct.go(); } } // Draw outline boxes arround fields if (isTemplateMode()) { cb.setLineWidth(0.5f); cb.setLineDash(4f, 2f); cb.setColorStroke(new Color(0xA0, 0xA0, 0xA0)); cb.moveTo(x1, y1); cb.lineTo(x1, y2); cb.lineTo(x2, y2); cb.lineTo(x2, y1); cb.lineTo(x1, y1); cb.stroke(); } } // end for-loop } catch (DocumentException e) { String err = "Error printing data - " + e.getMessage(); log.error(err, e); throw new EngineProcessingException(err); // } catch (IOException e) { // String err = "Error printing data - " + e.getMessage(); // log.error(err ,e); // throw new EngineProcessingException(err); } }
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 .ja v a2 s . co 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 } } }