Example usage for com.lowagie.text FontFactory register

List of usage examples for com.lowagie.text FontFactory register

Introduction

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

Prototype


public static void register(String path) 

Source Link

Document

Register a ttf- or a ttc-file.

Usage

From source file:com.aripd.clms.service.ContractServiceBean.java

@Override
public void generatePdf(ContractEntity contract) {
    String baseFontUrl = "/fonts/Quivira.otf";
    FontFactory.register(baseFontUrl);

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {//w w w .  j a va  2  s  .  c  o  m
        BaseFont bf = BaseFont.createFont(baseFontUrl, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        Font font18n = new Font(bf, 18, Font.NORMAL);
        Font font12n = new Font(bf, 12, Font.NORMAL);
        Font font8n = new Font(bf, 8, Font.NORMAL);
        Font font8nbu = new Font(bf, 8, Font.BOLD | Font.UNDERLINE);
        Font font8ng = new Font(bf, 8, Font.NORMAL, Color.DARK_GRAY);
        Font font6n = new Font(bf, 6, Font.NORMAL);

        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        addMetaData(document);
        addTitlePage(document, contract);
        Image imgBlue = Image.getInstance(1, 1, 3, 8, new byte[] { (byte) 0, (byte) 0, (byte) 255, });
        imgBlue.scaleAbsolute(document.getPageSize().getWidth(), 10);
        imgBlue.setAbsolutePosition(0, document.getPageSize().getHeight() - imgBlue.getScaledHeight());
        PdfImage stream = new PdfImage(imgBlue, "", null);
        stream.put(new PdfName("ITXT_SpecialId"), new PdfName("123456789"));
        PdfIndirectObject ref = writer.addToBody(stream);
        imgBlue.setDirectReference(ref.getIndirectReference());
        document.add(imgBlue);

        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);

        PdfPCell cell = new PdfPCell(new Paragraph(contract.getName(), font18n));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        cell.setPadding(5);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Version: " + contract.getVersion(), font8n));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        cell.setPadding(5);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Review: " + contract.getReview(), font8n));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        cell.setPadding(5);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph(contract.getRemark(), font12n));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setColspan(2);
        cell.setPadding(5);
        table.addCell(cell);
        document.add(table);
        // Start a new page
        document.newPage();

        HTMLWorker htmlWorker = new HTMLWorker(document);
        htmlWorker.parse(new StringReader(contract.getRemark()));
        // Start a new page
        document.newPage();

        document.add(new Paragraph("Review Board", font18n));
        document.add(new LineSeparator(0.5f, 100, null, 0, -5));

        table = new PdfPTable(3);
        table.setWidthPercentage(100);

        cell = new PdfPCell(new Paragraph("Review Board", font18n));
        cell.setColspan(3);
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Version", font12n));
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Date", font12n));
        table.addCell(cell);
        cell = new PdfPCell(new Paragraph("Review", font12n));
        table.addCell(cell);
        for (HistoryContractEntity history : historyContractService.listing(contract)) {
            cell = new PdfPCell(new Paragraph(history.getVersion().toString(), font8n));
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(history.getStartdate().toString(), font8n));
            table.addCell(cell);
            cell = new PdfPCell(new Paragraph(history.getReview(), font8n));
            table.addCell(cell);
        }
        document.add(table);

        document.close();

        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.reset();
        response.addHeader("Content-Type", "application/force-download");
        String filename = URLEncoder.encode(contract.getName() + ".pdf", "UTF-8");
        //            response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + filename);
        response.getOutputStream().write(output.toByteArray());
        response.getOutputStream().flush();
        context.responseComplete();
        context.renderResponse();

    } catch (BadPdfFormatException | IOException ex) {
        Logger.getLogger(ContractServiceBean.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(ContractServiceBean.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.dlya.facturews.DlyaPdfExporter2.java

License:Open Source License

protected static synchronized void registerFonts() {
    if (!fontsRegistered) {
        List<PropertySuffix> fontFiles = JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance())
                .getProperties(PDF_FONT_FILES_PREFIX);//FIXMECONTEXT no default here and below
        if (!fontFiles.isEmpty()) {
            for (Iterator<PropertySuffix> i = fontFiles.iterator(); i.hasNext();) {
                JRPropertiesUtil.PropertySuffix font = i.next();
                String file = font.getValue();
                if (file.toLowerCase().endsWith(".ttc")) {
                    FontFactory.register(file);
                } else {
                    String alias = font.getSuffix();
                    FontFactory.register(file, alias);
                }//from   w ww  .  j a  va  2  s  .c  om
            }
        }

        List<PropertySuffix> fontDirs = JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance())
                .getProperties(PDF_FONT_DIRS_PREFIX);
        if (!fontDirs.isEmpty()) {
            for (Iterator<PropertySuffix> i = fontDirs.iterator(); i.hasNext();) {
                JRPropertiesUtil.PropertySuffix dir = i.next();
                FontFactory.registerDirectory(dir.getValue());
            }
        }

        fontsRegistered = true;
    }
}

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

License:Open Source License

/**
 * Prepare fonts.//from   w  ww.  ja  v  a 2 s  .c  o  m
 * 
 * @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:net.sf.jasperreports.engine.export.JRPdfExporter.java

License:LGPL

protected static synchronized void registerFonts() {
    if (!fontsRegistered) {
        List fontFiles = JRProperties.getProperties(JRProperties.PDF_FONT_FILES_PREFIX);
        if (!fontFiles.isEmpty()) {
            for (Iterator i = fontFiles.iterator(); i.hasNext();) {
                JRProperties.PropertySuffix font = (JRProperties.PropertySuffix) i.next();
                String file = font.getValue();
                if (file.toLowerCase().endsWith(".ttc")) {
                    FontFactory.register(file);
                } else {
                    String alias = font.getSuffix();
                    FontFactory.register(file, alias);
                }//from w  w w.  j  a v a  2s .c o  m
            }
        }

        List fontDirs = JRProperties.getProperties(JRProperties.PDF_FONT_DIRS_PREFIX);
        if (!fontDirs.isEmpty()) {
            for (Iterator i = fontDirs.iterator(); i.hasNext();) {
                JRProperties.PropertySuffix dir = (JRProperties.PropertySuffix) i.next();
                FontFactory.registerDirectory(dir.getValue());
            }
        }

        fontsRegistered = true;
    }
}

From source file:org.eclipse.birt.report.engine.layout.pdf.font.FontMappingManagerFactory.java

License:Open Source License

private static void registerFontPath(final String fontPath) {
    AccessController.doPrivileged(new PrivilegedAction<Object>() {

        public Object run() {
            long start = System.currentTimeMillis();
            File file = new File(fontPath);
            if (file.exists()) {
                if (file.isDirectory()) {
                    FontFactory.registerDirectory(fontPath);
                } else {
                    FontFactory.register(fontPath);
                }/*from   w  ww  .j av a  2  s .  c  o m*/
            }
            long end = System.currentTimeMillis();
            logger.info("register fonts in " + fontPath + " cost:" + (end - start) + "ms");
            return null;
        }
    });
}

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

