Example usage for com.lowagie.text.pdf PdfContentByte setLineWidth

List of usage examples for com.lowagie.text.pdf PdfContentByte setLineWidth

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfContentByte setLineWidth.

Prototype


public void setLineWidth(float w) 

Source Link

Document

Changes the line width.

Usage

From source file:net.sf.jasperreports.engine.export.JRPdfExporter.java

License:LGPL

/**
 *
 *//*from w w  w  .j a v a  2  s  .  c o m*/
private static void preparePen(PdfContentByte pdfContentByte, JRPen pen, int lineCap) {
    float lineWidth = pen.getLineWidth().floatValue();

    if (lineWidth <= 0) {
        return;
    }

    pdfContentByte.setLineWidth(lineWidth);
    pdfContentByte.setLineCap(lineCap);

    Color color = pen.getLineColor();
    pdfContentByte.setRGBColorStroke(color.getRed(), color.getGreen(), color.getBlue());

    switch (pen.getLineStyle().byteValue()) {
    case JRPen.LINE_STYLE_DOUBLE: {
        pdfContentByte.setLineWidth(lineWidth / 3);
        pdfContentByte.setLineDash(0f);
        break;
    }
    case JRPen.LINE_STYLE_DOTTED: {
        switch (lineCap) {
        case PdfContentByte.LINE_CAP_BUTT: {
            pdfContentByte.setLineDash(lineWidth, lineWidth, 0f);
            break;
        }
        case PdfContentByte.LINE_CAP_PROJECTING_SQUARE: {
            pdfContentByte.setLineDash(0, 2 * lineWidth, 0f);
            break;
        }
        }
        break;
    }
    case JRPen.LINE_STYLE_DASHED: {
        switch (lineCap) {
        case PdfContentByte.LINE_CAP_BUTT: {
            pdfContentByte.setLineDash(5 * lineWidth, 3 * lineWidth, 0f);
            break;
        }
        case PdfContentByte.LINE_CAP_PROJECTING_SQUARE: {
            pdfContentByte.setLineDash(4 * lineWidth, 4 * lineWidth, 0f);
            break;
        }
        }
        break;
    }
    case JRPen.LINE_STYLE_SOLID:
    default: {
        pdfContentByte.setLineDash(0f);
        break;
    }
    }
}

From source file:net.sf.jasperreports.engine.export.PdfGlyphGraphics2D.java

License:Open Source License

@Override
public void drawGlyphVector(GlyphVector glyphVector, float x, float y) {
    Font awtFont = glyphVector.getFont();
    Map<Attribute, Object> fontAttrs = new HashMap<Attribute, Object>();
    Map<TextAttribute, ?> awtFontAttributes = awtFont.getAttributes();
    fontAttrs.putAll(awtFontAttributes);

    //the following relies on FontInfo.getFontInfo matching the face/font name
    com.lowagie.text.Font currentFont = pdfExporter.getFont(fontAttrs, locale, false);
    boolean bold = (currentFont.getStyle() & com.lowagie.text.Font.BOLD) != 0;
    boolean italic = (currentFont.getStyle() & com.lowagie.text.Font.ITALIC) != 0;

    PdfContentByte text = pdfContentByte.getDuplicate();
    text.beginText();/* w w  w.  j av a2 s .c  o m*/

    float[] originalCoords = new float[] { x, y };
    float[] transformedCoors = new float[2];
    getTransform().transform(originalCoords, 0, transformedCoors, 0, 1);
    text.setTextMatrix(1, 0, italic ? ITALIC_ANGLE : 0f, 1, transformedCoors[0],
            pdfExporter.getCurrentPageFormat().getPageHeight() - transformedCoors[1]);

    double scaleX = awtFont.getTransform().getScaleX();
    double scaleY = awtFont.getTransform().getScaleY();
    double minScale = Math.min(scaleX, scaleY);
    text.setFontAndSize(currentFont.getBaseFont(), (float) (minScale * awtFont.getSize2D()));

    if (bold) {
        text.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
        text.setLineWidth(currentFont.getSize() * BOLD_STRIKE_FACTOR);
        text.setColorStroke(getColor());
    }

    text.setColorFill(getColor());
    //FIXME find a way to determine the characters that correspond to this glyph vector
    // so that we can map the font glyphs that do not directly map to a character
    text.showText(glyphVector);
    text.resetRGBColorFill();

    if (bold) {
        text.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
        text.setLineWidth(1f);
        text.resetRGBColorStroke();
    }

    text.endText();
    pdfContentByte.add(text);
}

