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

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

Introduction

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

Prototype

public void showText(PdfTextArray text) 

Source Link

Document

Show an array of text.

Usage

From source file:com.teag.reports.EstatePlan.java

private void drawLifeExp() {
    PdfContentByte cb = writer.getDirectContentUnder();

    char c = userInfo.getClientFirstName().charAt(0);
    char s = ' ';
    if (!userInfo.isSingle()) {
        s = userInfo.getSpouseFirstName().charAt(0);
    }/*from   w ww.j  a  v  a 2 s  .  c om*/

    String cText = Character.toString(c).toUpperCase() + ": " + userInfo.getClientFirstName()
            + " actuarial life expectancy - " + userInfo.getClientLifeExpectancy() + " years";
    String sText = Character.toString(s).toUpperCase() + ": " + userInfo.getSpouseFirstName()
            + " actuarial life expectancy - " + userInfo.getSpouseLifeExpectancy() + " years";
    try {
        BaseFont font = BaseFont.createFont(Locations.getFontLocation() + "times.ttf", BaseFont.CP1252,
                BaseFont.EMBEDDED);

        cb.beginText();
        cb.setFontAndSize(font, 8);
        cb.setRGBColorFill(255, 0, 0);
        cb.setTextMatrix(72 * .5F, .4f * 72);
        cb.showText(cText);
        cb.endText();
        if (!userInfo.isSingle()) {
            cb.beginText();
            cb.setFontAndSize(font, 8);
            cb.setRGBColorFill(255, 0, 0);
            cb.setTextMatrix(72 * .5F, .25f * 72);
            cb.showText(sText);
            cb.endText();
        }
    } catch (Exception e) {
        System.err.println("Error printing Life Expectancy");
    }
}

From source file:de.cuseb.bilderbuch.pdf.PdfController.java

License:Open Source License

@RequestMapping(value = "/pdf", method = RequestMethod.GET)
public void generatePdf(HttpSession session, HttpServletResponse httpServletResponse) {

    try {/*from ww w . j  a  va2 s.  c o  m*/
        PdfRequest pdfRequest = (PdfRequest) session.getAttribute("pdfRequest");
        httpServletResponse.setContentType("application/pdf");

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, httpServletResponse.getOutputStream());
        writer.setDefaultColorspace(PdfName.COLORSPACE, PdfName.DEFAULTRGB);

        //document.addAuthor(pdfRequest.getAuthor());
        //document.addTitle(pdfRequest.getTitle());
        document.setPageSize(
                new Rectangle(Utilities.millimetersToPoints(156), Utilities.millimetersToPoints(148)));
        document.open();

        FontFactory.defaultEmbedding = true;
        FontFactory.register("IndieRock.ttf", "IndieRock");
        Font font = FontFactory.getFont("IndieRock");
        BaseFont baseFont = font.getBaseFont();
        PdfContentByte cb = writer.getDirectContent();

        Iterator<PdfPage> pages = pdfRequest.getPages().iterator();
        while (pages.hasNext()) {

            PdfPage page = pages.next();
            if (page.getImage() != null) {

                Image image = Image.getInstance(new URL(page.getImage().getUrl()));
                image.setDpi(300, 300);
                image.setAbsolutePosition(0f, 0f);
                image.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight());
                document.add(image);

                cb.saveState();
                cb.beginText();
                cb.setColorFill(Color.WHITE);
                cb.moveText(10f, 10f);
                cb.setFontAndSize(baseFont, 18);
                cb.showText(page.getSentence());
                cb.endText();
                cb.restoreState();

                if (pages.hasNext()) {
                    document.newPage();
                }
            }
        }
        document.close();

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

From source file:fr.aliasource.webmail.server.export.ConversationPdfEventHandler.java

License:GNU General Public License

/**
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter,
 *      com.lowagie.text.Document)//  www  .ja v a2s .c om
 */
public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    // write the headertable
    table.setTotalWidth(document.right() - document.left());
    table.writeSelectedRows(0, -1, document.left(), document.getPageSize().getHeight() - 20, cb);
    // compose the footer
    String text = writer.getPageNumber() + " / ";
    float textSize = helv.getWidthPoint(text, 12);
    float textBase = document.bottom() - 49;
    cb.beginText();
    cb.setFontAndSize(helv, 12);
    float adjust = helv.getWidthPoint("0", 12);
    cb.setTextMatrix(document.right() - textSize - adjust - 5, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(tpl, document.right() - adjust, textBase);
    cb.saveState();
    // draw a Rectangle around the page
    cb.setLineWidth(1);
    cb.rectangle(20, 20, document.getPageSize().getWidth() - 40, document.getPageSize().getHeight() - 40);
    cb.stroke();
    cb.restoreState();
}

