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

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

Introduction

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

Prototype

public void beginText() 

Source Link

Document

Starts the writing of text.

Usage

From source file:org.oscarehr.phr.web.PHRUserManagementAction.java

License:Open Source License

public ByteArrayOutputStream generateUserRegistrationLetter(String demographicNo, String username,
        String password) throws Exception {
    log.debug("Demographic " + demographicNo + " username " + username + " password " + password);
    DemographicDao demographicDao = (DemographicDao) SpringUtils.getBean("demographicDao");
    Demographic demographic = demographicDao.getDemographic(demographicNo);

    final String PAGESIZE = "printPageSize";
    Document document = new Document();

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfWriter writer = null;/*from   w ww  . j  a va2 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;/* w w w.  ja v a2  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);
    }
}

From source file:org.posterita.core.PDFReportPageEventHelper.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();/*from w ww  . j av a 2s  .  co m*/
    // write the headertable
    table.setTotalWidth(document.right() - document.left());
    table.writeSelectedRows(0, -1, document.left(), document.getPageSize().getHeight() - 50, cb);
    // compose the footer
    String text = "Page " + writer.getPageNumber() + " of ";
    float textSize = PAGE_FOOTER_FONT.getBaseFont().getWidthPoint(text, 10);
    float textBase = document.bottom() - 20;
    cb.beginText();
    cb.setFontAndSize(PAGE_FOOTER_FONT.getBaseFont(), 10);

    float adjust = PAGE_FOOTER_FONT.getBaseFont().getWidthPoint("0", 10);
    cb.setTextMatrix(document.right() - textSize - adjust, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(tpl, document.right() - adjust, textBase);

    cb.saveState();

    text = "Report Generated on : " + dateAndTime;

    textSize = PAGE_FOOTER_FONT.getBaseFont().getWidthPoint(text, 10);
    textBase = document.bottom() - 20;
    cb.beginText();
    cb.setFontAndSize(PAGE_FOOTER_FONT.getBaseFont(), 10);

    adjust = PAGE_FOOTER_FONT.getBaseFont().getWidthPoint("0", 10);
    cb.setTextMatrix(MARGIN, textBase);
    cb.showText(text);
    cb.endText();

    cb.saveState();

}

From source file:org.revager.export.PDFPageEventHelper.java

License:Open Source License

@Override
public void onEndPage(PdfWriter writer, Document document) {
    int columnNumber;

    try {//from  w  w  w . j a  v  a 2  s  .c om
        Rectangle page = document.getPageSize();
        float pageWidth = page.getWidth() - document.leftMargin() - document.rightMargin();

        /*
         * Write marks
         */
        setMarks(writer, document);

        /*
         * Define fonts
         */
        headBaseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        Font headFont = new Font(headBaseFont, headFontSize);

        footBaseFont = BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED);
        Font footFont = new Font(footBaseFont, footFontSize);

        /*
         * Cell fill for space between head/foot and content
         */
        PdfPCell cellFill = new PdfPCell();
        cellFill.setMinimumHeight(PDFTools.cmToPt(0.8f));
        cellFill.setBorderWidth(0);

        /*
         * Write head
         */
        if (headLogoPath != null) {
            columnNumber = 2;
        } else {
            columnNumber = 1;
        }

        PdfPTable head = new PdfPTable(columnNumber);

        Phrase phraseTitle = new Phrase(headTitle, headFont);

        PdfPCell cellTitle = new PdfPCell(phraseTitle);
        cellTitle.setHorizontalAlignment(Element.ALIGN_LEFT);
        cellTitle.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cellTitle.setPaddingTop(0);
        cellTitle.setPaddingBottom(PDFTools.cmToPt(0.2f));
        cellTitle.setPaddingLeft(0);
        cellTitle.setPaddingRight(0);
        cellTitle.setBorderWidthTop(0);
        cellTitle.setBorderWidthBottom(0.5f);
        cellTitle.setBorderWidthLeft(0);
        cellTitle.setBorderWidthRight(0);

        head.addCell(cellTitle);

        if (headLogoPath != null) {
            Image headLogo = Image.getInstance(headLogoPath);
            headLogo.scaleToFit(PDFTools.cmToPt(5.0f), PDFTools.cmToPt(1.1f));

            PdfPCell cellLogo = new PdfPCell(headLogo);
            cellLogo.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cellLogo.setVerticalAlignment(Element.ALIGN_BOTTOM);
            cellLogo.setPaddingTop(0);
            cellLogo.setPaddingBottom(PDFTools.cmToPt(0.15f));
            cellLogo.setPaddingLeft(0);
            cellLogo.setPaddingRight(0);
            cellLogo.setBorderWidthTop(0);
            cellLogo.setBorderWidthBottom(0.5f);
            cellLogo.setBorderWidthLeft(0);
            cellLogo.setBorderWidthRight(0);

            head.addCell(cellLogo);

            head.addCell(cellFill);
        }

        head.addCell(cellFill);

        head.setTotalWidth(pageWidth);
        head.writeSelectedRows(0, -1, document.leftMargin(),
                page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());

        /*
         * Write foot
         */
        if (footText == null) {
            footText = " ";
        }

        PdfPTable foot = new PdfPTable(1);

        foot.addCell(cellFill);

        PdfPCell cellFootText = new PdfPCell(new Phrase(footText, footFont));
        cellFootText.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cellFootText.setVerticalAlignment(Element.ALIGN_TOP);
        cellFootText.setPaddingTop(PDFTools.cmToPt(0.15f));
        cellFootText.setPaddingBottom(0);
        cellFootText.setPaddingLeft(0);
        cellFootText.setPaddingRight(0);
        cellFootText.setBorderWidthTop(0.5f);
        cellFootText.setBorderWidthBottom(0);
        cellFootText.setBorderWidthLeft(0);
        cellFootText.setBorderWidthRight(0);

        foot.addCell(cellFootText);

        /*
         * Print page numbers
         */
        PdfContentByte contentByte = writer.getDirectContent();
        contentByte.saveState();

        String text = MessageFormat.format(translate("Page {0} of") + " ", writer.getPageNumber());

        float textSize = footBaseFont.getWidthPoint(text, footFontSize);
        float textBase = document.bottom() - PDFTools.cmToPt(1.26f);
        contentByte.beginText();
        contentByte.setFontAndSize(footBaseFont, footFontSize);

        float adjust;
        if (footText.trim().equals("")) {
            adjust = (pageWidth / 2) - (textSize / 2) - footBaseFont.getWidthPoint("0", footFontSize);
        } else {
            adjust = 0;
        }

        contentByte.setTextMatrix(document.left() + adjust, textBase);
        contentByte.showText(text);
        contentByte.endText();
        contentByte.addTemplate(template, document.left() + adjust + textSize, textBase);

        contentByte.stroke();
        contentByte.restoreState();

        foot.setTotalWidth(pageWidth);
        foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                writer.getDirectContent());
    } catch (Exception e) {
        /*
         * Not part of unit testing because this exception is only thrown if
         * an internal error occurs.
         */
        throw new ExceptionConverter(e);
    }
}