From source file:org.eclipse.birt.report.engine.emitter.pdf.PDFPage.java

License:Open Source License

/**
 * Draws a line with the line-style specified in advance from the start
 * position to the end position with the given linewidth, color, and style
 * at the given pdf layer. If the line-style is NOT set before invoking this
 * method, "solid" will be used as the default line-style.
 *
 * @param startX//from www . j a  v a 2s  . c o m
 *            the start X coordinate of the line
 * @param startY
 *            the start Y coordinate of the line
 * @param endX
 *            the end X coordinate of the line
 * @param endY
 *            the end Y coordinate of the line
 * @param width
 *            the lineWidth
 * @param color
 *            the color of the line
 * @param contentByte
 *            the given pdf layer
 */
private void drawRawLine(float startX, float startY, float endX, float endY, float width, Color color,
        PdfContentByte contentByte) {
    startY = transformY(startY);
    endY = transformY(endY);
    contentByte.concatCTM(1, 0, 0, 1, startX, startY);

    contentByte.moveTo(0, 0);
    contentByte.lineTo(endX - startX, endY - startY);

    contentByte.setLineWidth(width);
    contentByte.setColorStroke(color);
    contentByte.stroke();
}

From source file:org.eclipse.birt.report.engine.emitter.pdf.PDFPage.java

License:Open Source License

private void simulateBold(PdfContentByte cb, int fontWeight) {
    cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
    if (fontWeightLineWidthMap.containsKey(fontWeight)) {
        cb.setLineWidth(fontWeightLineWidthMap.get(fontWeight));
    } else {//w w w .j  a  va2s  .c o m
        cb.setLineWidth(0.225f);
    }
    cb.setTextMatrix(0, 0);
}

From source file:org.jaffa.modules.printing.services.FormPrintEngineIText.java

License:Open Source License

/**
 * This will fill in the page with data,
 * m_currentPageData contains the details of the current page being printed
 * @throws FormPrintException Thrown if there is any form processing problems
 *///from ww  w.j  a va  2  s.co m