From source file:mx.randalf.digital.ocr.hocrtopdf.HocrToPdf.java

License:Open Source License

public void hocrToPdf(File fImg, File fHtml, File fPdf) throws IOException, DocumentException, Exception {
    URL inputHOCRFile = null;//  ww w  .j  a v a  2 s .  c om
    FileOutputStream outputPDFStream = null;
    // The resolution of a PDF file (using iText) is 72pt per inch
    float pointsPerInch = 72.0f;
    Source source = null;
    StartTag pageTag = null;
    Pattern imagePattern = null;
    Matcher imageMatcher = null;
    // Load the image
    Image pageImage = null;
    float dotsPerPointX;
    float dotsPerPointY;
    float pageImagePixelHeight;
    Document pdfDocument = null;
    PdfWriter pdfWriter = null;
    Font defaultFont = null;
    PdfContentByte cb = null;
    Pattern bboxPattern = null;
    Pattern bboxCoordinatePattern = null;
    StartTag ocrLineTag = null;

    try {
        try {
            inputHOCRFile = new URL("file://" + fHtml.getAbsolutePath());
        } catch (MalformedURLException e) {
            throw e;
        }
        try {
            outputPDFStream = new FileOutputStream(fPdf);
        } catch (FileNotFoundException e) {
            throw e;
        }

        // Using the jericho library to parse the HTML file
        source = new Source(inputHOCRFile);

        // Find the tag of class ocr_page in order to load the scanned image
        pageTag = source.findNextStartTag(0, "class", "ocr_page", false);
        imagePattern = Pattern.compile("image\\s+([^;]+)");
        imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title"));
        if (!imageMatcher.find()) {
            throw new Exception("Could not find a tag of class \"ocr_page\", aborting.");
        }

        try {
            pageImage = Image.getInstance(new URL("file://" + fImg.getAbsolutePath()));
        } catch (MalformedURLException e) {
            throw e;
        }
        dotsPerPointX = pageImage.getDpiX() / pointsPerInch;
        dotsPerPointY = pageImage.getDpiY() / pointsPerInch;
        pageImagePixelHeight = pageImage.getHeight();
        pdfDocument = new Document(
                new Rectangle(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY));
        pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream);
        pdfDocument.open();

        // first define a standard font for our text
        defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK);

        // Put the text behind the picture (reverse for debugging)
        cb = pdfWriter.getDirectContentUnder();
        //PdfContentByte cb = pdfWriter.getDirectContent();

        pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);
        pageImage.setAbsolutePosition(0, 0);
        // Put the image in front of the text (reverse for debugging)
        pdfWriter.getDirectContent().addImage(pageImage);
        //pdfWriter.getDirectContentUnder().addImage(pageImage);

        // In order to place text behind the recognised text snippets we are interested in the bbox property      
        bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}");
        // This pattern separates the coordinates of the bbox property
        bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
        // Only tags of the ocr_line class are interesting
        ocrLineTag = source.findNextStartTag(0, "class", "ocr_line", false);
        while (ocrLineTag != null) {
            au.id.jericho.lib.html.Element lineElement = ocrLineTag.getElement();
            Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title"));
            if (bboxMatcher.find()) {
                // We found a tag of the ocr_line class containing a bbox property
                Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group());
                bboxCoordinateMatcher.find();
                int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))),
                        Integer.parseInt((bboxCoordinateMatcher.group(2))),
                        Integer.parseInt((bboxCoordinateMatcher.group(3))),
                        Integer.parseInt((bboxCoordinateMatcher.group(4))) };
                String line = lineElement.getContent().extractText();
                //               float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
                float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;

                // Put the text into the PDF
                cb.beginText();
                // Comment the next line to debug the PDF output (visible Text)
                cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                // TODO: Scale the text width to fit the OCR bbox
                cb.setFontAndSize(defaultFont.getBaseFont(), Math.round(bboxHeightPt));
                cb.moveText((float) (coordinates[0] / dotsPerPointX),
                        (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY));
                cb.showText(line);
                cb.endText();
            }
            ocrLineTag = source.findNextStartTag(ocrLineTag.getEnd(), "class", "ocr_line", false);
        }
    } catch (NumberFormatException e) {
        throw e;
    } catch (MalformedURLException e) {
        throw e;
    } catch (FileNotFoundException e) {
        throw e;
    } catch (BadElementException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } catch (DocumentException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    } finally {
        if (pdfDocument != null) {
            pdfDocument.close();
        }
        if (outputPDFStream != null) {
            outputPDFStream.close();
        }
    }
}

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 a v a2  s  .c om*/

    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.layout.pdf.font.FontCacheUtils.java

License:Open Source License