License:Open Source License

/**
 * Register the user specified fonts in iText.
 */// ww  w  .  ja  v a  2 s  .c o  m
private void initFonts() {
    //we don't do that since it takes ages and that would hurt the perfs for
    //the python controller:
    //FontFactory.registerDirectories();

    FontFactory.defaultEmbedding = true;

    final TreeSet<String> fontPaths = config.getFonts();
    if (fontPaths != null) {
        for (String fontPath : fontPaths) {
            fontPath = fontPath.replaceAll("\\$\\{configDir\\}", configDir);
            File fontFile = new File(fontPath);
            if (fontFile.isDirectory()) {
                FontFactory.registerDirectory(fontPath, true);
            } else {
                FontFactory.register(fontPath);
            }
        }
    }
}

From source file:org.oss.pdfreporter.pdf.Document.java

License:Open Source License

@Override
public void registerTrueTypeFont(String pathToFont, boolean embed) {
    FontFactory.register(pathToFont);

}

From source file:org.pz.platypus.plugin.html.HtmlFont.java

License:Open Source License

/**
 * Get the name by which iText refers to this font. This routine is mostly occupied
 * with the special handling of the base14 fonts. For all other fonts, this routine
 * simply returns its existing name./*from  w ww .  ja  v a  2  s  . co m*/
 *
 * @param f PdfFont whose iText name we're getting
 * @return a string containing the iText usable name for this font.
 */
