Example usage for com.lowagie.text.pdf BaseFont NOT_EMBEDDED

List of usage examples for com.lowagie.text.pdf BaseFont NOT_EMBEDDED

Introduction

In this page you can find the example usage for com.lowagie.text.pdf BaseFont NOT_EMBEDDED.

Prototype

boolean NOT_EMBEDDED

To view the source code for com.lowagie.text.pdf BaseFont NOT_EMBEDDED.

Click Source Link

Document

if the font doesn't have to be embedded

Usage

From source file:org.onehippo.forge.hst.pdf.renderer.HtmlPDFRenderer.java

License:Open Source License

public void renderHtmlToPDF(Reader htmlInput, boolean convertToXHTML, OutputStream pdfOutput,
        String documentURL, String externalLinkBaseURL) throws IOException {
    Reader xhtmlReader = null;//from   w  w  w.j  av a  2 s. c om

    try {
        if (convertToXHTML) {
            xhtmlReader = convertHtmlReaderToXhtmlReader(htmlInput);
        } else {
            xhtmlReader = htmlInput;
        }

        ITextRenderer renderer = new ITextRenderer();

        if (fontPaths != null && fontPaths.length > 0) {
            ITextFontResolver fontResolver = renderer.getFontResolver();

            for (String fontPath : fontPaths) {
                fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }
        }

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(new InputSource(xhtmlReader));

        if (removeExistingCssLinks) {
            removeExistingCssLinks(document);
        }

        if (cssURIs != null && cssURIs.length > 0) {
            appendCssLinkElementToXhtmlDocument(document, cssURIs);
        }

        if (useFullyQualifiedLinks && !StringUtils.isEmpty(externalLinkBaseURL)) {
            replaceLinksByFullyQualifiedURLs(document, "a", externalLinkBaseURL, documentURL);
            replaceLinksByFullyQualifiedURLs(document, "A", externalLinkBaseURL, documentURL);
        }

        if (userAgentCallback != null) {
            renderer.getSharedContext().setUserAgentCallback(userAgentCallback);
        }

        renderer.setDocument(document, documentURL);
        renderer.layout();
        renderer.createPDF(pdfOutput);
    } catch (ParserConfigurationException e) {
        log.error("Parse configuration exception.", e);
    } catch (SAXException e) {
        log.error("XML parsing exception.", e);
    } catch (DocumentException e) {
        log.error("pdf generation exception.", e);
    } finally {
        if (xhtmlReader != htmlInput) {
            IOUtils.closeQuietly(xhtmlReader);
        }
    }
}

From source file:org.opentestsystem.delivery.testreg.rest.view.PdfReportPageEventHelper.java

License:Open Source License

public PdfReportPageEventHelper(final PdfWriter writer) {
    template = writer.getDirectContent().createTemplate(100, 100);
    template.setBoundingBox(new Rectangle(-20, -20, 100, 100));
    try {/*from  w  ww  .  j av  a 2 s.c  om*/
        helv = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1257, BaseFont.NOT_EMBEDDED);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

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  a  va  2 s . co  m
        // 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 w w.  j  a va 2  s  .c om

            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.print.OscarChartPrinter.java

License:Open Source License

public OscarChartPrinter(HttpServletRequest request, OutputStream os) throws DocumentException, IOException {
    this.request = request;
    this.os = os;

    document = new Document();
    writer = PdfWriter.getInstance(document, os);
    writer.setPageEvent(new EndPage());
    document.setPageSize(PageSize.LETTER);
    document.open();/*from  w ww . ja v  a  2 s . c om*/
    //Create the font we are going to print to
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    font = new Font(bf, FONTSIZE, Font.NORMAL);
    boldFont = new Font(bf, FONTSIZE, Font.BOLD);
}

From source file:org.oscarehr.casemgmt.service.CaseManagementPrintPdf.java

License:Open Source License

public void printDocHeaderFooter() throws IOException, DocumentException {
    //Create the document we are going to write to
    document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, os);
    writer.setPageEvent(new EndPage());
    document.setPageSize(PageSize.LETTER);
    document.open();/*from w ww .j  a va 2  s  . co  m*/

    //Create the font we are going to print to
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    font = new Font(bf, FONTSIZE, Font.NORMAL);

    String title = "", gender = "", dob = "", age = "", mrp = "";
    if (this.demoDtl != null) {
        //set up document title and header
        ResourceBundle propResource = ResourceBundle.getBundle("oscarResources");
        title = propResource.getString("oscarEncounter.pdfPrint.title") + " " + (String) demoDtl.get("demoName")
                + "\n";
        gender = propResource.getString("oscarEncounter.pdfPrint.gender") + " "
                + (String) demoDtl.get("demoSex") + "\n";
        dob = propResource.getString("oscarEncounter.pdfPrint.dob") + " " + (String) demoDtl.get("demoDOB")
                + "\n";
        age = propResource.getString("oscarEncounter.pdfPrint.age") + " " + (String) demoDtl.get("demoAge")
                + "\n";
        mrp = propResource.getString("oscarEncounter.pdfPrint.mrp") + " " + (String) demoDtl.get("mrp") + "\n";
    } else {
        //set up document title and header
        ResourceBundle propResource = ResourceBundle.getBundle("oscarResources");
        title = propResource.getString("oscarEncounter.pdfPrint.title") + " "
                + (String) request.getAttribute("demoName") + "\n";
        gender = propResource.getString("oscarEncounter.pdfPrint.gender") + " "
                + (String) request.getAttribute("demoSex") + "\n";
        dob = propResource.getString("oscarEncounter.pdfPrint.dob") + " "
                + (String) request.getAttribute("demoDOB") + "\n";
        age = propResource.getString("oscarEncounter.pdfPrint.age") + " "
                + (String) request.getAttribute("demoAge") + "\n";
        mrp = propResource.getString("oscarEncounter.pdfPrint.mrp") + " " + (String) request.getAttribute("mrp")
                + "\n";
    }

    String[] info = new String[] { title, gender, dob, age, mrp };

    ClinicData clinicData = new ClinicData();
    clinicData.refreshClinicData();
    String[] clinic = new String[] { clinicData.getClinicName(), clinicData.getClinicAddress(),
            clinicData.getClinicCity() + ", " + clinicData.getClinicProvince(), clinicData.getClinicPostal(),
            clinicData.getClinicPhone(), "Fax: " + clinicData.getClinicFax() };

    //Header will be printed at top of every page beginning with p2
    Phrase headerPhrase = new Phrase(LEADING, title, font);
    HeaderFooter header = new HeaderFooter(headerPhrase, false);
    header.setAlignment(HeaderFooter.ALIGN_CENTER);
    document.setHeader(header);

    //Write title with top and bottom borders on p1
    cb = writer.getDirectContent();
    cb.setColorStroke(new Color(0, 0, 0));
    cb.setLineWidth(0.5f);

    cb.moveTo(document.left(), document.top());
    cb.lineTo(document.right(), document.top());
    cb.stroke();
    //cb.setFontAndSize(bf, FONTSIZE);

    upperYcoord = document.top() - (font.getCalculatedLeading(LINESPACING) * 2f);

    ColumnText ct = new ColumnText(cb);
    Paragraph p = new Paragraph();
    p.setAlignment(Paragraph.ALIGN_LEFT);
    Phrase phrase = new Phrase();
    Phrase dummy = new Phrase();
    for (int idx = 0; idx < clinic.length; ++idx) {
        phrase.add(clinic[idx] + "\n");
        dummy.add("\n");
        upperYcoord -= phrase.getLeading();
    }

    dummy.add("\n");
    ct.setSimpleColumn(document.left(), upperYcoord, document.right() / 2f, document.top());
    ct.addElement(phrase);
    ct.go();

    p.add(dummy);
    document.add(p);

    //add patient info
    phrase = new Phrase();
    p = new Paragraph();
    p.setAlignment(Paragraph.ALIGN_RIGHT);
    for (int idx = 0; idx < info.length; ++idx) {
        phrase.add(info[idx]);
    }

    ct.setSimpleColumn(document.right() / 2f, upperYcoord, document.right(), document.top());
    p.add(phrase);
    ct.addElement(p);
    ct.go();

    cb.moveTo(document.left(), upperYcoord);
    cb.lineTo(document.right(), upperYcoord);
    cb.stroke();
    upperYcoord -= phrase.getLeading();

    if (Boolean.parseBoolean(OscarProperties.getInstance().getProperty("ICFHT_CONVERT_TO_PDF", "false"))) {
        printPersonalInfo();
    }
}

