List of usage examples for com.lowagie.text.pdf PdfContentByte setFontAndSize
public void setFontAndSize(BaseFont bf, float size)
From source file:org.mapfish.print.map.renderers.vector.PointRenderer.java
License:Open Source License
protected void renderImpl(RenderingContext context, PdfContentByte dc, PJsonObject style, Point geometry) { PdfGState state = new PdfGState(); final Coordinate coordinate = geometry.getCoordinate(); float pointRadius = style.optFloat("pointRadius", 4.0f); final float f = context.getStyleFactor(); String graphicName = style.optString("graphicName"); float width = style.optFloat("graphicWidth", pointRadius * 2.0f); float height = style.optFloat("graphicHeight", pointRadius * 2.0f); float offsetX = style.optFloat("graphicXOffset", -width / 2.0f); float offsetY = style.optFloat("graphicYOffset", -height / 2.0f); // See Feature/Vector.js for more information about labels String label = style.optString("label"); String labelAlign = style.optString("labelAlign", "lb"); /*//from w w w .jav a 2 s .c om * Valid values for horizontal alignment: "l"=left, "c"=center, "r"=right. * Valid values for vertical alignment: "t"=top, "m"=middle, "b"=bottom. */ float labelXOffset = style.optFloat("labelXOffset", (float) 0.0); float labelYOffset = style.optFloat("labelYOffset", (float) 0.0); String fontColor = style.optString("fontColor", "#000000"); /* Supported itext fonts: COURIER, HELVETICA, TIMES_ROMAN */ String fontFamily = style.optString("fontFamily", "HELVETICA"); String fontSize = style.optString("fontSize", "12"); String fontWeight = style.optString("fontWeight", "normal"); if (style.optString("externalGraphic") != null) { float opacity = style.optFloat("graphicOpacity", style.optFloat("fillOpacity", 1.0f)); state.setFillOpacity(opacity); state.setStrokeOpacity(opacity); dc.setGState(state); try { Image image = PDFUtils.createImage(context, width * f, height * f, new URI(style.getString("externalGraphic")), 0.0f); image.setAbsolutePosition((float) coordinate.x + offsetX * f, (float) coordinate.y + offsetY * f); dc.addImage(image); } catch (BadElementException e) { context.addError(e); } catch (URISyntaxException e) { context.addError(e); } catch (DocumentException e) { context.addError(e); } } else if (graphicName != null && !graphicName.equalsIgnoreCase("circle")) { PolygonRenderer.applyStyle(context, dc, style, state); float[] symbol = SYMBOLS.get(graphicName); if (symbol == null) { throw new InvalidValueException("graphicName", graphicName); } dc.setGState(state); dc.moveTo((float) coordinate.x + symbol[0] * width * f + offsetX * f, (float) coordinate.y + symbol[1] * height * f + offsetY * f); for (int i = 2; i < symbol.length - 2; i += 2) { dc.lineTo((float) coordinate.x + symbol[i] * width * f + offsetX * f, (float) coordinate.y + symbol[i + 1] * height * f + offsetY * f); } dc.closePath(); dc.fillStroke(); } else if (label != null && label.length() > 0) { BaseFont bf = PDFUtils.getBaseFont(fontFamily, fontSize, fontWeight); float fontHeight = (float) Double.parseDouble(fontSize.toLowerCase().replaceAll("px", "")) * f; dc.setFontAndSize(bf, fontHeight); dc.setColorFill(ColorWrapper.convertColor(fontColor)); state.setFillOpacity((float) 1.0); dc.setGState(state); dc.beginText(); dc.setTextMatrix((float) coordinate.x + labelXOffset * f, (float) coordinate.y + labelYOffset * f); dc.setGState(state); dc.showTextAligned(PDFUtils.getHorizontalAlignment(labelAlign), label, (float) coordinate.x + labelXOffset * f, (float) coordinate.y + labelYOffset * f - PDFUtils.getVerticalOffset(labelAlign, fontHeight), 0); dc.endText(); } else { PolygonRenderer.applyStyle(context, dc, style, state); dc.setGState(state); dc.circle((float) coordinate.x, (float) coordinate.y, pointRadius * f); dc.fillStroke(); } }
From source file:org.mapfish.print.scalebar.ScalebarDrawer.java
License:Open Source License
public void renderImpl(Rectangle rectangle, PdfContentByte dc) { dc.saveState();/*from w w w .ja v a 2 s. c om*/ try { //sets the transformation for drawing the labels and do it final AffineTransform rotate = getRotationTransform(block.getBarDirection()); final AffineTransform labelTransform = AffineTransform.getTranslateInstance(rectangle.getLeft(), rectangle.getBottom()); labelTransform.concatenate(rotate); labelTransform.translate(leftLabelMargin, maxLabelHeight); dc.transform(labelTransform); dc.setColorStroke(block.getColorVal()); dc.setFontAndSize(pdfFont.getCalculatedBaseFont(false), pdfFont.getSize()); drawLabels(dc); dc.restoreState(); dc.saveState(); //sets the transformation for drawing the bar and do it final AffineTransform lineTransform = AffineTransform.getTranslateInstance(rectangle.getLeft(), rectangle.getBottom()); lineTransform.concatenate(rotate); lineTransform.translate(leftLabelMargin, labelDistance + maxLabelHeight); dc.transform(lineTransform); dc.setLineWidth((float) block.getLineWidth()); dc.setColorStroke(block.getColorVal()); drawBar(dc); } finally { dc.restoreState(); } }
From source file:org.meveo.admin.action.billing.BillingAccountBean.java
License:Open Source License
public void generatePDF(long invoiceId) { Invoice invoice = invoiceService.findById(invoiceId); byte[] invoicePdf = invoice.getPdf(); FacesContext context = FacesContext.getCurrentInstance(); String invoiceFilename = null; BillingRun billingRun = invoice.getBillingRun(); invoiceFilename = invoice.getInvoiceNumber() + ".pdf"; if (billingRun != null && billingRun.getStatus() != BillingRunStatusEnum.VALIDATED) { invoiceFilename = "unvalidated-invoice.pdf"; }//w ww . j a v a2 s. c o m HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); response.setContentType("application/pdf"); // fill in response.setHeader("Content-disposition", "attachment; filename=" + invoiceFilename); try { OutputStream os = response.getOutputStream(); Document document = new Document(PageSize.A4); if (billingRun != null && invoice.getBillingRun().getStatus() != BillingRunStatusEnum.VALIDATED) { // Add watemark image PdfReader reader = new PdfReader(invoicePdf); int n = reader.getNumberOfPages(); PdfStamper stamp = new PdfStamper(reader, os); PdfContentByte over = null; BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f); int i = 1; while (i <= n) { over = stamp.getOverContent(i); over.setGState(gs); over.beginText(); System.out.println("top=" + document.top() + ",bottom=" + document.bottom()); over.setTextMatrix(document.top(), document.bottom()); over.setFontAndSize(bf, 150); over.setColorFill(Color.GRAY); over.showTextAligned(Element.ALIGN_CENTER, "TEST", document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45); over.endText(); i++; } stamp.close(); } else { os.write(invoicePdf); // fill in PDF with bytes } // contentType os.flush(); os.close(); context.responseComplete(); } catch (IOException e) { log.error("failed to generate PDF ", e); } catch (DocumentException e) { log.error("error in generation PDF ", e); } }
From source file:org.opentestsystem.delivery.testreg.rest.view.PdfReportPageEventHelper.java
License:Open Source License
@Override public void onEndPage(final PdfWriter writer, final Document document) { PdfContentByte cb = writer.getDirectContent(); if (document.getPageNumber() == 1) { ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, new Phrase(""), (document.right() - document.left()) / 2 + document.leftMargin(), document.top() - 5, 0f); }/*from w w w. j a v a2s . co m*/ ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(""), document.left(), document.bottom() - 15, 0f); int pageN = writer.getPageNumber(); String text = "Page " + pageN + " of "; cb.beginText(); cb.setFontAndSize(helv, 11); cb.setTextMatrix(document.right() - document.rightMargin() - 10, document.bottom() - 15); cb.showText(text); cb.endText(); cb.addTemplate(template, document.right(), document.bottom() - 15); }
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 w w .j av a2 s .com*/ // 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.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 . jav a 2 s . c om*/ 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 .jav a 2s .c om*/ * @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
public static byte[] stamp(byte[] content) throws Exception { PdfReader reader = null;/* w ww . ja v a2s. c o m*/ ByteArrayOutputStream os = null; PdfStamper stamper = null; try { reader = new PdfReader(content); os = new ByteArrayOutputStream(content.length); stamper = new PdfStamper(reader, os); for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfContentByte over = stamper.getOverContent(i); BaseFont font = FontSettings.HELVETICA_6PT.createFont(); over.setFontAndSize(font, 10); float center = reader.getPageSize(i).getWidth() / 2.0f; // TODO Consider refactoring this into is own class printText(over, "Page " + i + " of " + reader.getNumberOfPages(), center, 35); printText(over, OscarProperties.getConfidentialityStatement(), center, 25); } // this is ugly, but there is no flush method for readers in itext.... stamper.close(); reader.close(); os.flush(); return os.toByteArray(); } finally { if (os != null) IOUtils.closeQuietly(os); } }
From source file:org.oscarehr.common.printing.PdfWriterFactory.java
License:Open Source License
public static PdfContentByte setFont(PdfContentByte pdfContentByte, FontSettings settings) { pdfContentByte.setFontAndSize(settings.createFont(), settings.getFontSize()); return pdfContentByte; }
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;/*from w w w . jav a 2 s . c o m*/ 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; }