static void createUnicodePDF(String format, Locale locale, String fileName) throws Exception {
    FontMappingManager manager = FontMappingManagerFactory.getInstance().getFontMappingManager(format, locale);

    // step 1: creation of a document-object
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
    document.open();/*from   w w  w.ja v  a2  s.  c o  m*/
    for (int seg = 0; seg < 0xFF; seg++) {
        PdfContentByte cb = writer.getDirectContent();
        cb.beginText();
        for (int hi = 0; hi < 16; hi++) {
            for (int lo = 0; lo < 16; lo++) {
                int x = 100 + hi * 32;
                int y = 100 + lo * 32;
                char ch = (char) (seg * 0xFF + hi * 16 + lo);

                String fontFamily = manager.getDefaultPhysicalFont(ch);
                BaseFont bf = manager.createFont(fontFamily, Font.NORMAL);
                cb.setFontAndSize(bf, 16);
                cb.setTextMatrix(x, y);
                cb.showText(new String(new char[] { ch }));
            }
        }
        cb.endText();
    }
    document.close();
}

From source file:org.kuali.kfs.module.purap.pdf.PurapPdf.java

License:Open Source License

/**
 * Overrides the method in PdfPageEventHelper from itext to write the headerTable, compose the footer and show the
 * footer.//from  ww  w.j ava 2 s. c om
 *
 * @param writer    The PdfWriter for this document.
 * @param document  The document.
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
@Override
public void onEndPage(PdfWriter writer, Document document) {
    LOG.debug("onEndPage() started.");
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    // write the headerTable
    headerTable.setTotalWidth(document.right() - document.left());
    headerTable.writeSelectedRows(0, -1, document.left(), document.getPageSize().height() - 10, cb);
    // compose the footer
    String text = "Page " + writer.getPageNumber() + " of ";
    float textSize = helv.getWidthPoint(text, 12);
    float textBase = document.bottom() - 20;
    cb.beginText();
    cb.setFontAndSize(helv, 12);
    // show the footer
    float adjust = helv.getWidthPoint("0", 12);
    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(tpl, document.right() - adjust, textBase);
    cb.saveState();
}

From source file:org.kuali.kfs.module.purap.pdf.PurchaseOrderQuoteRequestsPdf.java

License:Open Source License

/**
 * Overrides the method in PdfPageEventHelper from itext to compose the footer and show the
 * footer./*from   www  . j ava 2 s. c  om*/
 *
 * @param writer    The PdfWriter for this document.
 * @param document  The document.
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onEndPage(PdfWriter writer, Document document) {
    LOG.debug("onEndPage() started.");
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    // compose the footer
    String text = "Page " + writer.getPageNumber() + " of ";
    float textSize = helv.getWidthPoint(text, 12);
    float textBase = document.bottom() - 20;
    cb.beginText();
    cb.setFontAndSize(helv, 12);
    // show the footer
    float adjust = helv.getWidthPoint("0", 12);
    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(tpl, document.right() - adjust, textBase);
    cb.saveState();
}

From source file:org.kuali.ole.module.purap.pdf.PurapPdf.java

License:Educational Community License

/**
 * Overrides the method in PdfPageEventHelper from itext to write the headerTable, compose the footer and show the
 * footer.//  w  ww  .  java 2  s . c o  m
 *
 * @param writer   The PdfWriter for this document.
 * @param document The document.
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onEndPage(PdfWriter writer, Document document) {
    LOG.debug("onEndPage() started.");
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    // write the headerTable
    headerTable.setTotalWidth(document.right() - document.left());
    headerTable.writeSelectedRows(0, -1, document.left(), document.getPageSize().height() - 10, cb);
    // compose the footer
    String text = "Page " + writer.getPageNumber() + " of ";
    float textSize = helv.getWidthPoint(text, 12);
    float textBase = document.bottom() - 20;
    cb.beginText();
    cb.setFontAndSize(helv, 12);
    // show the footer
    float adjust = helv.getWidthPoint("0", 12);
    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(tpl, document.right() - adjust, textBase);
    cb.saveState();
}

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

License:Open Source License

@Override
public void onEndPage(final PdfWriter writer, final Document document) {
    PdfContentByte cb = writer.getDirectContent();
    if (document.getPageNumber() == 1) {
        ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, new Phrase(""),
                (document.right() - document.left()) / 2 + document.leftMargin(), document.top() - 5, 0f);
    }//w  ww .  ja va 2  s  .  c  o m
    ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(""), document.left(), document.bottom() - 15,
            0f);

    int pageN = writer.getPageNumber();
    String text = "Page " + pageN + " of ";
    cb.beginText();
    cb.setFontAndSize(helv, 11);
    cb.setTextMatrix(document.right() - document.rightMargin() - 10, document.bottom() - 15);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(template, document.right(), document.bottom() - 15);

}