protected void fillPageFields() throws FormPrintException {
    log.debug("fillPageFields: Page=" + getCurrentPage());

    try {
        PdfContentByte cb = m_writer.getDirectContent();
        PageDetailsExtended page = (PageDetailsExtended) getCurrentPageData();

        //                // Test code to throw a barcode on the page...
        //                Barcode39 code39 = new Barcode39();
        //                code39.setCode("CODE39-1234567890");
        //                code39.setStartStopText(false);
        //                code39.setSize(0);
        //                Image image39 = code39.createImageWithBarcode(cb, null, null);
        //                com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(2);
        //                table.setWidthPercentage(100);
        //                table.getDefaultCell().setBorder(com.lowagie.text.Rectangle.NO_BORDER);
        //                table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        //                table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
        //                table.getDefaultCell().setFixedHeight(70);
        //                table.addCell("CODE 39");
        //                table.addCell(new Phrase(new Chunk(image39, 0, 0)));
        //                m_generatedDoc.add(table);
        //                //--------------------------------------------------

        // Loop through each field to be inserted
        for (Iterator i = page.fieldList.iterator(); i.hasNext();) {
            String fieldname = (String) i.next();

            // Get the properties for displaying this field
            FieldProperties props = (FieldProperties) page.fieldProperties.get(fieldname);

            // Get the data to display
            FormPrintEngine.DomValue data = new FormPrintEngine.DomValue(fieldname, props.sampleData);

            // Caluclate Clipping Region
            float x1 = Math.min(props.x1, props.x2);
            float x2 = Math.max(props.x1, props.x2);
            float y1 = Math.min(props.y1, props.y2);
            float y2 = Math.max(props.y1, props.y2);
            float w = Math.abs(props.x1 - props.x2) + 1;
            float h = Math.abs(props.y1 - props.y2) + 1;

            if (log.isDebugEnabled())
                log.debug("Print Field " + fieldname + "=" + data.getObject() + " @ [(" + x1 + "," + y1 + ")->("
                        + x2 + "," + y2 + ")]");

            // Default the font if not specified
            String font = BaseFont.HELVETICA;
            if (props.fontFace != null)
                font = props.fontFace;

            // Handle Barcodes diffently withing iText, don't just use fonts
            if (font.startsWith("Barcode")) {
                String bcClassName = "com.lowagie.text.pdf." + font;
                Object bcode = null;
                String dataStr = data.getValue();
                if (dataStr != null) {
                    log.debug("Barcode Data String = " + dataStr);
                    // Try and create the correct Barcode Object
                    try {
                        Class bcClass = Class.forName(bcClassName);
                        bcode = bcClass.newInstance();
                    } catch (Exception e) {
                        String err = "Can't Create Barcode Object for barcode type '" + font + "' on field "
                                + fieldname;
                        log.error(err, e);
                    }

                    // Only continue if the barcode object was created
                    if (bcode != null) {

                        // Generate and Print barcode, based on common interface
                        if (bcode instanceof Barcode) {
                            Barcode b = (Barcode) bcode;
                            // Set some default output a barcode
                            b.setCode(dataStr);
                            if (props.fontSize <= 0) {
                                // Hide text if font size is 0, and make the barcode height the size of the box
                                b.setBarHeight(h);
                                b.setFont(null);
                            } else {
                                b.setSize(props.fontSize); // size of text under barcode
                                b.setBarHeight(h - props.fontSize - 5); // Adjust Bar Height to allow for font size
                            }
                            b.setN(2); // Wide Bars

                            // Set custom parameters
                            setBarcodeParams(fieldname, bcode, props.style);

                            // Print out barcode
                            Image image = ((Barcode) bcode).createImageWithBarcode(cb, null, null);
                            printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);

                        } else

                        // Print PDF417 barcode, not based on common interface
                        if (bcode instanceof BarcodePDF417) {
                            BarcodePDF417 b = (BarcodePDF417) bcode;
                            // Set some default output a barcode
                            b.setText(dataStr);
                            b.setErrorLevel(5);
                            // Set custom parameters
                            setBarcodeParams(fieldname, bcode, props.style);
                            log.debug("PDF417 Settings\n" + "BitColumns=" + b.getBitColumns() + "\n"
                                    + "CodeColumns=" + b.getCodeColumns() + "\n" + "CodeRows=" + b.getCodeRows()
                                    + "\n" + "ErrorLevel=" + b.getErrorLevel() + "\n" + "YHeight="
                                    + b.getYHeight() + "\n" + "AspectRatio=" + b.getAspectRatio() + "\n"
                                    + "Options=" + b.getOptions() + "\n" + "LenCodewords="
                                    + b.getLenCodewords());

                            // Print out barcode
                            //image = b.getImage();
                            printImage(b.getImage(), cb, x1, y1, x2, y2, props.align, props.fitMethod,
                                    props.rotate);

                        } else {
                            // Error, unknown barcode
                            String err = "Error, No print handler for barcode object "
                                    + bcode.getClass().getName();
                            log.error(err);
                            //throw new EngineProcessingException(err);
                        }
                    }
                } else
                    log.debug("SKIPPED BARCODE : No data for " + fieldname);

                // Handle Images differently within iText, native support for JFreeChart
            } else if ("image".equalsIgnoreCase(font)) {
                try {
                    java.awt.Image image = data.getDomImage();
                    // Add an image to the page
                    if (image != null) {
                        if (fieldname.startsWith("watermark")) {
                            // Add an image-based watermark to the under content layer
                            PdfContentByte contentUnder = m_writer.getDirectContentUnder();
                            if (props.opacity != 1f) {
                                PdfGState gs = new PdfGState();
                                gs.setFillOpacity(props.opacity);
                                contentUnder.setGState(gs);
                            }
                            printImage(image, contentUnder, x1, y1, x2, y2, props.align, props.fitMethod,
                                    props.rotate);
                        } else {
                            // Add an image to main page layer
                            printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate);
                        }
                    }
                } catch (IOException e) {
                    // Add Error on page.
                    Phrase text = new Phrase("Image Error", FontFactory
                            .getFont(FontFactory.HELVETICA_BOLDOBLIQUE, 8f, 0, ColorHelper.getColor("red")));
                    ColumnText ct = new ColumnText(cb);
                    ct.setSimpleColumn(text, x1, y1, x2, y2, 8f, Element.ALIGN_LEFT);
                }
            } else if (fieldname.startsWith("watermark")) {
                // Add a text-based watermark
                String text = data.getValue();
                PdfContentByte contentUnder = m_writer.getDirectContentUnder();
                if (props.opacity != 1f) {
                    PdfGState gs = new PdfGState();
                    gs.setFillOpacity(props.opacity);
                    contentUnder.setGState(gs);
                }
                // The text aligns (left, center, right) on the pivot point.
                // Default to align left.
                float pivotX = x1;
                float pivotY = y1;
                if (Element.ALIGN_CENTER == props.align) {
                    pivotX = (x1 / 2) + (x2 / 2);
                    pivotY = y1;
                } else if (Element.ALIGN_RIGHT == props.align) {
                    pivotX = x2;
                    pivotY = y1;
                }
                Phrase watermark = new Phrase(text, FontFactory.getFont(props.fontFace, props.fontSize,
                        decodeFontStyle(props.style), ColorHelper.getColor(defaultWatermarkColor)));
                ColumnText.showTextAligned(contentUnder, props.align, watermark, pivotX, pivotY, props.rotate);
            } else {
                // Handle printing of basic Text
                float lineHeight = props.fontSize;
                String str = data.getValue();
                if (str != null) {
                    // Add a bounded column to add text to.
                    Phrase text = new Phrase(str, FontFactory.getFont(props.fontFace, props.fontSize,
                            decodeFontStyle(props.style), ColorHelper.getColor(props.color)));
                    ColumnText ct = new ColumnText(cb);
                    if (props.fitMethod == FIT_METHOD_CLIP)
                        // set up column with height/width restrictions
                        ct.setSimpleColumn(text, x1, y1, x2, y2, lineHeight, props.align);
                    else
                        // set up column without (i.e. large) height/width restrictions
                        ct.setSimpleColumn(text, x1, y1, 1000, 0, lineHeight, props.align);
                    ct.go();
                }
            }

            // Draw outline boxes arround fields
            if (isTemplateMode()) {
                cb.setLineWidth(0.5f);
                cb.setLineDash(4f, 2f);
                cb.setColorStroke(new Color(0xA0, 0xA0, 0xA0));
                cb.moveTo(x1, y1);
                cb.lineTo(x1, y2);
                cb.lineTo(x2, y2);
                cb.lineTo(x2, y1);
                cb.lineTo(x1, y1);
                cb.stroke();
            }
        } // end for-loop
    } catch (DocumentException e) {
        String err = "Error printing data - " + e.getMessage();
        log.error(err, e);
        throw new EngineProcessingException(err);
        //        } catch (IOException e) {
        //            String err = "Error printing data - " + e.getMessage();
        //            log.error(err ,e);
        //            throw new EngineProcessingException(err);
    }

}

