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

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

Introduction

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

Prototype

int ALIGN_RIGHT

To view the source code for com.lowagie.text.pdf PdfContentByte ALIGN_RIGHT.

Click Source Link

Document

The alignment is right

Usage

From source file:com.estate.pdf.PageBorder.java

public void draw(Document doc, int iconNum, String pageNum, String toolName) {
    try {/*  ww  w .j a  va  2s  . c  o  m*/
        PdfContentByte cb = writer.getDirectContentUnder();
        BaseFont fontBold = BaseFont.createFont(Locations.getFontLocation() + "timesbd.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        BaseFont font = BaseFont.createFont(Locations.getFontLocation() + "times.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        Rectangle rct = new Rectangle(doc.getPageSize());
        float iconBase = (1.25f * 72); // This is the base of the icons on
        // the page
        Image icon = Image.getInstance(Locations.getImageLocation() + icons[iconNum]);
        // Image box = Image.getInstance(Locations.ImageLocation() +
        // "blueBOX.png");
        icon.scalePercent(23);
        float scale = .23f;
        float iconLeft = (icon.getWidth() / 2) * scale;
        float boxSize = (.1875f * 72);

        // Adjust the top
        rct.setTop(rct.getTop() - (.5f * 72));

        // Place the Icon
        icon.setAbsolutePosition((1.25f * 72) - iconLeft, rct.getTop() - iconBase);
        doc.add(icon);

        // Set our line color
        cb.setRGBColorStroke(0, 72, 117);

        cb.setLineWidth(.75f);

        // do the bottom line
        cb.moveTo(1.25f * 72, (.5f * 72));
        cb.lineTo(rct.getRight() - (.5f * 72), (.5f * 72));

        cb.moveTo(1.25f * 72, (.5f * 72));
        cb.lineTo(1.25f * 72, rct.getTop());

        // stroke the lines
        cb.stroke();

        // Do the lower left box
        cb.rectangle((1.25f - 0.09375f) * 72, (.5f - 0.09375f) * 72, boxSize, boxSize);
        cb.setRGBColorFill(0, 72, 117);
        cb.closePathFillStroke();

        // Do the lower right box
        Rectangle pnRect = new Rectangle(0, 0);
        pnRect.setLeft(rct.getRight() - ((.5f + 0.09375f) * 72));
        pnRect.setTop((.5f - 0.09375f) * 72);
        pnRect.setRight(pnRect.getLeft() + boxSize);
        pnRect.setBottom(pnRect.getTop() - boxSize);

        // cb.rectangle(rct.getRight() - ((.5f + 0.09375f) * 72), (.5f -
        // 0.09375f) * 72, (.1875f * 72), (.1875f * 72));
        cb.rectangle(pnRect.getLeft(), pnRect.getTop(), boxSize, boxSize);
        cb.setRGBColorFill(0, 72, 117);
        cb.closePathFillStroke();

        // Now we do the page number if one is supplied.
        if (pageNum.length() > 0) {
            float pnHeight = fontBold.getAscentPoint(pageNum, 9) - fontBold.getDescentPoint(pageNum, 9);
            float pnWidth = fontBold.getWidthPoint(pageNum, 9);

            float l = pnRect.getLeft() + ((boxSize - pnWidth) / 2);
            float b = pnRect.getTop() + ((boxSize - pnHeight) / 2);

            cb.beginText();
            cb.setFontAndSize(fontBold, 9);
            cb.setRGBColorFill(255, 255, 255);
            cb.setTextMatrix(l, b);
            cb.showText(pageNum);
            cb.endText();

        }

        // Display the copyright
        SimpleDateFormat df = new SimpleDateFormat("yyyy");
        char cs = 0x00a9; // Unicode for the copyright symbol
        String copyRight = com.estate.constants.StringConstants.copyRight + cs + " " + df.format(new Date());
        float crWidth;
        float crLeft;

        crWidth = font.getWidthPoint(copyRight, 8);
        cb.beginText();

        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(0, 0, 0);

        crLeft = (doc.getPageSize().getRight() - crWidth) / 2;
        cb.setTextMatrix(crLeft, .375f * 72); // Place the base of the
        // copyright at 3/8" up from
        // the bottom
        cb.showText(copyRight);
        cb.endText();

        if (toolName.length() > 0) {
            cb.beginText();

            cb.setFontAndSize(font, 8);
            cb.setRGBColorFill(0, 0, 0);

            cb.setTextMatrix((1.25f * 72) + boxSize, .375f * 72);
            cb.showText(toolName);
            cb.endText();
        }

        // Fix a licensee at left
        cb.beginText();
        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(0, 0, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, " Licensee: " + getLicense(), (10.2f * 72), .375f * 72,
                0);
        cb.endText();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.estate.pdf.PageBorder.java

public void drawNoBorder(Document doc, String pageNum) {
    try {//  w w w . j ava  2s  . co  m
        PdfContentByte cb = writer.getDirectContentUnder();
        BaseFont fontBold = BaseFont.createFont(Locations.getFontLocation() + "timesbd.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        BaseFont font = BaseFont.createFont(Locations.getFontLocation() + "times.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);
        Rectangle rct = new Rectangle(doc.getPageSize());
        float boxSize = (.1875f * 72);

        // Adjust the top
        rct.setTop(rct.getTop() - (.5f * 72));

        // Do the lower right box
        Rectangle pnRect = new Rectangle(0, 0);
        pnRect.setLeft(rct.getRight() - ((.5f + 0.09375f) * 72));
        pnRect.setTop(((.5f - 0.09375f) * 72) - 9);
        pnRect.setRight(pnRect.getLeft() + boxSize);
        pnRect.setBottom(pnRect.getTop() - boxSize);

        cb.rectangle(pnRect.getLeft(), pnRect.getTop(), boxSize, boxSize);
        cb.setRGBColorFill(0, 72, 117);
        cb.closePathFillStroke();

        // Now we do the page number if one is supplied.
        if (pageNum.length() > 0) {
            float pnHeight = fontBold.getAscentPoint(pageNum, 9) - fontBold.getDescentPoint(pageNum, 9) - 4.5f;
            float pnWidth = fontBold.getWidthPoint(pageNum, 9);

            float l = pnRect.getLeft() + ((boxSize - pnWidth) / 2);
            float b = pnRect.getTop() + ((boxSize - pnHeight) / 2) - 4.5f;

            cb.beginText();
            cb.setFontAndSize(fontBold, 9);
            cb.setRGBColorFill(255, 255, 255);
            cb.setTextMatrix(l, b);
            cb.showText(pageNum);
            cb.endText();
        }

        // Display the copyright
        SimpleDateFormat df = new SimpleDateFormat("yyyy");
        char cs = 0x00a9; // Unicode for the copyright symbol
        String copyRight = "Advanced Practice Network " + cs + " " + df.format(new Date());
        float crWidth;
        float crLeft;

        crWidth = font.getWidthPoint(copyRight, 8);
        cb.beginText();

        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(0, 0, 0);

        crLeft = (doc.getPageSize().getRight() - crWidth) / 2;
        cb.setTextMatrix(crLeft, .375f * 72); // Place the base of the
        // copyright at 3/8" up from
        // the bottom
        cb.showText(copyRight);
        cb.endText();

        if (license != null) {
            // Fix a licensee at left
            cb.beginText();
            cb.setFontAndSize(font, 8);
            cb.setRGBColorFill(0, 0, 0);
            cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, " Licensee: " + getLicense(), (10.2f * 72),
                    .375f * 72, 0);
            cb.endText();
        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:com.moss.pdf.template.core.Renderer.java

License:Open Source License

public void render(InputStream in, List<? extends PropertyMapping> fields, OutputStream out) throws Exception {

    PdfReader reader = new PdfReader(in);

    Document document = new Document(reader.getPageSizeWithRotation(1));

    PdfWriter writer = PdfWriter.getInstance(document, out);

    document.open();/*from  ww w . jav a  2  s .co m*/

    for (int i = 1; i <= reader.getNumberOfPages(); i++) {

        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage customPage = writer.getImportedPage(reader, i);

        /*
         * add the page to our new document, turning this page to its 
         * original rotation
         */
        int pageRotation = reader.getPageRotation(i);

        if (pageRotation > 0) {

            System.out.println("page rotation found: " + pageRotation);

            double angle = -((2 * Math.PI) * pageRotation / 360);
            //         double angle = -(Math.PI / 2);

            cb.addTemplate(customPage, (float) Math.cos(angle), (float) Math.sin(angle),
                    (float) -Math.sin(angle), (float) Math.cos(angle), 0f, // x
                    document.top() + document.topMargin() // y
            );
        } else {
            cb.addTemplate(customPage, 0f, 0f);
        }

        Map<FontName, BaseFont> fonts = new HashMap<FontName, BaseFont>();

        for (PropertyMapping field : fields) {

            if (field.getPageNumber() != i) {
                continue;
            }

            /*
             * Only builtin fonts are supported at the moment
             */
            BaseFont font;
            int fontSize;
            int alignment;
            String text;
            float x, y;
            float rotation;

            {
                font = fonts.get(field.getFontName());

                if (font == null) {

                    FontName e = field.getFontName();
                    String name = null;

                    if (FontName.COURIER == e) {
                        name = BaseFont.COURIER;
                    } else if (FontName.COURIER_BOLD == e) {
                        name = BaseFont.COURIER_BOLD;
                    } else if (FontName.COURIER_BOLD_OBLIQUE == e) {
                        name = BaseFont.COURIER_BOLDOBLIQUE;
                    } else if (FontName.COURIER_OBLIQUE == e) {
                        name = BaseFont.COURIER_OBLIQUE;
                    } else if (FontName.HELVETICA == e) {
                        name = BaseFont.HELVETICA;
                    } else if (FontName.HELVETICA_BOLD == e) {
                        name = BaseFont.HELVETICA_BOLD;
                    } else if (FontName.HELVETICA_BOLD_OBLIQUE == e) {
                        name = BaseFont.HELVETICA_BOLDOBLIQUE;
                    } else if (FontName.HELVETICA_OBLIQUE == e) {
                        name = BaseFont.HELVETICA_OBLIQUE;
                    } else if (FontName.TIMES_BOLD == e) {
                        name = BaseFont.TIMES_BOLD;
                    } else if (FontName.TIMES_BOLD_ITALIC == e) {
                        name = BaseFont.TIMES_BOLDITALIC;
                    } else if (FontName.TIMES_ITALIC == e) {
                        name = BaseFont.TIMES_ITALIC;
                    } else if (FontName.TIMES_ROMAN == e) {
                        name = BaseFont.TIMES_ROMAN;
                    }

                    if (name == null) {
                        throw new RuntimeException("Unknown font type: " + e);
                    }

                    font = BaseFont.createFont(name, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
                    fonts.put(field.getFontName(), font);
                }

                fontSize = field.getFontSize();

                if (TextAlignment.LEFT == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_LEFT;
                } else if (TextAlignment.CENTER == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_CENTER;
                } else if (TextAlignment.RIGHT == field.getAlignment()) {
                    alignment = PdfContentByte.ALIGN_RIGHT;
                } else {
                    alignment = PdfContentByte.ALIGN_LEFT;
                }

                Object value = p.eval(field.getExpr());

                if (value == null) {
                    text = "";
                } else {
                    text = value.toString();
                }

                x = field.getX() * POINTS_IN_A_CM;
                y = field.getY() * POINTS_IN_A_CM;

                rotation = 0;
            }

            cb.beginText();

            cb.setFontAndSize(font, fontSize);

            cb.showTextAligned(alignment, text, x, y, rotation);

            cb.endText();
        }

        document.newPage();
    }

    reader.close();
    document.close();
}

From source file:com.t2.compassionMeditation.ViewSessionsActivity.java

License:Open Source License

/**
 * Create a PDF file based on the contents of the graph
 *//*ww  w.jav  a2s.  co  m*/
void CreatePdf() {

    // Run the export on a separate thread.
    new Thread(new Runnable() {
        @Override
        public void run() {

            Document document = new Document();
            try {
                Date calendar = Calendar.getInstance().getTime();
                mResultsFileName = "BioZenResults_";
                mResultsFileName += (calendar.getYear() + 1900) + "-" + (calendar.getMonth() + 1) + "-"
                        + calendar.getDate() + "_";
                mResultsFileName += calendar.getHours() + "-" + calendar.getMinutes() + "-"
                        + calendar.getSeconds() + ".pdf";

                PdfWriter writer = PdfWriter.getInstance(document,
                        new FileOutputStream(android.os.Environment.getExternalStorageDirectory()
                                + java.io.File.separator + mResultsFileName));
                document.open();
                PdfContentByte contentByte = writer.getDirectContent();
                BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252,
                        BaseFont.NOT_EMBEDDED);
                // Note top of PDF = 900
                float chartWidth = 332;
                float chartHeight = 45;

                float spaceHeight = chartHeight + 30;
                int horizontalPos = 180;
                float verticalPos = 780;

                // Write document header
                contentByte.beginText();
                contentByte.setFontAndSize(baseFont, 20);
                contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "T2 BioZen Report", 300, 800, 0);
                contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER,
                        "Generated on: " + calendar.toLocaleString(), 300, 770, 0);
                contentByte.endText();

                contentByte.setLineWidth(1f);
                verticalPos -= spaceHeight;
                long startTime = startCal.getTimeInMillis();
                long endTime = endCal.getTimeInMillis();

                float maxChartValue = 0;
                float chartYAvg;

                BioSession tmpSession = sessionItems.get(0);
                int maxKeys = tmpSession.keyItemNames.length;

                // Loop through all of the the keys
                for (int key = 0; key < maxKeys; key++) {

                    //Draw a border rect
                    contentByte.setRGBColorStrokeF(0, 0, 0);
                    contentByte.setLineWidth(1f);
                    contentByte.rectangle(horizontalPos, verticalPos, chartWidth, chartHeight);
                    contentByte.stroke();

                    // Write band name
                    contentByte.beginText();
                    contentByte.setFontAndSize(baseFont, 12);
                    BioSession tmpSession1 = sessionItems.get(0);
                    contentByte.showTextAligned(PdfContentByte.ALIGN_RIGHT, tmpSession1.keyItemNames[key], 170,
                            (verticalPos + (chartHeight / 2)) - 5, 0);
                    contentByte.endText();

                    maxChartValue = 0;
                    // First find the max Y
                    for (BioSession session : sessionItems) {
                        if (session.time >= startTime && session.time <= endTime) {
                            chartYAvg = session.avgFilteredValue[key];
                            if (chartYAvg > maxChartValue)
                                maxChartValue = chartYAvg;
                        }
                    }

                    float lastY = -1;
                    float xIncrement = 0;
                    if (sessionItems.size() > 0) {
                        xIncrement = chartWidth / sessionItems.size();
                    }

                    float yIncrement = 0;
                    if (maxChartValue > 0) {
                        yIncrement = chartHeight / maxChartValue;
                    }

                    float highValue = 0;
                    int highTime = 0;
                    float highY = 0;
                    float highX = 0;
                    int lowTime = 0;
                    float lowY = 100;
                    float lowX = chartWidth;
                    float lowValue = maxChartValue;

                    int lCount = 0;
                    String keyName = "";

                    ArrayList<RegressionItem> ritems = new ArrayList<RegressionItem>();

                    // Loop through the session points of this key
                    String rawYValues = "";
                    for (BioSession session : sessionItems) {
                        keyName = session.keyItemNames[key];
                        if (session.time >= startTime && session.time <= endTime) {
                            chartYAvg = session.avgFilteredValue[key];
                            rawYValues += chartYAvg + ", ";
                            if (lastY < 0)
                                lastY = (float) chartYAvg;

                            contentByte.setLineWidth(3f);
                            contentByte.setRGBColorStrokeF(255, 0, 0);

                            float graphXFrom = horizontalPos + (lCount * xIncrement);
                            float graphYFrom = verticalPos + (lastY * yIncrement);
                            float graphXTo = (horizontalPos + ((lCount + 1) * xIncrement));
                            float graphYTo = verticalPos + (chartYAvg * yIncrement);
                            //                     Log.e(TAG, "[" + graphXFrom + ", " + graphYFrom + "] to [" + graphXTo + ", " + graphYTo + "]");
                            // Draw the actual graph
                            contentByte.moveTo(graphXFrom, graphYFrom);
                            contentByte.lineTo(graphXTo, graphYTo);
                            contentByte.stroke();

                            //Add regression Item
                            ritems.add(new RegressionItem(lCount, (chartYAvg * yIncrement)));

                            if (chartYAvg > highValue) {
                                highValue = chartYAvg;
                                highY = graphYTo;
                                highX = graphXTo;
                                highTime = (int) (session.time / 1000);
                            }

                            if (chartYAvg < lowValue) {
                                lowValue = chartYAvg;
                                lowY = graphYTo;
                                lowX = graphXTo;
                                lowTime = (int) (session.time / 1000);
                            }

                            lCount++;
                            lastY = (float) chartYAvg;

                        } // End if (session.time >= startTime && session.time <= endTime )
                    } // End for (BioSession session : sessionItems)            

                    //Draw high low dates
                    if (highY != 0 && lowY != 0) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
                        String hDate = dateFormat.format(new Date((long) highTime * 1000L));
                        String lDate = dateFormat.format(new Date((long) lowTime * 1000L));
                        contentByte.beginText();
                        contentByte.setFontAndSize(baseFont, 8);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, hDate, highX, highY, 0);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, lDate, lowX, lowY, 0);
                        contentByte.endText();
                    }

                    //Draw Regression Line
                    RegressionResult regression = calculateRegression(ritems);
                    contentByte.saveState();
                    contentByte.setRGBColorStrokeF(0, 0, 250);
                    contentByte.setLineDash(3, 3, 0);
                    contentByte.moveTo(horizontalPos, verticalPos + (float) regression.intercept);
                    contentByte.lineTo(horizontalPos + chartWidth, (float) ((verticalPos + regression.intercept)
                            + (float) (regression.slope * (chartWidth / xIncrement))));
                    contentByte.stroke();
                    contentByte.restoreState();
                    contentByte.setRGBColorStrokeF(0, 0, 0);

                    //               Log.e(TAG, keyName + ": [" + rawYValues + "]");
                    // Get ready for the next key (and series of database points )
                    verticalPos -= spaceHeight;

                    if (verticalPos < 30) {
                        document.newPage();
                        verticalPos = 780 - spaceHeight;
                    }

                } // End for (int key = 0; key < maxKeys; key++)

                //document.add(new Paragraph("You can also write stuff directly tot he document like this!"));
            } catch (DocumentException de) {
                System.err.println(de.getMessage());
                Log.e(TAG, de.toString());
            } catch (IOException ioe) {
                System.err.println(ioe.getMessage());
                Log.e(TAG, ioe.toString());
            } catch (Exception e) {
                System.err.println(e.getMessage());
                Log.e(TAG, e.toString());
            }

            // step 5: we close the document
            document.close();
            fileExportCompleteHandler.sendEmptyMessage(EXPORT_SUCCESS);

        }
    }).start();

}

