Example usage for com.lowagie.text Font Font

List of usage examples for com.lowagie.text Font Font

Introduction

In this page you can find the example usage for com.lowagie.text Font Font.

Prototype


public Font(int family, float size) 

Source Link

Document

Constructs a Font.

Usage

From source file:ambit.data.qmrf.Qmrf_Xml_Pdf.java

License:Open Source License

public Qmrf_Xml_Pdf(String ttffont) {
    super();/*  w w w .j av a2  s . c o  m*/
    try {
        this.ttffont = ttffont;
        docBuilder = docBuilderFactory.newDocumentBuilder();
        nodeBuilder = docBuilderFactory.newDocumentBuilder();
        nodeBuilder.setErrorHandler(new ErrorHandler() {
            public void error(SAXParseException arg0) throws SAXException {
                throw new SAXException(arg0);
            }

            public void fatalError(SAXParseException arg0) throws SAXException {
                throw new SAXException(arg0);
            }

            public void warning(SAXParseException arg0) throws SAXException {
            }
        });
        //PRIndirectReference pri;
        //pri.
        try {

            baseFont = BaseFont.createFont(ttffont,
                    //"c:\\windows\\fonts\\times.ttf",
                    BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            System.out.println(ttffont);
        } catch (Exception x) {
            x.printStackTrace();
            baseFont = BaseFont.createFont("c:\\windows\\fonts\\times.ttf", BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED);
            System.out.println("Default font c:\\windows\\fonts\\times.ttf");
        }

        font = new Font(baseFont, 12);
        bfont = new Font(baseFont, 12, Font.BOLD);
    } catch (Exception x) {
        docBuilder = null;
    }

}

From source file:ca.sqlpower.architect.profile.output.ProfilePDFFormat.java

License:Open Source License

/**
 * Outputs a PDF file report of the data in drs to the given
 * output stream./* w ww.  ja va  2 s .co m*/
 * @throws SQLObjectException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public void format(OutputStream out, List<ProfileResult> profileResults)
        throws DocumentException, IOException, SQLException, SQLObjectException, InstantiationException,
        IllegalAccessException, ClassNotFoundException {

    final int minRowsTogether = 1; // counts smaller than this are considered orphan/widow
    final int mtop = 50; // margin at top of page (in points)
    final int mbot = 50; // margin at bottom of page (page numbers are below this)
    //        final int pbot = 20;  // padding between bottom margin and bottom of body text
    final int mlft = 50; // margin at left side of page
    final int mrgt = 50; // margin at right side of page
    final Rectangle pagesize = PageSize.LETTER.rotate();
    final Document document = new Document(pagesize, mlft, mrgt, mtop, mbot);
    final PdfWriter writer = PdfWriter.getInstance(document, out);

    final float fsize = 6f; // the font size to use in the table body
    final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    document.addTitle("Table Profiling Report");
    document.addSubject("Tables: " + profileResults);
    document.addAuthor(System.getProperty("user.name"));
    document.addCreator("Power*Architect version " + ArchitectVersion.APP_FULL_VERSION);

    document.open();

    // vertical position where next element should start
    //   (bottom is 0; top is pagesize.height())
    float pos = pagesize.height() - mtop;

    final PdfContentByte cb = writer.getDirectContent();
    final PdfTemplate nptemplate = cb.createTemplate(50, 50);
    writer.setPageEvent(new PdfPageEventHelper() {
        // prints the "page N of <template>" footer
        public void onEndPage(PdfWriter writer, Document document) {
            int pageN = writer.getPageNumber();
            String text = "Page " + pageN + " of ";
            float len = bf.getWidthPoint(text, fsize - 2);
            cb.beginText();
            cb.setFontAndSize(bf, fsize - 2);
            cb.setTextMatrix(pagesize.width() / 2 - len / 2, mbot / 2);
            cb.showText(text);
            cb.endText();
            cb.addTemplate(nptemplate, pagesize.width() / 2 - len / 2 + len, mbot / 2);
        }

        public void onCloseDocument(PdfWriter writer, Document document) {
            nptemplate.beginText();
            nptemplate.setFontAndSize(bf, fsize - 2);
            nptemplate.showText(String.valueOf(writer.getPageNumber() - 1));
            nptemplate.endText();
        }
    });

    document.add(new Paragraph("SQL Power Architect Profiling Report"));
    document.add(new Paragraph("Generated " + new java.util.Date() + " by " + System.getProperty("user.name")));

    float[] widths = new float[totalColumn]; // widths of widest cells per row in pdf table
    LinkedList<ProfileTableStructure> profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result

    Font f = new Font(bf, fsize);

    // This ddl generator is set to the appropriate ddl generator for the source database
    // every time we encounter a table profile result in the list.
    DDLGenerator ddlg = null;

    PdfPTable pdfTable = null;
    for (ProfileResult result : profileResults) {
        if (result instanceof TableProfileResult) {
            TableProfileResult tableResult = (TableProfileResult) result;
            pdfTable = new PdfPTable(widths.length);
            pdfTable.setWidthPercentage(100f);
            ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths);
            profiles.add(oneProfile);
            ddlg = tableResult.getDDLGenerator();
        } else if (result instanceof ColumnProfileResult) {
            final ColumnProfileResult columnResult = (ColumnProfileResult) result;
            TableProfileResult tResult = columnResult.getParent();
            addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths);
        }
    }

    double allowedTableSize = pagesize.width() - mrgt - mlft;
    double totalWidths = 0;
    for (int i = 0; i < headings.length; i++) {
        if (!columnsToTruncate.contains(headings[i])) {
            widths[i] += PIXELS_PER_BORDER;
            totalWidths += widths[i];
        }
    }
    truncateLength = (allowedTableSize - totalWidths - (PIXELS_PER_BORDER * (columnsToTruncate.size())))
            / columnsToTruncate.size();
    logger.debug("Truncate length is " + truncateLength);
    widths = new float[totalColumn];

    profiles = new LinkedList<ProfileTableStructure>(); // 1 table per profile result
    for (ProfileResult result : profileResults) {
        if (result instanceof TableProfileResult) {
            TableProfileResult tableResult = (TableProfileResult) result;
            pdfTable = new PdfPTable(widths.length);
            pdfTable.setWidthPercentage(100f);
            ProfileTableStructure oneProfile = makeNextTable(tableResult, pdfTable, bf, fsize, widths);
            profiles.add(oneProfile);
            ddlg = tableResult.getDDLGenerator();
        } else if (result instanceof ColumnProfileResult) {
            final ColumnProfileResult columnResult = (ColumnProfileResult) result;
            TableProfileResult tResult = columnResult.getParent();
            addBodyRow(tResult, columnResult, ddlg, pdfTable, bf, f, fsize, widths);
        }
    }

    for (int i = 0; i < headings.length; i++) {
        widths[i] += PIXELS_PER_BORDER;
    }

    // add the PdfPTables to the document; try to avoid orphan and widow rows
    pos = writer.getVerticalPosition(true) - fsize;
    logger.debug("Starting at pos=" + pos);
    boolean newPageInd = true;

    for (ProfileTableStructure profile : profiles) {

        pdfTable = profile.getMainTable();
        pdfTable.setTotalWidth(pagesize.width() - mrgt - mlft);
        pdfTable.setWidths(widths);
        resetHeaderWidths(profile, widths);

        int startrow = pdfTable.getHeaderRows();
        int endrow = startrow; // current page will contain header+startrow..endrow

        /* no other rows in the table, just the header, and the header may
         * contain error message
         */
        if (endrow == pdfTable.size()) {
            pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb);
            continue;
        }

        while (endrow < pdfTable.size()) {

            // figure out how many body rows fit nicely on the page
            float endpos = pos - calcHeaderHeight(pdfTable);

            // y position of page number# = (mbot/2+fsize)
            while ((endpos - pdfTable.getRowHeight(endrow)) >= (mbot / 2 + fsize + 2)
                    && endrow < pdfTable.size()) {
                endpos -= pdfTable.getRowHeight(endrow);
                endrow++;
            }

            // adjust for orphan rows. Might create widows or make
            // endrow < startrow, which is handled later by deferring the table
            if (endrow < pdfTable.size() && endrow + minRowsTogether >= pdfTable.size()) {

                // page # maybe fall into table area, but usually that's column of
                // min value, usually that's enough space for both, or we should
                // disable page # on this page
                if (endrow + 1 == pdfTable.size() && endpos - pdfTable.getRowHeight(endrow) > 10) {

                    // short by 1 row.. just squeeze it in
                    endrow = pdfTable.size();
                } else {
                    // more than 1 row remains: shorten this page so orphans aren't lonely
                    endrow = pdfTable.size() - minRowsTogether;
                }
            }

            if (endrow == pdfTable.size() || endrow - startrow >= minRowsTogether) {
                // this is the end of the table, or we have enough rows to bother printing
                pos = pdfTable.writeSelectedRows(0, pdfTable.getHeaderRows(), mlft, pos, cb);
                pos = pdfTable.writeSelectedRows(startrow, endrow, mlft, pos, cb);
                startrow = endrow;
                newPageInd = false;
            } else {
                // not the end of the table and not enough rows to print out
                if (newPageInd)
                    throw new IllegalStateException(
                            "PDF Page is not large engouh to display " + minRowsTogether + " row(s)");
                endrow = startrow;
            }

            // new page if necessary (that is, when we aren't finished the table yet)
            if (endrow != pdfTable.size()) {
                document.newPage();
                pos = pagesize.height() - mtop;
                newPageInd = true;
            }
        }
    }
    document.close();
}