From source file:org.mapfish.print.map.MapChunkDrawer.java

License:Open Source License

/**
 * Used by overview maps to draw the extent of the real map.
 *//*from   ww w  .  j a v a  2 s. com*/
private void drawMapExtent(PdfContentByte dc, Transformer mainTransformer) {
    dc.saveState();
    try {
        //in "degrees" unit, there seems to have rounding errors if I use the
        //PDF transform facility. Therefore, I do the transform by hand :-(
        transformer.setRotation(mainTransformer.getRotation());
        dc.transform(transformer.getGeoTransform(true));
        transformer.setRotation(0);

        dc.setLineWidth(1 * transformer.getGeoW() / transformer.getPaperW());
        dc.setColorStroke(new Color(255, 0, 0));
        dc.rectangle(mainTransformer.getMinGeoX(), mainTransformer.getMinGeoY(), mainTransformer.getGeoW(),
                mainTransformer.getGeoH());
        dc.stroke();

        if (mainTransformer.getRotation() != 0.0) {
            //draw a little arrow
            dc.setLineWidth(0.5F * transformer.getGeoW() / transformer.getPaperW());
            dc.moveTo((3 * mainTransformer.getMinGeoX() + mainTransformer.getMaxGeoX()) / 4,
                    mainTransformer.getMinGeoY());
            dc.lineTo((mainTransformer.getMinGeoX() + mainTransformer.getMaxGeoX()) / 2,
                    (mainTransformer.getMinGeoY() * 2 + mainTransformer.getMaxGeoY()) / 3);
            dc.lineTo((mainTransformer.getMinGeoX() + 3 * mainTransformer.getMaxGeoX()) / 4,
                    mainTransformer.getMinGeoY());
            dc.stroke();
        }
    } finally {
        dc.restoreState();
    }
}