From source file:is.idega.idegaweb.egov.printing.business.DocumentBusinessBean.java

License:Open Source License

public void createHeaderDate(Document document, PdfWriter writer, String dateString) throws DocumentException {
    /*//from ww  w  . j  av  a2s.  c o m
     * final PdfPTable header = new PdfPTable(new float[]{1}); header.setWidthPercentage(100f); final PdfPCell defaultCell = header.getDefaultCell();
     * defaultCell.setBorder(0); //defaultCell.setFixedHeight(getPointsFromMM(40)); defaultCell.setPadding(0); defaultCell.setNoWrap(true);
     * defaultCell.setVerticalAlignment(align); header.addCell(new Phrase(new Chunk(dateString, getDefaultParagraphFont()))); document.add(header);
     */
    PdfContentByte cb = writer.getDirectContent();
    cb.beginText();
    Font font = getDefaultParagraphFont();

    try {
        BaseFont bf = BaseFont.createFont(font.getFamilyname(), BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.setFontAndSize(bf, font.size());
        // we show some text starting on some absolute position with a given
        // alignment
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, dateString, getPointsFromMM(210 - 20),
                getPointsFromMM(297 - 20), 0);
        cb.endText();
    }

    catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.areasy.common.doclet.document.DocumentEventHandler.java

License:Open Source License

/**
 * At the end of each page, index information is collected
 * and footer and headers are inserted./*from   www. j a v a2  s.  c o  m*/
 *
 * @param document The current PDF document.
 * @param writer   The writer used to create the document.
 */
public void onEndPage(PdfWriter writer, Document document) {
    currentPage = document.getPageNumber();
    State.setCurrentPage(currentPage);

    if (State.getCurrentHeaderType() != HEADER_DEFAULT) {
        float len;

        if (State.isContinued() && !State.isLastMethod()) {
            String cont = "(continued on next page)";
            len = bf.getWidthPoint(cont, 7);
            cb.beginText();
            cb.setFontAndSize(bf, 7);
            cb.setTextMatrix(300 - (len / 2), 56);
            cb.showText(cont);
            cb.endText();
        }

        if (State.getCurrentHeaderType() != HEADER_DETAILS) {
            // add lines
            cb.setLineWidth(1f);
            cb.moveTo(LEFT_MARGIN, 812);
            cb.lineTo(RIGHT_MARGIN, 812);
        }

        cb.moveTo(LEFT_MARGIN, 42);
        cb.lineTo(RIGHT_MARGIN, 42);
        cb.stroke();

        // page footer with number of pages
        float textX = (float) 0.0;
        float templateX = (float) 0.0;
        float textWidth = (float) 0.0;
        float numWidth = (float) 0.0;
        int currPageNumberAlign;

        if (pageNumberAlign == PAGE_NUMBER_ALIGN_SWITCH) {
            if ((currentPage % 2) == 0)
                currPageNumberAlign = PAGE_NUMBER_ALIGN_LEFT;
            else
                currPageNumberAlign = PAGE_NUMBER_ALIGN_RIGHT;
        } else
            currPageNumberAlign = pageNumberAlign;

        String text = DefaultConfiguration.getString(ARG_PGN_PREFIX, "Page ") + currentPage;
        if (pageNumberType == PAGE_NUMBER_FULL)
            text = text + " of ";

        textWidth = bf.getWidthPoint(text, 8);
        numWidth = bf.getWidthPoint("999", 8);

        if (currPageNumberAlign == PAGE_NUMBER_ALIGN_LEFT)
            textX = LEFT_MARGIN;

        if (currPageNumberAlign == PAGE_NUMBER_ALIGN_CENTER)
            textX = (float) (DOCUMENT_WIDTH / 2) - (textWidth / 2);

        if (currPageNumberAlign == PAGE_NUMBER_ALIGN_RIGHT)
            textX = RIGHT_MARGIN - textWidth - numWidth;

        templateX = textX + textWidth;

        cb.beginText();
        cb.setFontAndSize(bf, 8);

        if (currPageNumberAlign == PAGE_NUMBER_ALIGN_LEFT) {
            cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text, textX, FOOTER_BASELINE, 0);
        }

        if (currPageNumberAlign == PAGE_NUMBER_ALIGN_CENTER) {
            cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text, textX, FOOTER_BASELINE, 0);
        }

        if (currPageNumberAlign == PAGE_NUMBER_ALIGN_RIGHT) {
            cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text, textX, FOOTER_BASELINE, 0);
        }

        cb.endText();

        if (pageNumberType == PAGE_NUMBER_FULL) {
            // add template for total page number
            cb.addTemplate(template, templateX, FOOTER_BASELINE);
        }

        // headers (left, right, center)
        // temporary solution: handling of first page of package
        // not correct yet, so use fix heading configuration now
        if (State.getCurrentHeaderType() == HEADER_API) {
            leftHeader = "";
            centerHeader = "$CLASS";
            rightHeader = "";
        }

        if (State.getCurrentHeaderType() == HEADER_INDEX) {
            leftHeader = "";
            centerHeader = "Index";
            rightHeader = "";
        }

        if (State.getCurrentHeaderType() == HEADER_DETAILS) {
            leftHeader = "";
            centerHeader = "";
            rightHeader = "";
        }

        cb.beginText();
        cb.setFontAndSize(bf, 8);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, parseHeader(centerHeader), DOCUMENT_WIDTH / 2,
                HEADER_BASELINE, 0);
        cb.endText();

        cb.beginText();
        cb.setFontAndSize(bf, 8);
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, parseHeader(leftHeader), LEFT_MARGIN, HEADER_BASELINE, 0);
        cb.endText();

        cb.beginText();
        cb.setFontAndSize(bf, 8);
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, parseHeader(rightHeader), RIGHT_MARGIN, HEADER_BASELINE,
                0);
        cb.endText();
    }
}