From source file:org.sakaiproject.evaluation.tool.reporting.EvalPDFReportBuilder.java

License:Educational Community License

public void addTitlePage(String evaltitle, String groupNames, String startDate, String endDate,
        String responseInformation, byte[] bannerImageBytes, String evalSystemTitle, String informationTitle) {
    try {/* www. j  av a 2s  .  c o  m*/
        float pagefooter = paragraphFont.getSize();

        PdfContentByte cb = pdfWriter.getDirectContent();

        float docMiddle = (document.right() - document.left()) / 2 + document.leftMargin();

        Paragraph emptyPara = new Paragraph(" ");
        emptyPara.setSpacingAfter(100.0f);

        // Title
        Paragraph titlePara = new Paragraph("\n\n\n" + evaltitle, frontTitleFont);
        titlePara.setAlignment(Element.ALIGN_CENTER);
        document.add(titlePara);

        // Groups

        Paragraph groupPara = new Paragraph(groupNames, frontAuthorFont);
        groupPara.setSpacingBefore(25.0f);
        groupPara.setAlignment(Element.ALIGN_CENTER);
        document.add(groupPara);

        // Little info area? I don't know, it was on the mockup though
        Paragraph infoPara = new Paragraph(informationTitle, frontInfoFont);
        infoPara.setAlignment(Element.ALIGN_CENTER);
        infoPara.setSpacingBefore(90.0f);
        document.add(infoPara);

        // Started on
        Paragraph startedPara = new Paragraph(startDate, frontInfoFont);
        startedPara.setAlignment(Element.ALIGN_CENTER);
        startedPara.setSpacingBefore(25.0f);
        document.add(startedPara);

        // Ended on
        Paragraph endedPara = new Paragraph(endDate, frontInfoFont);
        endedPara.setAlignment(Element.ALIGN_CENTER);
        endedPara.setSpacingBefore(25.0f);
        document.add(endedPara);

        // Reply Rate
        Paragraph replyRatePara = new Paragraph(responseInformation, frontInfoFont);
        replyRatePara.setAlignment(Element.ALIGN_CENTER);
        replyRatePara.setSpacingBefore(25.0f);
        document.add(replyRatePara);

        // Logo and Tagline
        cb.beginText();
        cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 12);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, evalSystemTitle, docMiddle, document.bottom() + 20, 0);
        cb.endText();

        if (bannerImageBytes != null) {
            Image banner = Image.getInstance(bannerImageBytes);
            cb.addImage(banner, banner.getWidth(), 0, 0, banner.getHeight(),
                    docMiddle - (banner.getWidth() / 2), document.bottom() + 35);
        }

        document.newPage();

        responseArea = new ColumnText(cb);
        responseArea.setSimpleColumn(document.left(), document.top(), document.right() / 2,
                document.bottom() + pagefooter);
        responseArea.go();
    } catch (DocumentException | IOException de) {
        throw UniversalRuntimeException.accumulate(de, "Unable to create title page");
    }
}