From source file:org.mapfish.print.map.renderers.vector.LineStringRenderer.java

License:Open Source License

protected static void applyStyle(RenderingContext context, PdfContentByte dc, PJsonObject style,
        PdfGState state) {//from ww  w  .j  a v  a  2  s . com
    if (style == null)
        return;
    if (style.optString("strokeColor") != null) {
        dc.setColorStroke(ColorWrapper.convertColor(style.getString("strokeColor")));
    }
    if (style.optString("strokeOpacity") != null) {
        state.setStrokeOpacity(style.getFloat("strokeOpacity"));
    }
    final float width = style.optFloat("strokeWidth", 1) * context.getStyleFactor();
    dc.setLineWidth(width);
    final String linecap = style.optString("strokeLinecap");
    if (linecap != null) {
        if (linecap.equalsIgnoreCase("butt")) {
            dc.setLineCap(PdfContentByte.LINE_CAP_BUTT);
        } else if (linecap.equalsIgnoreCase("round")) {
            dc.setLineCap(PdfContentByte.LINE_CAP_ROUND);
        } else if (linecap.equalsIgnoreCase("square")) {
            dc.setLineCap(PdfContentByte.LINE_CAP_PROJECTING_SQUARE);
        } else {
            throw new InvalidValueException("strokeLinecap", linecap);
        }
    }
    final String dashStyle = style.optString("strokeDashstyle");
    if (dashStyle != null) {
        if (dashStyle.equalsIgnoreCase("dot")) {
            final float[] def = new float[] { 0.1f, 2 * width };
            dc.setLineDash(def, 0);
        } else if (dashStyle.equalsIgnoreCase("dash")) {
            final float[] def = new float[] { 2 * width, 2 * width };
            dc.setLineDash(def, 0);
        } else if (dashStyle.equalsIgnoreCase("dashdot")) {
            final float[] def = new float[] { 3 * width, 2 * width, 0.1f, 2 * width };
            dc.setLineDash(def, 0);
        } else if (dashStyle.equalsIgnoreCase("longdash")) {
            final float[] def = new float[] { 4 * width, 2 * width };
            dc.setLineDash(def, 0);
        } else if (dashStyle.equalsIgnoreCase("longdashdot")) {
            final float[] def = new float[] { 5 * width, 2 * width, 0.1f, 2 * width };
            dc.setLineDash(def, 0);
        } else if (dashStyle.equalsIgnoreCase("solid")) {

        } else {
            throw new InvalidValueException("strokeDashstyle", dashStyle);
        }
    }
}

From source file:org.mapfish.print.scalebar.ScalebarDrawer.java

License:Open Source License

