List of usage examples for com.lowagie.text.pdf PdfContentByte ALIGN_CENTER
int ALIGN_CENTER
To view the source code for com.lowagie.text.pdf PdfContentByte ALIGN_CENTER.
Click Source Link
From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java
License:Open Source License
protected void readInput(PipelineContext pipelineContext, ProcessorInput input, Config config, OutputStream outputStream) { final org.dom4j.Document configDocument = readCacheInputAsDOM4J(pipelineContext, "model");// TODO: after all, should we use "config"? final org.dom4j.Document instanceDocument = readInputAsDOM4J(pipelineContext, input); final Configuration configuration = XPathCache.getGlobalConfiguration(); final DocumentInfo configDocumentInfo = new DocumentWrapper(configDocument, null, configuration); final DocumentInfo instanceDocumentInfo = new DocumentWrapper(instanceDocument, null, configuration); try {//from w ww . j a v a 2 s . c om // Get reader final String templateHref = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@href", null, null, functionLibrary, null, null, null);//TODO: LocationData // Create PDF reader final PdfReader reader; { final String inputName = ProcessorImpl.getProcessorInputSchemeInputName(templateHref); 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 reader reader = new PdfReader(os.toByteArray()); } else { // Read and create the reader reader = new PdfReader(URLFactory.createURL(templateHref)); } } // Get total number of pages final int pageCount = reader.getNumberOfPages(); // Get size of first page final Rectangle pageSize = reader.getPageSize(1); final float width = pageSize.getWidth(); final float height = pageSize.getHeight(); final String showGrid = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@show-grid", null, null, functionLibrary, null, null, null);//TODO: LocationData final PdfStamper stamper = new PdfStamper(reader, outputStream); stamper.setFormFlattening(true); for (int currentPage = 1; currentPage <= pageCount; currentPage++) { final PdfContentByte contentByte = stamper.getOverContent(currentPage); // Handle root group final GroupContext initialGroupContext = new GroupContext(contentByte, stamper.getAcroFields(), height, currentPage, Collections.singletonList((Item) instanceDocumentInfo), 1, 0, 0, "Courier", 14, 15.9f); handleGroup(pipelineContext, initialGroupContext, Dom4jUtils.elements(configDocument.getRootElement()), functionLibrary, reader); // Handle preview grid (NOTE: This can be heavy in memory.) if ("true".equalsIgnoreCase(showGrid)) { final float topPosition = 10f; final BaseFont baseFont2 = BaseFont.createFont("Courier", BaseFont.CP1252, BaseFont.NOT_EMBEDDED); contentByte.beginText(); { // 20-pixel lines and side legends contentByte.setFontAndSize(baseFont2, (float) 7); for (int w = 0; w <= width; w += 20) { for (int h = 0; h <= height; h += 2) contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h, 0); } for (int h = 0; h <= height; h += 20) { for (int w = 0; w <= width; w += 2) contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h, 0); } for (int w = 0; w <= width; w += 20) { contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w, height - topPosition, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w, topPosition, 0); } for (int h = 0; h <= height; h += 20) { contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, (float) 5, height - h, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, width - (float) 5, height - h, 0); } // 10-pixel lines contentByte.setFontAndSize(baseFont2, (float) 3); for (int w = 10; w <= width; w += 10) { for (int h = 0; h <= height; h += 2) contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h, 0); } for (int h = 10; h <= height; h += 10) { for (int w = 0; w <= width; w += 2) contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h, 0); } } contentByte.endText(); } } // Close the document // document.close(); stamper.close(); } catch (Exception e) { throw new OXFException(e); } }
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 w ww . ja v a2 s . com 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.oscarehr.casemgmt.service.PageNumberStamper.java
License:Open Source License
public void onEndPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.getDirectContent(); cb.saveState();/*from w w w. ja v a2 s.c o m*/ String text = "Page " + writer.getPageNumber() + " of "; // height where text starts float textBase = document.bottom() - getBaseOffset(); float textSize = getFont().getWidthPoint(text, getFontSize()); float width = document.getPageSize().getWidth(); float center = width / 2.0f; cb.beginText(); cb.setFontAndSize(getFont(), getFontSize()); cb.setTextMatrix(document.left(), textBase); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, text, center, textBase, 0); cb.endText(); cb.addTemplate(total, center + (textSize / 2.0f), textBase); cb.restoreState(); }
From source file:org.oscarehr.casemgmt.service.PromoTextStamper.java
License:Open Source License
/** * Adds promo text, date and current page number to each page * // www . ja v a2 s .c o m * @param writer * @param document */ public void onEndPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.getDirectContent(); cb.saveState(); float textBase = document.bottom() - getBaseOffset(); float width = document.getPageSize().getWidth(); float center = width / 2.0f; cb.beginText(); cb.setFontAndSize(getFont(), getFontSize()); cb.setTextMatrix(document.left(), textBase); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, text, center, textBase, 0); cb.endText(); cb.restoreState(); }
From source file:org.oscarehr.common.printing.HtmlToPdfServlet.java
License:Open Source License
private static void printText(PdfContentByte over, String text, float x, float y) { over.beginText();// ww w . j a va 2 s . c o m over.showTextAligned(PdfContentByte.ALIGN_CENTER, text, x, y, 0); over.endText(); }
From source file:org.oscarehr.phr.web.PHRUserManagementAction.java
License:Open Source License
public ByteArrayOutputStream generateUserRegistrationLetter(String demographicNo, String username, String password) throws Exception { log.debug("Demographic " + demographicNo + " username " + username + " password " + password); DemographicDao demographicDao = (DemographicDao) SpringUtils.getBean("demographicDao"); Demographic demographic = demographicDao.getDemographic(demographicNo); final String PAGESIZE = "printPageSize"; Document document = new Document(); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter writer = null;/*w w w . j av a2s .com*/ try { writer = PdfWriter.getInstance(document, baosPDF); String title = "TITLE"; String template = "MyOscarLetterHead.pdf"; Properties printCfg = getCfgProp(); String[] cfgVal = null; StringBuilder tempName = null; // get the print prop values Properties props = new Properties(); props.setProperty("letterDate", UtilDateUtilities.getToday("yyyy-MM-dd")); props.setProperty("name", demographic.getFirstName() + " " + demographic.getLastName()); props.setProperty("dearname", demographic.getFirstName() + " " + demographic.getLastName()); props.setProperty("address", demographic.getAddress()); props.setProperty("city", demographic.getCity() + ", " + demographic.getProvince()); props.setProperty("postalCode", demographic.getPostal()); props.setProperty("credHeading", "MyOscar User Account Details"); props.setProperty("username", "Username: " + username); props.setProperty("password", "Password: " + password); //Temporary - the intro will change to be dynamic props.setProperty("intro", "We are pleased to provide you with a log in and password for your new MyOSCAR Personal Health Record. This account will allow you to connect electronically with our clinic. Please take a few minutes to review the accompanying literature for further information.We look forward to you benefiting from this service."); document.addTitle(title); document.addSubject(""); document.addKeywords("pdf, itext"); document.addCreator("OSCAR"); document.addAuthor(""); document.addHeader("Expires", "0"); Rectangle pageSize = PageSize.LETTER; document.setPageSize(pageSize); document.open(); // create a reader for a certain document String propFilename = oscar.OscarProperties.getInstance().getProperty("pdfFORMDIR", "") + "/" + template; PdfReader reader = null; try { reader = new PdfReader(propFilename); log.debug("Found template at " + propFilename); } catch (Exception dex) { log.debug("change path to inside oscar from :" + propFilename); reader = new PdfReader("/oscar/form/prop/" + template); log.debug("Found template at /oscar/form/prop/" + template); } // retrieve the total number of pages int n = reader.getNumberOfPages(); // retrieve the size of the first page Rectangle pSize = reader.getPageSize(1); float width = pSize.getWidth(); float height = pSize.getHeight(); log.debug("Width :" + width + " Height: " + height); PdfContentByte cb = writer.getDirectContent(); ColumnText ct = new ColumnText(cb); int fontFlags = 0; document.newPage(); PdfImportedPage page1 = writer.getImportedPage(reader, 1); cb.addTemplate(page1, 1, 0, 0, 1, 0, 0); BaseFont bf; // = normFont; String encoding; cb.setRGBColorStroke(0, 0, 255); String[] fontType; for (Enumeration e = printCfg.propertyNames(); e.hasMoreElements();) { tempName = new StringBuilder(e.nextElement().toString()); cfgVal = printCfg.getProperty(tempName.toString()).split(" *, *"); if (cfgVal[4].indexOf(";") > -1) { fontType = cfgVal[4].split(";"); if (fontType[1].trim().equals("italic")) fontFlags = Font.ITALIC; else if (fontType[1].trim().equals("bold")) fontFlags = Font.BOLD; else if (fontType[1].trim().equals("bolditalic")) fontFlags = Font.BOLDITALIC; else fontFlags = Font.NORMAL; } else { fontFlags = Font.NORMAL; fontType = new String[] { cfgVal[4].trim() }; } if (fontType[0].trim().equals("BaseFont.HELVETICA")) { fontType[0] = BaseFont.HELVETICA; encoding = BaseFont.CP1252; //latin1 encoding } else if (fontType[0].trim().equals("BaseFont.HELVETICA_OBLIQUE")) { fontType[0] = BaseFont.HELVETICA_OBLIQUE; encoding = BaseFont.CP1252; } else if (fontType[0].trim().equals("BaseFont.ZAPFDINGBATS")) { fontType[0] = BaseFont.ZAPFDINGBATS; encoding = BaseFont.ZAPFDINGBATS; } else { fontType[0] = BaseFont.COURIER; encoding = BaseFont.CP1252; } bf = BaseFont.createFont(fontType[0], encoding, BaseFont.NOT_EMBEDDED); // write in a rectangle area if (cfgVal.length >= 9) { Font font = new Font(bf, Integer.parseInt(cfgVal[5].trim()), fontFlags); ct.setSimpleColumn(Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), Integer.parseInt(cfgVal[7].trim()), (height - Integer.parseInt(cfgVal[8].trim())), Integer.parseInt(cfgVal[9].trim()), (cfgVal[0].trim().equals("left") ? Element.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? Element.ALIGN_RIGHT : Element.ALIGN_CENTER))); ct.setText(new Phrase(12, props.getProperty(tempName.toString(), ""), font)); ct.go(); continue; } // draw line directly if (tempName.toString().startsWith("__$line")) { cb.setRGBColorStrokeF(0f, 0f, 0f); cb.setLineWidth(Float.parseFloat(cfgVal[4].trim())); cb.moveTo(Float.parseFloat(cfgVal[0].trim()), Float.parseFloat(cfgVal[1].trim())); cb.lineTo(Float.parseFloat(cfgVal[2].trim()), Float.parseFloat(cfgVal[3].trim())); // stroke the lines cb.stroke(); // write text directly } else if (tempName.toString().startsWith("__")) { cb.beginText(); cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim())); cb.showTextAligned( (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER)), (cfgVal.length >= 7 ? (cfgVal[6].trim()) : props.getProperty(tempName.toString(), "")), Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0); cb.endText(); } else if (tempName.toString().equals("forms_promotext")) { if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) { cb.beginText(); cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim())); cb.showTextAligned( (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER)), OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"), Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0); cb.endText(); } } else { // write prop text cb.beginText(); cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim())); cb.showTextAligned( (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER)), (cfgVal.length >= 7 ? ((props.getProperty(tempName.toString(), "").equals("") ? "" : cfgVal[6].trim())) : props.getProperty(tempName.toString(), "")), Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0); cb.endText(); } } } catch (DocumentException dex) { baosPDF.reset(); throw dex; } finally { if (document != null) document.close(); if (writer != null) writer.close(); } return baosPDF; }
From source file:org.sakaiproject.evaluation.tool.reporting.EvalPDFReportBuilder.java
License:Educational Community License
public void addTitlePage(String evaltitle, String groupNames, String startDate, String endDate, String responseInformation, byte[] bannerImageBytes, String evalSystemTitle, String informationTitle) { try {/* w w w . j ava 2s .co m*/ float pagefooter = paragraphFont.getSize(); PdfContentByte cb = pdfWriter.getDirectContent(); float docMiddle = (document.right() - document.left()) / 2 + document.leftMargin(); Paragraph emptyPara = new Paragraph(" "); emptyPara.setSpacingAfter(100.0f); // Title Paragraph titlePara = new Paragraph("\n\n\n" + evaltitle, frontTitleFont); titlePara.setAlignment(Element.ALIGN_CENTER); document.add(titlePara); // Groups Paragraph groupPara = new Paragraph(groupNames, frontAuthorFont); groupPara.setSpacingBefore(25.0f); groupPara.setAlignment(Element.ALIGN_CENTER); document.add(groupPara); // Little info area? I don't know, it was on the mockup though Paragraph infoPara = new Paragraph(informationTitle, frontInfoFont); infoPara.setAlignment(Element.ALIGN_CENTER); infoPara.setSpacingBefore(90.0f); document.add(infoPara); // Started on Paragraph startedPara = new Paragraph(startDate, frontInfoFont); startedPara.setAlignment(Element.ALIGN_CENTER); startedPara.setSpacingBefore(25.0f); document.add(startedPara); // Ended on Paragraph endedPara = new Paragraph(endDate, frontInfoFont); endedPara.setAlignment(Element.ALIGN_CENTER); endedPara.setSpacingBefore(25.0f); document.add(endedPara); // Reply Rate Paragraph replyRatePara = new Paragraph(responseInformation, frontInfoFont); replyRatePara.setAlignment(Element.ALIGN_CENTER); replyRatePara.setSpacingBefore(25.0f); document.add(replyRatePara); // Logo and Tagline cb.beginText(); cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 12); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, evalSystemTitle, docMiddle, document.bottom() + 20, 0); cb.endText(); if (bannerImageBytes != null) { Image banner = Image.getInstance(bannerImageBytes); cb.addImage(banner, banner.getWidth(), 0, 0, banner.getHeight(), docMiddle - (banner.getWidth() / 2), document.bottom() + 35); } document.newPage(); responseArea = new ColumnText(cb); responseArea.setSimpleColumn(document.left(), document.top(), document.right() / 2, document.bottom() + pagefooter); responseArea.go(); } catch (DocumentException | IOException de) { throw UniversalRuntimeException.accumulate(de, "Unable to create title page"); } }
From source file:org.unitime.timetable.util.PdfEventHandler.java
License:Open Source License
/** * Print footer string on each page/*from w w w. j a v a 2 s . c o m*/ * @param writer * @param document */ public void onEndPage(PdfWriter writer, Document document) { if (getDateTime() == null) { setDateTime(new Date()); } PdfContentByte cb = writer.getDirectContent(); cb.beginText(); cb.setFontAndSize(getBaseFont(), getFontSize()); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, getDateFormat().format(getDateTime()), document.left(), 20, 0); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, String.valueOf(document.getPageNumber()), document.right(), 20, 0); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, MESSAGES.pdfCopyright(Constants.getVersion()), (document.left() + document.right()) / 2, 20, 0); cb.endText(); return; }
From source file:oscar.eform.util.EFormPDFServlet.java
License:Open Source License
private void writeContent(Properties printCfg, Properties props, Properties measurements, float height, PdfContentByte cb) throws Exception { for (Enumeration e = printCfg.propertyNames(); e.hasMoreElements();) { StringBuilder temp = new StringBuilder(e.nextElement().toString()); String[] cfgVal = printCfg.getProperty(temp.toString()).split(" *, *"); String[] fontType = null; int fontFlags = 0; if (cfgVal[4].indexOf(";") > -1) { fontType = cfgVal[4].split(";"); if (fontType[1].trim().equals("italic")) fontFlags = Font.ITALIC; else if (fontType[1].trim().equals("bold")) fontFlags = Font.BOLD; else if (fontType[1].trim().equals("bolditalic")) fontFlags = Font.BOLDITALIC; else//w w w. ja v a2 s .c o m fontFlags = Font.NORMAL; } else { fontFlags = Font.NORMAL; fontType = new String[] { cfgVal[4].trim() }; } String encoding = null; if (fontType[0].trim().equals("BaseFont.HELVETICA")) { fontType[0] = BaseFont.HELVETICA; encoding = BaseFont.CP1252; //latin1 encoding } else if (fontType[0].trim().equals("BaseFont.HELVETICA_OBLIQUE")) { fontType[0] = BaseFont.HELVETICA_OBLIQUE; encoding = BaseFont.CP1252; } else if (fontType[0].trim().equals("BaseFont.ZAPFDINGBATS")) { fontType[0] = BaseFont.ZAPFDINGBATS; encoding = BaseFont.ZAPFDINGBATS; } else { fontType[0] = BaseFont.COURIER; encoding = BaseFont.CP1252; } BaseFont bf = BaseFont.createFont(fontType[0], encoding, BaseFont.NOT_EMBEDDED); String propValue = props.getProperty(temp.toString()); //if not in regular config then check measurements if (propValue == null) { propValue = measurements.getProperty(temp.toString(), ""); } ColumnText ct = new ColumnText(cb); // write in a rectangle area if (cfgVal.length >= 9) { Font font = new Font(bf, Integer.parseInt(cfgVal[5].trim()), fontFlags); ct.setSimpleColumn(Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), Integer.parseInt(cfgVal[7].trim()), (height - Integer.parseInt(cfgVal[8].trim())), Integer.parseInt(cfgVal[9].trim()), (cfgVal[0].trim().equals("left") ? Element.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? Element.ALIGN_RIGHT : Element.ALIGN_CENTER))); ct.setText(new Phrase(12, propValue, font)); ct.go(); continue; } // draw line directly if (temp.toString().startsWith("__$line")) { cb.setRGBColorStrokeF(0f, 0f, 0f); cb.setLineWidth(Float.parseFloat(cfgVal[4].trim())); cb.moveTo(Float.parseFloat(cfgVal[0].trim()), Float.parseFloat(cfgVal[1].trim())); cb.lineTo(Float.parseFloat(cfgVal[2].trim()), Float.parseFloat(cfgVal[3].trim())); cb.stroke(); } else if (temp.toString().startsWith("__")) { cb.beginText(); cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim())); cb.showTextAligned( (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER)), (cfgVal.length >= 7 ? (cfgVal[6].trim()) : propValue), Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0); cb.endText(); } else { // write prop text cb.beginText(); cb.setFontAndSize(bf, Integer.parseInt(cfgVal[5].trim())); cb.showTextAligned( (cfgVal[0].trim().equals("left") ? PdfContentByte.ALIGN_LEFT : (cfgVal[0].trim().equals("right") ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER)), (cfgVal.length >= 7 ? ((propValue.equals("") ? "" : cfgVal[6].trim())) : propValue), Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0); cb.endText(); } } }
From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.EctConsultationFormRequestPrintPdf.java
License:Open Source License
private void addFooter() throws DocumentException, IOException { cb.beginText();// www. j a va2s . c o m cb.setFontAndSize(bf, FONTSIZE); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "-" + PAGENUM + "-", width / 2, 30, 0); cb.endText(); // add promotext if it is enabled if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) { cb.beginText(); cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 6); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"), width / 2, 19, 0); cb.endText(); } }