From source file:org.sonar.report.pdf.Events.java

License:Open Source License

private void printPageNumber(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();//from www . j a v  a2s  .  c  o m
    float textBase = document.bottom() - 20;
    try {
        cb.setFontAndSize(BaseFont.createFont("Helvetica", BaseFont.WINANSI, false), 12);
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    cb.beginText();
    cb.setTextMatrix(document.right() - 10, textBase);
    cb.showText(String.valueOf(writer.getPageNumber()));
    cb.endText();
    cb.saveState();
}

From source file:org.sonarqube.report.extendedpdf.ExtendedEvents.java

License:Open Source License

private void printPageNumber(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();//from  www.ja  va2s  . c  om
    float textBase = document.bottom() - 45;
    try {
        cb.setFontAndSize(BaseFont.createFont("Helvetica", BaseFont.WINANSI, false), 12);
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    cb.beginText();
    cb.setTextMatrix(document.right() - 10, textBase);
    cb.showText(String.valueOf(writer.getPageNumber()));
    cb.endText();
    cb.saveState();
}

From source file:org.unitime.timetable.util.PdfEventHandler.java

License:Open Source License

/**
 * Print footer string on each page/*  w  w w  .  j  a v  a2s .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;
}

From source file:org.xhtmlrenderer.pdf.ITextOutputDevice.java

License:Open Source License

public void drawString(String s, float x, float y, JustificationInfo info) {
    if (Configuration.isTrue("xr.renderer.replace-missing-characters", false)) {
        s = replaceMissingCharacters(s);
    }/*from   w w w.  jav  a 2  s . c  o m*/
    if (s.length() == 0)
        return;
    PdfContentByte cb = _currentPage;
    ensureFillColor();
    AffineTransform at = (AffineTransform) getTransform().clone();
    at.translate(x, y);
    AffineTransform inverse = normalizeMatrix(at);
    AffineTransform flipper = AffineTransform.getScaleInstance(1, -1);
    inverse.concatenate(flipper);
    inverse.scale(_dotsPerPoint, _dotsPerPoint);
    double[] mx = new double[6];
    inverse.getMatrix(mx);
    cb.beginText();
    // Check if bold or italic need to be emulated
    boolean resetMode = false;
    FontDescription desc = _font.getFontDescription();
    float fontSize = _font.getSize2D() / _dotsPerPoint;
    cb.setFontAndSize(desc.getFont(), fontSize);
    float b = (float) mx[1];
    float c = (float) mx[2];
    FontSpecification fontSpec = getFontSpecification();
    if (fontSpec != null) {
        int need = ITextFontResolver.convertWeightToInt(fontSpec.fontWeight);
        int have = desc.getWeight();

        if (need > have) {
            cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
            float lineWidth = fontSize * 0.04f; // 4% of font size
            cb.setLineWidth(lineWidth);
            resetMode = true;
            ensureStrokeColor();
        }
        if ((fontSpec.fontStyle == IdentValue.ITALIC) && (desc.getStyle() != IdentValue.ITALIC)) {
            b = 0f;
            c = 0.21256f;
        }
    }
    cb.setTextMatrix((float) mx[0], b, c, (float) mx[3], (float) mx[4], (float) mx[5]);
    if (info == null) {
        cb.showText(s);
    } else {
        PdfTextArray array = makeJustificationArray(s, info);
        cb.showText(array);
    }
    if (resetMode) {
        cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
        cb.setLineWidth(1);
    }
    cb.endText();
}

From source file:oscar.eform.util.EFormPDFServlet.java

License:Open Source License

private void writeContent(Properties printCfg, Properties props, Properties measurements, float height,
        PdfContentByte cb) throws Exception {
    for (Enumeration e = printCfg.propertyNames(); e.hasMoreElements();) {
        StringBuilder temp = new StringBuilder(e.nextElement().toString());
        String[] cfgVal = printCfg.getProperty(temp.toString()).split(" *, *");

        String[] fontType = null;
        int fontFlags = 0;
        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//from w  ww  .  ja v a2  s.  co  m
                fontFlags = Font.NORMAL;
        } else {
            fontFlags = Font.NORMAL;
            fontType = new String[] { cfgVal[4].trim() };
        }

        String encoding = null;
        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;
        }

        BaseFont bf = BaseFont.createFont(fontType[0], encoding, BaseFont.NOT_EMBEDDED);
        String propValue = props.getProperty(temp.toString());
        //if not in regular config then check measurements
        if (propValue == null) {
            propValue = measurements.getProperty(temp.toString(), "");
        }

        ColumnText ct = new ColumnText(cb);
        // 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, propValue, font));
            ct.go();
            continue;
        }

        // draw line directly
        if (temp.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()));
            cb.stroke();

        } else if (temp.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()) : propValue), 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 ? ((propValue.equals("") ? "" : cfgVal[6].trim())) : propValue),
                    Integer.parseInt(cfgVal[1].trim()), (height - Integer.parseInt(cfgVal[2].trim())), 0);

            cb.endText();
        }
    }
}