From source file:org.mapfish.print.PDFUtils.java

License:Open Source License

public static int getHorizontalAlignment(String labelAlign) {
    /* Valid values for horizontal alignment: "l"=left, "c"=center, "r"=right. */
    int myAlignment = PdfContentByte.ALIGN_LEFT;
    if (labelAlign.toUpperCase().contains("L")) {
        myAlignment = PdfContentByte.ALIGN_LEFT;
    }//from   w  ww  .j  a  v a 2 s .  co m
    if (labelAlign.toUpperCase().contains("C")) {
        myAlignment = PdfContentByte.ALIGN_CENTER;
    }
    if (labelAlign.toUpperCase().contains("R")) {
        myAlignment = PdfContentByte.ALIGN_RIGHT;
    }
    return myAlignment;
}

From source file:org.openconcerto.erp.core.finance.accounting.report.PdfGenerator.java

License:Open Source License

protected void addTextRight(String code, String string, int i, int j) {
    // addText(PdfContentByte.ALIGN_RIGHT, code, string, i, j, 0);

    int a = PdfContentByte.ALIGN_RIGHT;
    int k = 0;//from ww  w  .j  a  v a  2s  .  c  o  m

    if (this.map == null)
        this.cb.showTextAligned(a, string, i, j, k);
    else {
        boolean error = false;
        String s = (String) this.map.get(code);
        if (s == null) {
            System.out.println("Impossibe de trouver: " + code + " Set color red");
            s = code;
            error = true;

            // cb.setColorFill(Color.RED);
        } else {
            if (s.equalsIgnoreCase("-0.0")) {
                s = "0.0";
            }
            s = insertCurrencySpaces(s);
        }
        System.out.println("print " + s);
        this.cb.showTextAligned(a, s, i, j, k);
        if (error) {
            System.out.println(" Set color black");
            this.cb.setColorStroke(Color.BLACK);
        }
    }

}

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  . ja  va  2 s.  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.unitime.timetable.util.PdfEventHandler.java

License:Open Source License

/**
 * Print footer string on each page//  w  w w. j av a2 s .c o m
 * @param writer
 * @param document
 */
public void onEndPage(PdfWriter writer, Document document) {

    if (getDateTime() == null) {
        setDateTime(new Date());
    }

    PdfContentByte cb = writer.getDirectContent();
    cb.beginText();
    cb.setFontAndSize(getBaseFont(), getFontSize());
    cb.showTextAligned(PdfContentByte.ALIGN_LEFT, getDateFormat().format(getDateTime()), document.left(), 20,
            0);
    cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, String.valueOf(document.getPageNumber()), document.right(),
            20, 0);
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, MESSAGES.pdfCopyright(Constants.getVersion()),
            (document.left() + document.right()) / 2, 20, 0);
    cb.endText();

    return;
}