String createItextFontName(final HtmlFont f) {
    String iTextFontName;
    String typefaceName = f.typeface;

    // handle the different versions of base14 fonts
    if (typefaceName.equals("COURIER")) {
        if (f.bold) {
            if (f.italics)
                iTextFontName = BaseFont.COURIER_BOLDOBLIQUE;
            else
                iTextFontName = BaseFont.COURIER_BOLD;
        } else if (f.italics)
            iTextFontName = BaseFont.COURIER_OBLIQUE;
        else
            iTextFontName = BaseFont.COURIER;
    } else if (typefaceName.equals("HELVETICA")) {
        if (f.bold) {
            if (f.italics)
                iTextFontName = BaseFont.HELVETICA_BOLDOBLIQUE;
            else
                iTextFontName = BaseFont.HELVETICA_BOLD;
        } else if (f.italics)
            iTextFontName = BaseFont.HELVETICA_OBLIQUE;
        else
            iTextFontName = BaseFont.HELVETICA;
    } else if (typefaceName.equals("TIMES_ROMAN")) {
        if (f.bold) {
            if (f.italics)
                iTextFontName = BaseFont.TIMES_BOLDITALIC;
            else
                iTextFontName = BaseFont.TIMES_BOLD;
        } else if (f.italics)
            iTextFontName = BaseFont.TIMES_ITALIC;
        else
            iTextFontName = BaseFont.TIMES_ROMAN;
    } else if (typefaceName.equals("SYMBOL")) {
        iTextFontName = BaseFont.SYMBOL;
    } else if (typefaceName.equals("DINGBATS")) {
        iTextFontName = BaseFont.ZAPFDINGBATS;
    } else
    // not a base14 font. So make sure we've loaded the font files for Platypus
    // then look up this font among them. If it's still not there, then return
    // a TIMES_ROMAN and note the error.
    {
        //            if( htmlData.getTypefaceMap() == null ) {
        //                TypefaceMap typefaceMap = new TypefaceMap( htmlData.getGdd() );
        //                typefaceMap.loadFamilies();
        //                htmlData.setTypefaceMap( typefaceMap );
        //            }

        // if the font files for this typeface/font family have not been previously registered,
        // then get the filenames from the typefaceMap and register them in iText's FontFactory
        if (!FontFactory.isRegistered(typefaceName)) {
            String[] fontFiles = pdfData.getTypefaceMap().getFamilyFilenames(typefaceName);
            for (String fontFile : fontFiles) {
                FontFactory.register(fontFile);
            }
            gdd.log("Registered fonts for " + typefaceName + " in iText");
        }

        if (FontFactory.isRegistered(typefaceName)) {
            iTextFontName = typefaceName;
        } else {
            // the filename does not exist on the system, so substitute TIMES_ROMAN
            iTextFontName = BaseFont.TIMES_ROMAN;
        }
        //            }
        //            else {
        //                gdd.logInfo(
        //                        gdd.getLit( "FILE#" ) + " " + source.getFileNumber() + " " +
        //                        gdd.getLit( "LINE#" ) + " " + source.getLineNumber() + ": " +
        //                        gdd.getLit( "ERROR.INVALID_FONT_TYPEFACE" ) + " " +
        //                        f.typeface + " " +
        //                        gdd.getLit( "IGNORED" ));
        //                iTextFontName = typeface;
    }
    return (iTextFontName);
}

From source file:org.pz.platypus.plugin.pdf.PdfFontFactory.java

License:Open Source License

/**
 * Actual font registration. Takes care of specious warning emitted by iText registering
 * a TrueType collection (.ttc) file// w w  w  . j  a  v  a2 s . c om
 *
 * called from RegisterOneFont()
 *
 * @param fontFile the complete filename including the path
 */
private void registerFont(String fontFile) {
    if (!fontFile.toLowerCase().endsWith(".ttc")) {
        FontFactory.register(fontFile);
        return;
    }

    // if the file is a TrueTypeCollection (.ttc), iText generates an error message
    // which it writes to stderr, and then registers the fonts. Since, there's no way
    // to prevent this unneeded message, we do the registration manually here to avoid
    // printing out the error message (about which the user can do nothing).

    String[] names;

    try {
        names = BaseFont.enumerateTTCNames(fontFile);
        if (names == null) {
            errTtcFileHandling(fontFile);
            return;
        }
    } catch (DocumentException de) {
        errTtcFileHandling(fontFile);
        return;
    } catch (IOException ioe) {
        errTtcFileHandling(fontFile);
        return;
    }

    for (int i = 0; i < names.length; i++) {
        FontFactory.register(fontFile + "," + i);
    }
}

From source file:org.squale.welcom.outils.pdf.PDFFontUtil.java

License:Open Source License

/**
 * Initolisation du repertoire de font pour l'impression
 * /*  w ww.  j  ava 2s.c  om*/
 * @param s Action Servlet pour la fonc
 * @return True si TVB
 */
public static boolean init(final ActionServlet s) {
    pdfFontUtil = new PDFFontUtil(s);
    boolean resultSR = true;
    boolean resultIT = true;

    /*
     * TODO FAB : XReport doit tre sorti car il s'agit d'une lib non OSS try {
     * Class.forName("inetsoft.report.ReportEnv"); inetsoft.report.ReportEnv.setProperty("font.metrics.source",
     * "truetype"); inetsoft.report.ReportEnv.setProperty("font.truetype.path",
     * PDFFontUtil.getRealFontPath().trim()); resultSR = true; } catch (final ClassNotFoundException e) { resultSR =
     * false; }
     */

    try {
        Class.forName("com.lowagie.text.Document");
        final String path = PDFFontUtil.getRealFontPath().trim();
        final File fontDir = new File(path);
        final File[] listFile = fontDir.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(".ttf");
            }
        });
        if (listFile != null) {

            for (int i = 0; i < listFile.length; i++) {

                FontFactory.register(listFile[i].getCanonicalPath());
            }
            if (logger.isDebugEnabled()) {
                for (final Iterator iter = FontFactory.getRegisteredFamilies().iterator(); iter.hasNext();) {
                    final String font = (String) iter.next();

                    logger.debug("registering " + font);

                }
            }
        }

        resultIT = true;
    } catch (final ClassNotFoundException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Erreur lors du chargement des fonts pour itext", e);
        }
        resultIT = false;
    } catch (final IOException ie) {
        if (logger.isDebugEnabled()) {
            logger.debug("Erreur lors du chargement des fonts pour itext", ie);
        }

        resultIT = false;
    }

    return resultSR || resultIT;
}