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

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

Introduction

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

Prototype

int ALIGN_LEFT

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

Click Source Link

Document

The alignment is left

Usage

From source file:br.org.archimedes.io.pdf.elements.TextExporter.java

License:Open Source License

public void exportElement(Text text, Object outputObject) throws IOException {

    PDFWriterHelper helper = (PDFWriterHelper) outputObject;
    PdfContentByte cb = helper.getPdfContentByte();

    Point lowerLeft = text.getLowerLeft();
    Point docPoint = helper.modelToDocument(lowerLeft);

    BaseFont font = null;//from w w w  .  j a  v  a2 s.  c  o  m
    try {
        font = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    } catch (DocumentException e) {
        // Problems creating the font. This means the current
        // platform does not support this encoding or font.
        System.err.println(Messages.TextExporter_FontCreatingError);
        e.printStackTrace();
    }
    cb.setFontAndSize(font, (float) text.getSize());
    cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
    cb.beginText();
    cb.moveText((float) docPoint.getX(), (float) docPoint.getY());
    double angle = 0;
    try {
        angle = Geometrics.calculateAngle(new Point(0, 0), text.getDirection().getPoint());
    } catch (NullArgumentException e) {
        // Shouldn't happen since the text MUST have a direction to exists
        // and the point 0,0 is valid
        e.printStackTrace();
    }
    float degreeAngle = (float) (angle * 180 / Math.PI);
    cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text.getText(), (float) docPoint.getX(),
            (float) docPoint.getY(), degreeAngle);
    cb.endText();
}

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();/*  www .ja  v 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.virtusa.akura.student.controller.MessageBoardController.java

License:Open Source License

/**
 * Merge many pdf files into one file.//from w ww . jav  a2 s. c om
 *
 * @param streamOfPDFFiles - a list of inputStreams
 * @param outputStream - an instance of outputStream
 * @param paginate - a boolean
 * @throws AkuraAppException - The exception details that occurred when processing
 */
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate)
        throws AkuraAppException {

    final int fontSize = 8, leftRightAlignment = 8;
    final int min = 0;
    final int max = 5;
    final int size = 300;
    final int xAxis = -150;
    final int pageHeight = 550;
    final int pageHieghtfromBottom = 16;
    final int pageRecHeight = 580;
    final int recHeightFromBottom = 14;
    Document document = new Document(PageSize.A4);
    try {
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the output stream
        PdfWriter writer = null;
        BaseFont bf = null;
        try {
            writer = PdfWriter.getInstance(document, outputStream);

            document.open();

            bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                if (currentPageNumber != 2) {
                    document.newPage();
                }
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                if (currentPageNumber == 1) {
                    cb.addTemplate(page, 0, xAxis);
                } else if (currentPageNumber != 2) {
                    cb.addTemplate(page, 0, 0);
                }

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, fontSize);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + AkuraWebConstant.REPORT_GPL, size,
                            max, min);
                    cb.newlineText();
                    cb.endText();

                    if (currentPageNumber != 2) {
                        int pageNo = currentPageNumber;
                        if (currentPageNumber != 1) {
                            pageNo = currentPageNumber - 1;
                        }

                        // write the page number inside a rectangle.
                        cb.fillStroke();
                        cb.rectangle(leftRightAlignment, recHeightFromBottom, pageRecHeight,
                                leftRightAlignment);
                        cb.beginText();
                        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, PAGE + pageNo, pageHeight,
                                pageHieghtfromBottom, 0);
                        cb.endText();
                        cb.stroke();
                    }
                }
            }
            pageOfCurrentReaderPDF = 0;
        }

        outputStream.flush();

        document.close();

        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:dinamica.PDFPageEvents.java

License:LGPL

/**
 * Create custom-made footer on every page, this
 * will place the empty template on every page
 *//*from  www .  j a  v a2  s  . com*/
public void onEndPage(PdfWriter writer, Document document) {

    // print (x of ...) on every page (bottom right)
    // append template at the end of the footer, like:
    // 1 of [template] - template is an empty box
    String footer = writer.getPageNumber() + this.pageXofY;
    float tWidth = bf.getWidthPoint(footer, 10);
    float extraSpace = bf.getWidthPoint("00", 10);
    float ty = document.bottom() - 12; //below bottom margin
    float tx = document.right() - tWidth - extraSpace; //x coordinate for the footer

    // print "X of " on right-side and footer + date on left side
    cb.beginText();
    cb.setFontAndSize(bf, 10);
    cb.showTextAligned(PdfContentByte.ALIGN_LEFT, footer, tx, ty, 0);
    cb.showTextAligned(PdfContentByte.ALIGN_LEFT, footerLeft, document.left(), ty, 0);
    cb.endText();

    // now append empty template after "X of " 
    cb.addTemplate(tpl, document.right() - extraSpace, ty);

}