From source file:com.ev.export.AnnualPDFExporter.java

License:Apache License

private void addHeading() throws Exception {
    Element elem = new Paragraph("Energieverbrauch " + year, new Font(Font.TIMES_ROMAN, 24));
    document.add(elem);/*from www. ja  v a  2  s.  c  om*/
}

From source file:com.gtdfree.test.PDFTestFont.java

License:Open Source License

/**
 * Fonts and encoding.//from   w w  w . ja va 2  s. co  m
 * @param args no arguments needed
 */
public static void main(String[] args) {

    System.out.println("Encodings");

    String[] names = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();

    System.out.println(Arrays.toString(names));

    /*System.out.println("---");
    try {
    System.getProperties().store(System.out, "");
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    System.out.println("---");*/
    //System.out.println(System.getenv());
    //System.out.println("---");

    //String font= System.getProperty("java.home")+"/lib/fonts/LucidaBrightRegular.ttf";
    //String font= "fonts/DejaVuSans.ttf";

    //byte[] ttf= ApplicationHelper.loadResource(font);

    try {
        // step 1
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream("encodingfont.pdf"));
        // step 3
        document.open();
        // step 4
        String all[] = { "Symbol", "ZapfDingbats" };
        Font hex = new Font(Font.HELVETICA, 5);
        for (int z = 0; z < all.length; ++z) {
            String file = all[z];
            document.add(new Paragraph(
                    "Unicode equivalence for the font \"" + file + "\" with the encoding \"" + file + "\"\n"));
            /*char tb[];
            if (z == 0)
               tb = SYMBOL_TABLE;
            else
               tb = DINGBATS_TABLE;*/
            BaseFont bf;
            if (z == 2) {
                bf = BaseFont.createFont(file, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, null, null);
                ;
            } else {
                bf = BaseFont.createFont(file, file, true);
            }
            Font f = new Font(bf, 12);
            PdfPTable table = new PdfPTable(16);
            table.setWidthPercentage(100);
            table.getDefaultCell().setBorderWidth(1);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            for (char k = 0; k < Character.MAX_VALUE; ++k) {
                char c = k;
                if (bf.charExists(c)) {
                    Phrase ph = new Phrase(12, new String(new char[] { c }), f);
                    ph.add(new Phrase(12, "\n" + Integer.toString(c) + "\n" + cst(c), hex));
                    table.addCell(ph);
                } /*
                  else {
                     Phrase ph = new Phrase("\u00a0");
                     ph.add(new Phrase(12, "\n\n" + cst(c), hex));
                     table.addCell(ph);
                  }*/
            }
            document.add(table);
            document.newPage();
        }
        // step 5
        document.close();

        FontFactory.registerDirectories();

        Set<?> s = FontFactory.getRegisteredFonts();

        System.out.println("Fonts: " + s);

        s = FontFactory.getRegisteredFamilies();

        System.out.println("Families: " + s);

        ArrayList<Font> f = new ArrayList<Font>(s.size());

        for (Object name : s) {

            try {
                f.add(FontFactory.getFont(name.toString(), "UTF-8", true, 12, Font.NORMAL, Color.BLACK, true));
            } catch (Exception e) {
                f.add(FontFactory.getFont(name.toString(), "UTF-8", false, 12, Font.NORMAL, Color.BLACK, true));
            }

        }

        Collections.sort(f, new Comparator<Font>() {
            @Override
            public int compare(Font o1, Font o2) {
                return o1.getFamilyname().compareTo(o2.getFamilyname());
            }
        });

        for (Font ff : f) {

            if (ff.getBaseFont() == null) {
                continue;
            }
            System.out.println(ff.getFamilyname() + " " + ff.getBaseFont().isEmbedded());

        }

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

From source file:com.qcadoo.mes.costCalculation.print.utils.CostCalculationMaterial.java

License:Open Source License

public CostCalculationMaterial(String productNumber, String unit, BigDecimal productQuantity,
        BigDecimal costForGivenQuantity) {
    this.productNumber = productNumber;
    this.unit = unit;
    this.productQuantity = productQuantity;
    this.costForGivenQuantity = costForGivenQuantity;
    this.totalCost = costForGivenQuantity;
    this.toAdd = BigDecimal.ZERO;
    redFont = new Font(FontUtils.getDejavu(), 7);
    redFont.setColor(Color.RED);/*from   ww w .  j  av a 2s  .com*/
}

From source file:com.qcadoo.mes.costCalculation.print.utils.CostCalculationMaterial.java

License:Open Source License

public CostCalculationMaterial(String productNumber, String unit, BigDecimal productQuantity,
        BigDecimal costForGivenQuantity, BigDecimal totalCost, BigDecimal toAdd) {
    this.productNumber = productNumber;
    this.unit = unit;
    this.productQuantity = productQuantity;
    this.costForGivenQuantity = costForGivenQuantity;
    this.totalCost = totalCost;
    this.toAdd = toAdd;
    redFont = new Font(FontUtils.getDejavu(), 7);
    redFont.setColor(Color.RED);//from w ww.  j  ava 2 s.c om

}

From source file:com.qcadoo.report.api.FontUtils.java

License:Open Source License

/**
 * Prepare fonts./*  ww w.ja v  a 2 s. c  om*/
 * 
 * @throws DocumentException
 * @throws IOException
 */
public static synchronized void prepare() throws DocumentException, IOException {
    if (dejavuBold10Dark == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Pdf fonts initialization");
        }
        try {
            FontFactory.register("/fonts/dejaVu/DejaVuSans.ttf");
            dejavu = BaseFont.createFont("/fonts/dejaVu/DejaVuSans.ttf", BaseFont.IDENTITY_H,
                    BaseFont.EMBEDDED);
        } catch (ExceptionConverter e) {
            LOG.warn("Font not found, using embedded font helvetica");
            dejavu = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        }
        dejavuBold70Light = new Font(dejavu, 70);
        dejavuBold70Light.setStyle(Font.BOLD);
        dejavuBold70Light.setColor(ColorUtils.getLightColor());

        dejavuBold70Dark = new Font(dejavu, 70);
        dejavuBold70Dark.setStyle(Font.BOLD);
        dejavuBold70Dark.setColor(ColorUtils.getDarkColor());

        dejavuBold19Light = new Font(dejavu, 19);
        dejavuBold19Light.setStyle(Font.BOLD);
        dejavuBold19Light.setColor(ColorUtils.getLightColor());

        dejavuBold19Dark = new Font(dejavu, 19);
        dejavuBold19Dark.setStyle(Font.BOLD);
        dejavuBold19Dark.setColor(ColorUtils.getDarkColor());

        dejavuBold14Dark = new Font(dejavu, 14);
        dejavuBold14Dark.setStyle(Font.BOLD);
        dejavuBold14Dark.setColor(ColorUtils.getDarkColor());

        dejavuBold17Light = new Font(dejavu, 17);
        dejavuBold17Light.setStyle(Font.BOLD);
        dejavuBold17Light.setColor(ColorUtils.getLightColor());

        dejavuBold14Light = new Font(dejavu, 17);
        dejavuBold14Light.setStyle(Font.BOLD);
        dejavuBold14Light.setColor(ColorUtils.getLightColor());

        dejavuBold17Dark = new Font(dejavu, 17);
        dejavuBold17Dark.setStyle(Font.BOLD);
        dejavuBold17Dark.setColor(ColorUtils.getDarkColor());

        dejavuRegular9Light = new Font(dejavu, 9);
        dejavuRegular9Light.setColor(ColorUtils.getLightColor());

        dejavuRegular9Dark = new Font(dejavu, 9);
        dejavuRegular9Dark.setColor(ColorUtils.getDarkColor());

        dejavuRegular7Dark = new Font(dejavu, 7);
        dejavuRegular7Dark.setColor(ColorUtils.getDarkColor());

        dejavuBold9Dark = new Font(dejavu, 9);
        dejavuBold9Dark.setColor(ColorUtils.getDarkColor());
        dejavuBold9Dark.setStyle(Font.BOLD);

        dejavuBold11Dark = new Font(dejavu, 11);
        dejavuBold11Dark.setColor(ColorUtils.getDarkColor());
        dejavuBold11Dark.setStyle(Font.BOLD);

        dejavuBold11Light = new Font(dejavu, 11);
        dejavuBold11Light.setColor(ColorUtils.getLightColor());
        dejavuBold11Light.setStyle(Font.BOLD);

        dejavuRegular10Dark = new Font(dejavu, 10);
        dejavuRegular10Dark.setColor(ColorUtils.getDarkColor());

        dejavuBold10Dark = new Font(dejavu, 10);
        dejavuBold10Dark.setColor(ColorUtils.getDarkColor());
        dejavuBold10Dark.setStyle(Font.BOLD);

        dejavuRegular7Light = new Font(dejavu, 7);
        dejavuRegular7Light.setColor(ColorUtils.getLightColor());

        dejavuBold7Dark = new Font(dejavu, 7);
        dejavuBold7Dark.setColor(ColorUtils.getDarkColor());
        dejavuBold7Dark.setStyle(Font.BOLD);

        dejavuBold8Dark = new Font(dejavu, 8);
        dejavuBold8Dark.setColor(ColorUtils.getDarkColor());
        dejavuBold8Dark.setStyle(Font.BOLD);

    }
}