From source file:org.oscarehr.casemgmt.service.FooterSupport.java

License:Open Source License

/**
 * Creates a new instance with as the Helvetica 12pt base font. 
 *//*from ww  w  .  jav a2 s. c o  m*/
public FooterSupport() {
    super();
    setFontSize(12);
    setFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
}

From source file:org.oscarehr.common.service.PdfRecordPrinter.java

License:Open Source License

public PdfRecordPrinter(HttpServletRequest request, OutputStream os) throws DocumentException, IOException {
    this.request = request;
    this.os = os;
    formatter = new SimpleDateFormat("dd-MMM-yyyy");

    //Create the font we are going to print to
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    font = new Font(bf, FONTSIZE, Font.NORMAL);
    boldFont = new Font(bf, FONTSIZE, Font.BOLD);

    //Create the document we are going to write to
    document = new Document();
    writer = PdfWriter.getInstance(document, os);
    writer.setPageEvent(new EndPage());
    writer.setStrictImageSequence(true);

    document.setPageSize(PageSize.LETTER);

    /*/*  w ww.  j  a  v  a2 s .  co m*/
    HeaderFooter footer = new HeaderFooter(new Phrase("-",font),new Phrase("-",font));
    footer.setAlignment(HeaderFooter.ALIGN_CENTER);
    footer.setBorder(0);
            
    document.setFooter(footer);
    */
    document.open();

}

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 ww.  j  a va2s . c om

    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.pz.platypus.TypefaceMap.java

License:Open Source License

/**
 * Uses iText to extract the family name (or in case of .ttc the names) of the font family.
 *
 * @param fontFilename font file/*from  www. java  2s . co m*/
 * @param bf base font we create to get the family font name
 *
 * @return the font's family name(s) or an empty array if an error occurred.
 *
 * For explanation of .ttc handling, see:
 * http://itextdocs.lowagie.com/tutorial/fonts/getting/index.php
 *
 */
public String[] extractFamilyNames(String fontFilename, BaseFont bf) {
    String familyName[] = new String[1];

    String names[][];
    File f = new File(fontFilename);
    if (f.exists() || !f.isDirectory()) {
        try {
            if (fontFilename.toLowerCase().endsWith(".ttc")) {
                return (BaseFont.enumerateTTCNames(fontFilename));
            }

            bf = BaseFont.createFont(fontFilename, "winansi", BaseFont.NOT_EMBEDDED);
            names = bf.getFamilyFontName();
        } catch (IOException ioe) {
            gdd.logInfo("IOException loading " + fontFilename + " into font-family map");
            return (new String[0]);
        } catch (DocumentException de) {
            gdd.logInfo("Document Exception loading " + fontFilename + " into font-family map");
            return (new String[0]);
        }

        if (names != null && names[0] != null) {
            familyName[0] = names[0][3];
            return familyName;
        } else {
            return (new String[0]);
        }
    }
    return (new String[0]);
}