From source file:org.andrill.coretools.graphics.driver.pdf.PDFDriver.java

License:Apache License

/**
 * {@inheritDoc}/*from  w  ww  .j  a  v a  2 s.  c o  m*/
 */
public void drawString(final Point2D point, final Font font, final String string) {
    content.setFontAndSize(fontMapper.awtToPdf(font), font.getSize2D());
    content.beginText();
    content.showTextAligned(PdfContentByte.ALIGN_LEFT, string, x(point.getX()),
            y(point.getY() + font.getSize2D()), 0);
    content.endText();
}

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   w w w .  j  a v a 2s  .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.geomajas.plugin.print.component.PdfContext.java

License:Open Source License

/**
 * Draw text in the center of the specified box.
 *
 * @param text text//w  ww .jav a 2 s.  co  m
 * @param font font
 * @param box box to put text int
 * @param fontColor colour
 */
public void drawText(String text, Font font, Rectangle box, Color fontColor) {
    template.saveState();
    // get the font
    DefaultFontMapper mapper = new DefaultFontMapper();
    BaseFont bf = mapper.awtToPdf(font);
    template.setFontAndSize(bf, font.getSize());

    // calculate descent
    float descent = 0;
    if (text != null) {
        descent = bf.getDescentPoint(text, font.getSize());
    }

    // calculate the fitting size
    Rectangle fit = getTextSize(text, font);

    // draw text if necessary
    template.setColorFill(fontColor);
    template.beginText();
    template.showTextAligned(PdfContentByte.ALIGN_LEFT, text,
            origX + box.getLeft() + 0.5f * (box.getWidth() - fit.getWidth()),
            origY + box.getBottom() + 0.5f * (box.getHeight() - fit.getHeight()) - descent, 0);
    template.endText();
    template.restoreState();
}

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 ww w  .  j a  v  a 2 s.com
    if (labelAlign.toUpperCase().contains("C")) {
        myAlignment = PdfContentByte.ALIGN_CENTER;
    }
    if (labelAlign.toUpperCase().contains("R")) {
        myAlignment = PdfContentByte.ALIGN_RIGHT;
    }
    return myAlignment;
}

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

License:Open Source License

/**
 * Draws the labels. The transformation is setup in a manner where the
 * position of the labels is at (label.paperOffset,0).
 *//*w  w w. j  av a  2 s . c o m*/
private void drawLabels(PdfContentByte dc) {
    float prevPos = getTotalWidth();

    for (int i = labels.size() - 1; i >= 0; --i) {
        Label label = labels.get(i);
        final float offsetH;
        final float offsetV;
        if (block.getTextDirection().getAngle() == block.getBarDirection().getAngle()) {
            //same direction
            offsetH = -label.width / 2;
            offsetV = -maxLabelHeight;

        } else if (block.getTextDirection().getAngle() == -block.getBarDirection().getAngle()) {
            //opposite direction
            offsetH = label.width / 2;
            offsetV = 0;
        } else if (block.getTextDirection().getAngle() - block.getBarDirection().getAngle() < 0) {
            offsetH = label.width / 2;
            offsetV = -label.height;
        } else {
            offsetH = -label.width / 2;
            offsetV = 0;
        }

        if (label.paperOffset + Math.abs(offsetH) <= prevPos - 1) {
            dc.beginText();
            dc.showTextAligned(PdfContentByte.ALIGN_LEFT, label.label, label.paperOffset + offsetH, offsetV,
                    (float) (block.getBarDirection().getAngle() - block.getTextDirection().getAngle()));
            dc.endText();
            prevPos = label.paperOffset - Math.abs(offsetH);
        } else {
            //the label would be written over the previous one => ignore it
            label.label = null;
        }
    }
}

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

License:Open Source License

protected void addSplittedText(String code, String string, int fromx, int y, double deltax) {
    float x = fromx - this.offsetX - this.templateOffsetX;
    y = y - this.offsetY - this.templateOffsetY;
    boolean error = false;
    String s = string;/*from  ww w  . j  a v  a 2s  . co  m*/
    if (this.map != null) {
        s = (String) this.map.get(code);

    }
    if (s == null) {
        s = code;
        error = true;
        this.cb.setColorFill(Color.RED);
    }

    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        String sub = String.valueOf(c);

        this.cb.showTextAligned(PdfContentByte.ALIGN_LEFT, sub, x, y, 0);
        x += deltax;
    }

    if (error) {

        this.cb.setColorStroke(Color.BLACK);
    }

}