From source file:corner.orm.tapestry.pdf.PdfUtils.java

License:Apache License

/**
 * ./*ww w . java2 s .  co m*/
 * @param size ?
 * @return
 */
public static final Font createSongLightFont(int size) {
    BaseFont bf = createSongLightBaseFont();
    if (size <= 0) {
        size = Font.UNDEFINED;
    }
    Font font = new Font(bf, size);
    return font;

}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFTitlePage.java

License:Apache License

/************************************************************************************
 * get font as {@link Font} from given font name and size
 * /*w  w w .  j a  va 2  s . co m*/
 * @param fontname name of font
 * @param fontsize size of font
 * 
 * @throws PDFManagerException
 ************************************************************************************/
private Font getPDFFont(int fontsize) throws PDFManagerException {
    Font resultfont = null;

    // set the base font
    try {
        if (this.ttffontpath == null) {
            // don't use TTF

            LOGGER.debug("Do not use TrueType Font... instead standard Arial is used");
            resultfont = FontFactory.getFont("Arial", BaseFont.CP1252, BaseFont.EMBEDDED, fontsize);

            // String[] codePages = basefont.getCodePagesSupported();
            // System.out.println("All available encodings for font:\n\n");
            // for (int i = 0; i < codePages.length; i++) {
            // System.out.println(codePages[i]);
            // }
        } else {
            // load font, embedd it - use unicode
            LOGGER.debug("Use TrueType Font... at:" + this.ttffontpath);

            BaseFont bf = BaseFont.createFont(this.ttffontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            resultfont = new Font(bf, fontsize);
        }

    } catch (Exception e) {
        LOGGER.error("DocumentException while creating title page for PDF", e);
        throw new PDFManagerException("Exception while creating Titlepage for PDF", e);
    }

    return resultfont;
}

From source file:dinamica.AbstractPDFOutput.java

License:LGPL

/**
 * Receives a byte buffer that should be filled with resulting PDF.
 * @param data Data module that provides recordsets to this output module
 * @param buf Buffer to print PDF, then used to send to browser
 * @throws Throwable//from  www . ja  va  2 s  . co m
 */
protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable {

    //pdf objects
    Document doc = new Document();
    PdfWriter docWriter = PdfWriter.getInstance(doc, buf);

    //header
    HeaderFooter header = new HeaderFooter(new Phrase(getHeader()), false);
    header.setBorder(Rectangle.BOTTOM);
    header.setAlignment(Rectangle.ALIGN_CENTER);
    doc.setHeader(header);

    //footer
    HeaderFooter footer = new HeaderFooter(new Phrase(getFooter()), true);
    footer.setBorder(Rectangle.TOP);
    footer.setAlignment(Rectangle.ALIGN_RIGHT);
    doc.setFooter(footer);

    //pagesize
    doc.setPageSize(PageSize.LETTER);

    doc.open();

    //title
    Paragraph t = new Paragraph(getReportTitle(), new Font(Font.HELVETICA, 18f));
    t.setAlignment(Rectangle.ALIGN_CENTER);
    doc.add(t);

    //paragraph
    Paragraph p = new Paragraph("Hello World");
    p.setAlignment(Rectangle.ALIGN_CENTER);
    doc.add(p);

    doc.close();
    docWriter.close();

}