public void renderImpl(Rectangle rectangle, PdfContentByte dc) {
    dc.saveState();//from   www  . j ava2  s .  c o m
    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.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 a v a  2 s. 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.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfLogicalPageDrawable.java

License:Open Source License

protected void drawText(final RenderableText renderableText, final long contentX2) {
    if (renderableText.getLength() == 0) {
        return;/*from  w  ww  .  j a v  a  2 s.  c o m*/
    }

    final long posX = renderableText.getX();
    final long posY = renderableText.getY();
    final float x1 = (float) (StrictGeomUtility.toExternalValue(posX));

    final PdfContentByte cb;
    PdfTextSpec textSpec = (PdfTextSpec) getTextSpec();
    if (textSpec == null) {
        final StyleSheet layoutContext = renderableText.getStyleSheet();

        // The code below may be weird, but at least it is predictable weird.
        final String fontName = getMetaData()
                .getNormalizedFontFamilyName((String) layoutContext.getStyleProperty(TextStyleKeys.FONT));
        final String encoding = (String) layoutContext.getStyleProperty(TextStyleKeys.FONTENCODING);
        final float fontSize = (float) layoutContext.getDoubleStyleProperty(TextStyleKeys.FONTSIZE, 10);

        final boolean embed = globalEmbed || layoutContext.getBooleanStyleProperty(TextStyleKeys.EMBEDDED_FONT);
        final boolean bold = layoutContext.getBooleanStyleProperty(TextStyleKeys.BOLD);
        final boolean italics = layoutContext.getBooleanStyleProperty(TextStyleKeys.ITALIC);

        final BaseFontFontMetrics fontMetrics = getMetaData().getBaseFontFontMetrics(fontName, fontSize, bold,
                italics, encoding, embed, false);

        final PdfGraphics2D g2 = (PdfGraphics2D) getGraphics();
        final Color cssColor = (Color) layoutContext.getStyleProperty(ElementStyleKeys.PAINT);
        g2.setPaint(cssColor);
        g2.setFillPaint();
        g2.setStrokePaint();
        // final float translateY = (float) affineTransform.getTranslateY();

        cb = g2.getRawContentByte();

        textSpec = new PdfTextSpec(layoutContext, getMetaData(), g2, fontMetrics, cb);
        setTextSpec(textSpec);

        cb.beginText();
        cb.setFontAndSize(fontMetrics.getBaseFont(), fontSize);
    } else {
        cb = textSpec.getContentByte();
    }

    final BaseFontFontMetrics baseFontRecord = textSpec.getFontMetrics();
    final BaseFont baseFont = baseFontRecord.getBaseFont();
    final float ascent;
    if (legacyLineHeightCalc) {
        final float awtAscent = baseFont.getFontDescriptor(BaseFont.AWT_ASCENT, textSpec.getFontSize());
        final float awtLeading = baseFont.getFontDescriptor(BaseFont.AWT_LEADING, textSpec.getFontSize());
        ascent = awtAscent + awtLeading;
    } else {
        ascent = baseFont.getFontDescriptor(BaseFont.BBOXURY, textSpec.getFontSize());
    }
    final float y2 = (float) (StrictGeomUtility.toExternalValue(posY) + ascent);
    final float y = globalHeight - y2;

    final AffineTransform affineTransform = textSpec.getGraphics().getTransform();
    final float translateX = (float) affineTransform.getTranslateX();

    final FontNativeContext nativeContext = baseFontRecord.getNativeContext();
    if (baseFontRecord.isTrueTypeFont() && textSpec.isBold() && nativeContext.isNativeBold() == false) {
        final float strokeWidth = textSpec.getFontSize() / 30.0f; // right from iText ...
        if (strokeWidth == 1) {
            cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
        } else {
            cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
            cb.setLineWidth(strokeWidth);
        }
    } else {
        cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
    }

    // if the font does not declare to be italics already, emulate it ..
    if (baseFontRecord.isTrueTypeFont() && textSpec.isItalics() && nativeContext.isNativeItalics() == false) {
        final float italicAngle = baseFont.getFontDescriptor(BaseFont.ITALICANGLE, textSpec.getFontSize());
        if (italicAngle == 0) {
            // italics requested, but the font itself does not supply italics gylphs.
            cb.setTextMatrix(1, 0, PdfLogicalPageDrawable.ITALIC_ANGLE, 1, x1 + translateX, y);
        } else {
            cb.setTextMatrix(x1 + translateX, y);
        }
    } else {
        cb.setTextMatrix(x1 + translateX, y);
    }

    final OutputProcessorMetaData metaData = getMetaData();
    final GlyphList gs = renderableText.getGlyphs();
    final int offset = renderableText.getOffset();

    final CodePointBuffer codePointBuffer = getCodePointBuffer();
    if (metaData.isFeatureSupported(OutputProcessorFeature.FAST_FONTRENDERING)
            && isNormalTextSpacing(renderableText)) {
        final int maxLength = renderableText.computeMaximumTextSize(contentX2);
        final String text = gs.getText(renderableText.getOffset(), maxLength, codePointBuffer);

        cb.showText(text);
    } else {
        final PdfTextArray textArray = new PdfTextArray();
        final StringBuilder buffer = new StringBuilder(gs.getSize());
        final int maxPos = offset + renderableText.computeMaximumTextSize(contentX2);

        for (int i = offset; i < maxPos; i++) {
            final Glyph g = gs.getGlyph(i);
            final Spacing spacing = g.getSpacing();
            if (i != offset) {
                final float optimum = (float) StrictGeomUtility.toFontMetricsValue(spacing.getMinimum());
                if (optimum != 0) {
                    textArray.add(buffer.toString());
                    textArray.add(-optimum / textSpec.getFontSize());
                    buffer.setLength(0);
                }
            }

            final String text = gs.getGlyphAsString(i, codePointBuffer);
            buffer.append(text);
        }
        if (buffer.length() > 0) {
            textArray.add(buffer.toString());
        }
        cb.showText(textArray);
    }
}