Java 类com.lowagie.text.pdf.BaseFont 实例源码

项目:tifoon    文件:ReportGeneratorServiceImpl.java   
@Override
@Nullable
public byte[] generatePdf(@NonNull final String _html) {
    try {
        final ITextRenderer renderer = new ITextRenderer();
        final ITextFontResolver fontResolver = renderer.getFontResolver();

        final ClassPathResource regular = new ClassPathResource("fonts/LiberationSerif-Regular.ttf");
        fontResolver.addFont(regular.getURL().toString(), BaseFont.IDENTITY_H, true);

        renderer.setDocumentFromString(_html);
        renderer.layout();

        @Cleanup final ByteArrayOutputStream os = new ByteArrayOutputStream();
        renderer.createPDF(os);

        return os.toByteArray();
    } catch(Exception _e) {
        log.error("Failed to generate PDF", _e);
        return null;
    }
}
项目:itext2    文件:Hyphenator.java   
/**
 * @param key
 * @return a hyphenation tree
 */
public static HyphenationTree getResourceHyphenationTree(String key) {
    try {
        InputStream stream = BaseFont.getResourceStream(defaultHyphLocation + key + ".xml");
        if (stream == null && key.length() > 2) {
            stream = BaseFont.getResourceStream(defaultHyphLocation + key.substring(0, 2) + ".xml");
        }
        if (stream == null) {
            return null;
        }
        HyphenationTree hTree = new HyphenationTree();
        hTree.loadSimplePatterns(stream);
        return hTree;
    }
    catch (Exception e) {
        return null;
    }
}
项目:itext2    文件:TrueTypeTest.java   
/**
 * Using a True Type Font.
 */
@Test
public void main() throws Exception {


    // step 1: creation of a document-object
    Document document = new Document();

    // step 2:
    // we create a writer that listens to the document
    // and directs a PDF-stream to a file
    PdfWriter.getInstance(document,PdfTestBase.getOutputStream("truetype.pdf"));

    // step 3: we open the document
    document.open();

    String f = new File(PdfTestBase.RESOURCES_DIR + "liberation-fonts-ttf/LiberationMono-Regular.ttf").getAbsolutePath();
    // step 4: we add content to the document
    BaseFont bfComic = BaseFont.createFont(f, BaseFont.CP1252,  BaseFont.NOT_EMBEDDED);
    Font font = new Font(bfComic, 12);
    String text1 = "This is the quite popular Liberation Mono.";
    document.add(new Paragraph(text1, font));

    // step 5: we close the document
    document.close();
}
项目:itext2    文件:FixedFontWidthTest.java   
/**
 * Changing the width of font glyphs.
 * 
 * @param args
 *            no arguments needed
 */
@Test
public void main() throws Exception {
    // step 1
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    // step 2
    PdfWriter.getInstance(document, PdfTestBase.getOutputStream("fixedfontwidth.pdf"));
    // step 3
    document.open();
    // step 4
    BaseFont bf = BaseFont.createFont("Helvetica", "winansi", false, false, null, null);
    int widths[] = bf.getWidths();
    for (int k = 0; k < widths.length; ++k) {
        if (widths[k] != 0)
            widths[k] = 1000;
    }
    bf.setForceWidthsOutput(true);
    document.add(new Paragraph("A big text to show Helvetica with fixed width.", new Font(bf)));
    // step 5
    document.close();
}
项目:itext2    文件:ListEncodingsTest.java   
/**
 * Listing the encodings of font comic.
 * 
 * @param args
 *            no arguments needed
 */
@Test
public void main() throws Exception {

    File font = new File(PdfTestBase.RESOURCES_DIR + "liberation-fonts-ttf/LiberationMono-Regular.ttf");
    BufferedWriter out = new BufferedWriter(new FileWriter(PdfTestBase.OUTPUT_DIR + "encodings.txt"));
    BaseFont bfComic = BaseFont.createFont(font.getAbsolutePath(), BaseFont.CP1252,
            BaseFont.NOT_EMBEDDED);
    out.write("postscriptname: " + bfComic.getPostscriptFontName());
    out.write("\r\n\r\n");
    String[] codePages = bfComic.getCodePagesSupported();
    out.write("All available encodings:\n\n");
    for (int i = 0; i < codePages.length; i++) {
        out.write(codePages[i]);
        out.write("\r\n");
    }
    out.flush();
    out.close();

}
项目:itext2    文件:FontEncodingTest.java   
/**
    * Specifying an encoding.
    */
@Test
   public void main() throws Exception {


       // step 1: creation of a document-object
       Document document = new Document();


           // step 2: creation of the writer
           PdfWriter.getInstance(document, PdfTestBase.getOutputStream("fontencoding.pdf"));

           // step 3: we open the document
           document.open();

           // step 4: we add content to the document
           BaseFont helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
           Font font = new Font(helvetica, 12, Font.NORMAL);
           Chunk chunk = new Chunk("Sponsor this example and send me 1\u20ac. These are some special characters: \u0152\u0153\u0160\u0161\u0178\u017D\u0192\u02DC\u2020\u2021\u2030", font);
           document.add(chunk);

       // step 5: we close the document
       document.close();
   }
项目:itext2    文件:FullFontNamesTest.java   
/**
 * Retrieving the full font name
 */
@Test
public void main() throws Exception {


    File font = new File(PdfTestBase.RESOURCES_DIR + "liberation-fonts-ttf/LiberationMono-Regular.ttf");
    BufferedWriter out = new BufferedWriter(new FileWriter(PdfTestBase.OUTPUT_DIR
            + "fullfontname_liberationmono.txt"));
    BaseFont bf = BaseFont.createFont(font.getAbsolutePath(), "winansi", BaseFont.NOT_EMBEDDED);
    out.write("postscriptname: " + bf.getPostscriptFontName());
    out.write("\r\n\r\n");
    String names[][] = bf.getFullFontName();
    out.write("\n\nListing the full font name:\n\n");
    for (int k = 0; k < names.length; ++k) {
        if (names[k][0].equals("3") && names[k][1].equals("1")) {
             // Microsoftencoding
            out.write(names[k][3] + "\r\n");
        }
    }
    out.flush();
    out.close();

}
项目:itext2    文件:OpenTypeFontTest.java   
/**
 * Using oth
 */
@Test
public void main() throws Exception {
    // step 1
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    // step 2
    PdfWriter.getInstance(document,
            PdfTestBase.getOutputStream("opentypefont.pdf"));
    // step 3
    document.open();
    // step 4
    BaseFont bf = BaseFont.createFont(PdfTestBase.RESOURCES_DIR
            + "liz.otf", BaseFont.CP1252, true);
    String text = "Some text with the otf font LIZ.";
    document.add(new Paragraph(text, new Font(bf, 14)));
    // step 5
    document.close();
}
项目:OSCAR-ConCert    文件:OscarChartPrinter.java   
public OscarChartPrinter(HttpServletRequest request, OutputStream os) throws DocumentException,IOException {
    this.request = request;
    this.os = os;

    document = new Document();
    // writer = PdfWriterFactory.newInstance(document, os, FontSettings.HELVETICA_10PT);

    writer = PdfWriter.getInstance(document,os);
    writer.setPageEvent(new EndPage());
    document.setPageSize(PageSize.LETTER);
    document.open();
    //Create the font we are going to print to
       bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
       font = new Font(bf, FONTSIZE, Font.NORMAL);
       boldFont = new Font(bf,FONTSIZE,Font.BOLD);
}
项目:OSCAR-ConCert    文件:PdfRecordPrinter.java   
public PdfRecordPrinter(HttpServletRequest request, OutputStream os) throws DocumentException,IOException {
    this.request = request;
    this.os = os;
    formatter = new SimpleDateFormat("dd-MMM-yyyy");

    //Create the font we are going to print to
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    font = new Font(bf, FONTSIZE, Font.NORMAL);
    boldFont = new Font(bf,FONTSIZE,Font.BOLD);

    //Create the document we are going to write to
    document = new Document();
    writer = PdfWriter.getInstance(document,os);
    writer.setPageEvent(new EndPage());
    writer.setStrictImageSequence(true);

    document.setPageSize(PageSize.LETTER);

    document.open();
}
项目:OSCAR-ConCert    文件:PdfRecordPrinter.java   
public void start() throws DocumentException,IOException {
    //Create the font we are going to print to
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    font = new Font(bf, FONTSIZE, Font.NORMAL);
    boldFont = new Font(bf,FONTSIZE,Font.BOLD);

    //Create the document we are going to write to
    document = new Document();
    writer = PdfWriterFactory.newInstance(document, os, FontSettings.HELVETICA_10PT);
    // writer = PdfWriter.getInstance(document,os);
    // writer.setPageEvent(new EndPage());
    writer.setStrictImageSequence(true);

    document.setPageSize(PageSize.LETTER);
    document.open();
}
项目:OSCAR-ConCert    文件:PDFController.java   
private void setPageNumbers() throws DocumentException, IOException {       

    int pages = getReader().getNumberOfPages();
    int i = 0;  
    PdfContentByte overContent;
    Rectangle pageSize = null;
    BaseFont font = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

    while (i < pages) {
        i++;
        overContent = getStamper().getOverContent(i);
        pageSize = overContent.getPdfDocument().getPageSize();
        overContent.beginText();
        overContent.setFontAndSize(font, 9);
        overContent.setTextMatrix(pageSize.getWidth() - 50, pageSize.getHeight() - 70);
        overContent.showText("Page " + i + " of " + pages);
        overContent.endText();
    }
}
项目:OSCAR-ConCert    文件:ConsultationPDFCreator.java   
/**
 * Prints the consultation request.
 * @throws IOException when an error with the output stream occurs
 * @throws DocumentException when an error in document construction occurs
 */
public void printPdf(LoggedInInfo loggedInInfo) throws IOException, DocumentException {

    // Create the document we are going to write to
    document = new Document();
    // PdfWriter.getInstance(document, os);
    PdfWriterFactory.newInstance(document, os, FontSettings.HELVETICA_10PT);

    document.setPageSize(PageSize.LETTER);
    document.addTitle(getResource("msgConsReq"));
    document.addCreator("OSCAR");
    document.open();

    // Create the fonts that we are going to use
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252,
            BaseFont.NOT_EMBEDDED);
    headerFont = new Font(bf, 14, Font.BOLD);
    infoFont = new Font(bf, 12, Font.NORMAL);
    font = new Font(bf, 9, Font.NORMAL);
    boldFont = new Font(bf, 10, Font.BOLD);
    bigBoldFont = new Font(bf, 12, Font.BOLD);

    createConsultationRequest(loggedInInfo);

    document.close();
}
项目:BJAF3.x    文件:GenPdfController.java   
public void createContent(WebInput wi, DocInfo di)throws ControllerException {
    Document pdfDoc = di.getPdfDocument();
    try {
        pdfDoc.add(new Paragraph("Hello World!"));
        try {
            BaseFont bf = BaseFont.createFont("STSong-Light",
                    "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font FontChinese = new Font(bf, 12, Font.NORMAL);
            String info=wi.getParameter("info");
            Paragraph p0 = new Paragraph(info, FontChinese);
            pdfDoc.add(p0);
            Paragraph p1 = new Paragraph("Beetle Web Framework 页面生成PDF文件演示!", FontChinese);
            pdfDoc.add(p1);
        } catch (Exception ex1) {
            throw new ControllerException(ex1);
        }
    } catch (DocumentException ex) {
        throw new ControllerException(ex);
    }
}
项目:sakai    文件:SpreadsheetDataFileWriterPdf.java   
private static void initFont() {
    String fontName = ServerConfigurationService.getString("pdf.default.font");
    if (StringUtils.isNotBlank(fontName)) {
        FontFactory.registerDirectories();
        if (FontFactory.isRegistered(fontName)) {
            font = FontFactory.getFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            boldFont = FontFactory.getFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10, Font.BOLD);
        } else {
            log.warn("Can not find font: " + fontName);
        }
    }
    if (font == null) {
        font = new Font();
        boldFont = new Font(Font.COURIER, 10, Font.BOLD);
    }
}
项目:openbd-core    文件:cfDOCUMENT.java   
private void resolveFonts( cfSession _Session, ITextRenderer _renderer ) throws dataNotSupportedException, cfmRunTimeException{
    ITextFontResolver resolver = _renderer.getFontResolver();

    boolean embed = getDynamic( _Session, "FONTEMBED" ).getBoolean();
    for ( int i = 0; i < defaultFontDirs.length; i++ ){
        File nextFontDir = new File( defaultFontDirs[i] );
        File[] fontFiles = nextFontDir.listFiles( new FilenameFilter() {
            public boolean accept( File _dir, String _name ){
                String name = _name.toLowerCase();
                return name.endsWith( ".otf" ) || name.endsWith( ".ttf" );
            }
     });
        if ( fontFiles != null ){
      for ( int f = 0; f < fontFiles.length; f++ ){
        try{
            resolver.addFont( fontFiles[f].getAbsolutePath(), BaseFont.IDENTITY_H,
              embed );
        }catch( Exception ignored ){} // ignore fonts that can't be added
      }
        }
    }
}
项目:OLE-INST    文件:BulkReceivingPdf.java   
/**
 * Overrides the method in PdfPageEventHelper from itext to create and set the headerTable and set its logo image if
 * there is a logoImage to be used, creates and sets the nestedHeaderTable and its content.
 *
 * @param writer   The PdfWriter for this document.
 * @param document The document.
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onOpenDocument(PdfWriter writer, Document document) {
    try {

        loadHeaderTable();

        // initialization of the template
        tpl = writer.getDirectContent().createTemplate(100, 100);

        // initialization of the font
        helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);

    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}
项目:convertJob    文件:ConvertJob.java   
public static void txtToPdf(InputStream is, File fileOut) throws Exception{
    Document doc = new Document();
    FileOutputStream out = new FileOutputStream(fileOut);
    PdfWriter.getInstance(doc, out);
    BaseFont bfHei = BaseFont.createFont(FONT_PATH, BaseFont.IDENTITY_H,
            BaseFont.NOT_EMBEDDED);
    Font font = new Font(bfHei, 12);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    String content = null;
    StringBuffer bu = new StringBuffer();
    doc.open();
    while ((content = reader.readLine()) != null) {
        bu.append(content);
    }
    Paragraph text = new Paragraph(bu.toString(), font);
    doc.add(text);
    doc.close();
    reader.close();
    if (is != null)
        is.close();
}
项目:kfs    文件:BulkReceivingPdf.java   
/**
 * Overrides the method in PdfPageEventHelper from itext to create and set the headerTable and set its logo image if 
 * there is a logoImage to be used, creates and sets the nestedHeaderTable and its content.
 * 
 * @param writer    The PdfWriter for this document.
 * @param document  The document.
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document)
 */
public void onOpenDocument(PdfWriter writer, Document document) {
    try {

        loadHeaderTable();

        // initialization of the template
        tpl = writer.getDirectContent().createTemplate(100, 100);

        // initialization of the font
        helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);

    }catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}
项目:sakai    文件:SpreadsheetDataFileWriterPdf.java   
private static void initFont() {
    String fontName = ServerConfigurationService.getString("pdf.default.font");
    if (StringUtils.isNotBlank(fontName)) {
        FontFactory.registerDirectories();
        if (FontFactory.isRegistered(fontName)) {
            font = FontFactory.getFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            boldFont = FontFactory.getFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10, Font.BOLD);
        } else {
            log.warn("Can not find font: " + fontName);
        }
    }
    if (font == null) {
        font = new Font();
        boldFont = new Font(Font.COURIER, 10, Font.BOLD);
    }
}
项目:birt    文件:FontHandler.java   
/**
 * Selects a proper font for a character.
 * 
 * @return true: we find a font which can be used to display the character.
 *         false: no font can display the character.
 */
public boolean selectFont( char character )
{
    assert ( fontManager != null );
    // FIXME: code review : return null when no mapped font defined the
    // character so that charExist only need to be invoked once.
    BaseFont candidateFont = getMappedFont( character );
    assert ( candidateFont != null );
    if ( bf == candidateFont )
    {
        isFontChanged = false;
    }
    else
    {
        isFontChanged = true;
        bf = candidateFont;
        simulation = needSimulate( bf );
    }
    return candidateFont.charExists( character );
}
项目:PDFTestForAndroid    文件:FixedFontWidth.java   
/**
 * Changing the width of font glyphs.
 * 
 * @param args
 *            no arguments needed
 */
public static void main(String[] args) {
    System.out.println("Fixed Font Width");
    // step 1
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    try {
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "fixedfontwidth.pdf"));
        // step 3
        document.open();
        // step 4
        BaseFont bf = BaseFont.createFont("Helvetica", "winansi", false, false, null, null);
        int widths[] = bf.getWidths();
        for (int k = 0; k < widths.length; ++k) {
            if (widths[k] != 0)
                widths[k] = 1000;
        }
        bf.setForceWidthsOutput(true);
        document.add(new Paragraph("A big text to show Helvetica with fixed width.", new Font(bf)));
    } catch (Exception de) {
        de.printStackTrace();
    }
    // step 5
    document.close();
}
项目:PDFTestForAndroid    文件:OpenTypeFont.java   
/**
     * Using oth
     * 
     * @param args
     *            no arguments needed
     */
    public static void main(String[] args) {
        // step 1
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        try {
            // step 2
            PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "opentypefont.pdf"));
            // step 3
            document.open();
            // step 4
            //Don't use path read ttf into byte[] instead
//          BaseFont bf = BaseFont.createFont("liz.otf", BaseFont.CP1252, true);
            InputStream inputStream = PdfTestRunner.getActivity().getResources().openRawResource(R.raw.liz);
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            BaseFont bf = BaseFont.createFont("freesans.ttf", BaseFont.CP1252, true, false, buffer, null);
            String text = "Some text with the otf font LIZ.";
            document.add(new Paragraph(text, new Font(bf, 14)));
        } catch (Exception de) {
            de.printStackTrace();
        }
        // step 5
        document.close();
    }
项目:yarg    文件:HtmlFormatter.java   
protected void loadFontsFromDirectory(ITextRenderer renderer, File fontsDir) {
    if (fontsDir.exists()) {
        if (fontsDir.isDirectory()) {
            File[] files = fontsDir.listFiles((dir, name) -> {
                String lower = name.toLowerCase();
                return lower.endsWith(".otf") || lower.endsWith(".ttf");
            });
            for (File file : files) {
                try {
                    // Usage of some fonts may be not permitted
                    renderer.getFontResolver().addFont(file.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                } catch (IOException | DocumentException e) {
                    if (StringUtils.contains(e.getMessage(), "cannot be embedded due to licensing restrictions")) {
                        e.printStackTrace();//todo log message
                    } else {
                        e.printStackTrace();//todo log message
                    }
                }
            }
        } else {
            //todo log message
        }
    } else {
        //todo log message
    }
}
项目:us-check-printing    文件:CheckPdfRenderer.java   
private BaseFont createFixedFont() throws Exception {

    boolean cached = true;
    byte[] ttf;
    {
        InputStream in = CheckPdfRenderer.class.getResourceAsStream("/com/moss/check/us/VeraMono.ttf");
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024 * 10]; //10k buffer
        for(int numRead = in.read(buffer); numRead!=-1; numRead = in.read(buffer)){
            out.write(buffer, 0, numRead);
        }

        ttf = out.toByteArray();
    }
    byte[] pfb = null; 
    boolean noThrow = false;

    BaseFont baseFont = BaseFont.createFont("VeraMono.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, cached, ttf, pfb, noThrow);

    return baseFont;
}
项目:geomajas-project-server    文件:PdfContext.java   
/**
 * Draw text in the center of the specified box.
 *
 * @param text text
 * @param font font
 * @param box box to put text int
 * @param fontColor colour
 */
public void drawText(String text, Font font, Rectangle box, Color fontColor) {
    template.saveState();
    // get the font
    DefaultFontMapper mapper = new DefaultFontMapper();
    BaseFont bf = mapper.awtToPdf(font);
    template.setFontAndSize(bf, font.getSize());

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

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

    // draw text if necessary
    template.setColorFill(fontColor);
    template.beginText();
    template.showTextAligned(PdfContentByte.ALIGN_LEFT, text, origX + box.getLeft() + 0.5f
            * (box.getWidth() - fit.getWidth()), origY + box.getBottom() + 0.5f
            * (box.getHeight() - fit.getHeight()) - descent, 0);
    template.endText();
    template.restoreState();
}
项目:orbeon-forms    文件:XHTMLToPDFProcessor.java   
public static void embedFonts(ITextRenderer renderer) {
    final PropertySet propertySet = Properties.instance().getPropertySet();
    for (final String propertyName : propertySet.getPropertiesStartsWith("oxf.fr.pdf.font.path")) {
        final String path = StringUtils.trimToNull(propertySet.getString(propertyName));
        if (path != null) {
            try {
                // Overriding the font family is optional
                final String family; {
                    final String[] tokens = StringUtils.split(propertyName, '.');
                    if (tokens.length >= 6) {
                        final String id = tokens[5];
                        family = StringUtils.trimToNull(propertySet.getString("oxf.fr.pdf.font.family" + '.' + id));
                    } else {
                        family = null;
                    }
                }

                // Add the font
                renderer.getFontResolver().addFont(path, family, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, null);
            } catch (Exception e) {
                logger.warn("Failed to load font by path: '" + path + "' specified with property '"  + propertyName + "'");
            }
        }
    }
}
项目:us-check-printing    文件:CheckPdfRenderer.java   
private BaseFont createMicrFont() throws Exception {

    boolean cached = true;
    byte[] ttf;
    {
        InputStream in = CheckPdfRenderer.class.getResourceAsStream("/com/moss/check/us/GnuMICR.ttf");
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024 * 10]; //10k buffer
        for(int numRead = in.read(buffer); numRead!=-1; numRead = in.read(buffer)){
            out.write(buffer, 0, numRead);
        }

        ttf = out.toByteArray();
    }
    byte[] pfb = null; 
    boolean noThrow = false;

    BaseFont baseFont = BaseFont.createFont("GnuMICR.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED, cached, ttf, pfb, noThrow);

    return baseFont;
}
项目:unitimes    文件:PdfTimetableGridTable.java   
public void addTextVertical(PdfPCell cell, String text, boolean bold) throws Exception  {
    if (text==null) return;
       if (text.indexOf("<span")>=0)
           text = text.replaceAll("</span>","").replaceAll("<span .*>", "");
       Font font = PdfFont.getFont(bold);
    BaseFont bf = font.getBaseFont();
    float width = bf.getWidthPoint(text, font.getSize());
    PdfTemplate template = iWriter.getDirectContent().createTemplate(2 * font.getSize() + 4, width);
    template.beginText();
    template.setColorFill(Color.BLACK);
    template.setFontAndSize(bf, font.getSize());
    template.setTextMatrix(0, 2);
    template.showText(text);
    template.endText();
    template.setWidth(width);
    template.setHeight(font.getSize() + 2);
    //make an Image object from the template
    Image img = Image.getInstance(template);
    img.setRotationDegrees(270);
    //embed the image in a Chunk
    Chunk ck = new Chunk(img, 0, 0);

    if (cell.getPhrase()==null) {
        cell.setPhrase(new Paragraph(ck));
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
    } else {
        cell.getPhrase().add(ck);
    }
}
项目:itext2    文件:FactoryProperties.java   
public Font getFont(ChainedProperties props) {
    String face = props.getProperty(ElementTags.FACE);
    if (face != null) {
        StringTokenizer tok = new StringTokenizer(face, ",");
        while (tok.hasMoreTokens()) {
            face = tok.nextToken().trim();
            if (face.startsWith("\""))
                face = face.substring(1);
            if (face.endsWith("\""))
                face = face.substring(0, face.length() - 1);
            if (fontImp.isRegistered(face))
                break;
        }
    }
    int style = 0;
    if (props.hasProperty(HtmlTags.I))
        style |= Font.ITALIC;
    if (props.hasProperty(HtmlTags.B))
        style |= Font.BOLD;
    if (props.hasProperty(HtmlTags.U))
        style |= Font.UNDERLINE;
    if (props.hasProperty(HtmlTags.S))
        style |= Font.STRIKETHRU;
    String value = props.getProperty(ElementTags.SIZE);
    float size = 12;
    if (value != null)
        size = Float.parseFloat(value);
    Color color = Markup.decodeColor(props.getProperty("color"));
    String encoding = props.getProperty("encoding");
    if (encoding == null)
        encoding = BaseFont.WINANSI;
    return fontImp.getFont(face, encoding, true, size, style, color);
}
项目:itext2    文件:EventsTest.java   
/**
 * The first thing to do when the document is opened, is to define the
 * BaseFont, get the Direct Content object and create the template that
 * will hold the final number of pages.
 * 
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter,
 *      com.lowagie.text.Document)
 */
public void onOpenDocument(PdfWriter writer, Document document) {
    try {
        bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252,
                BaseFont.NOT_EMBEDDED);
        cb = writer.getDirectContent();
        template = cb.createTemplate(50, 50);
    } catch (DocumentException de) {
    } catch (IOException ioe) {
    }
}
项目:itext2    文件:ShadingPatternTest.java   
/**
 * Shading example.
 */
@Test
public void main() throws Exception {
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    PdfWriter writer = PdfWriter.getInstance(document,
            PdfTestBase.getOutputStream("shading_pattern.pdf"));
    document.open();

    PdfShading shading = PdfShading.simpleAxial(writer, 100, 100, 400, 100,
            Color.red, Color.cyan);
    PdfShadingPattern shadingPattern = new PdfShadingPattern(shading);
    PdfContentByte cb = writer.getDirectContent();
    BaseFont bf = BaseFont.createFont(BaseFont.TIMES_BOLD,
            BaseFont.WINANSI, false);
    cb.setShadingFill(shadingPattern);
    cb.beginText();
    cb.setTextMatrix(100, 100);
    cb.setFontAndSize(bf, 40);
    cb.showText("Look at this text!");
    cb.endText();
    PdfShading shadingR = PdfShading.simpleRadial(writer, 200, 500, 50,
            300, 500, 100, new Color(255, 247, 148), new Color(247, 138,
                    107), false, false);
    cb.paintShading(shadingR);
    cb.sanityCheck();
    document.close();

}
项目:itext2    文件:VerticalTest.java   
/**
 * Writing vertical text.
 */
@Test
public void main() throws Exception {
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    texts[3] = convertCid(texts[0]);
    texts[4] = convertCid(texts[1]);
    texts[5] = convertCid(texts[2]);
    PdfWriter writer = PdfWriter.getInstance(document,PdfTestBase.getOutputStream("vertical.pdf"));
    int idx = 0;
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    for (int j = 0; j < 2; ++j) {
        BaseFont bf = BaseFont.createFont("KozMinPro-Regular", encs[j], false);
        cb.setRGBColorStroke(255, 0, 0);
        cb.setLineWidth(0);
        float x = 400;
        float y = 700;
        float height = 400;
        float leading = 30;
        int maxLines = 6;
        for (int k = 0; k < maxLines; ++k) {
            cb.moveTo(x - k * leading, y);
            cb.lineTo(x - k * leading, y - height);
        }
        cb.rectangle(x, y, -leading * (maxLines - 1), -height);
        cb.stroke();
        VerticalText vt = new VerticalText(cb);
        vt.setVerticalLayout(x, y, height, maxLines, leading);
        vt.addText(new Chunk(texts[idx++], new Font(bf, 20)));
        vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.blue)));
        vt.go();
        vt.setAlignment(Element.ALIGN_RIGHT);
        vt.addText(new Chunk(texts[idx++],  new Font(bf, 20, 0, Color.orange)));
        vt.go();
        document.newPage();
    }
    document.close();

}
项目:itext2    文件:UnicodeExampleTest.java   
/**
    * Embedding True Type Fonts.
    * @param args no arguments needed
    */
@Test
public void main() throws Exception {


    // step 1: creation of a document-object
    Document document = new Document();

    // step 2: creation of the writer-object
    PdfWriter.getInstance(document, PdfTestBase.getOutputStream("unicode.pdf"));

    // step 3: we open the document
    document.open();
    File fontPath = new File(PdfTestBase.RESOURCES_DIR + "liberation-fonts-ttf/LiberationMono-Regular.ttf");
    // step 4: we add content to the document
    BaseFont bfComic = BaseFont.createFont(fontPath.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    Font font = new Font(bfComic, 12);
    String text1 = "This is the quite popular True Type font 'Liberation Mono'.";
    String text2 = "Some greek characters: \u0393\u0394\u03b6";
    String text3 = "Some cyrillic characters: \u0418\u044f";
    document.add(new Paragraph(text1, font));
    document.add(new Paragraph(text2, font));
    document.add(new Paragraph(text3, font));

    // step 5: we close the document
    document.close();
}
项目:itext2    文件:TrueTypeTest.java   
/**
 * Embedding True Type Fonts.
 */
@Test
public void main() throws Exception {



    // step 1: creation of a document-object
    Document document = new Document();

    // step 2:
    // we create a writer that listens to the document
    // and directs a PDF-stream to a file
    PdfWriter.getInstance(document, PdfTestBase.getOutputStream( "truetype.pdf"));

    // step 3: we open the document
    document.open();

    // step 4: we add content to the document
    BaseFont bfComic = BaseFont.createFont(PdfTestBase.RESOURCES_DIR + "/liberation-fonts-ttf/LiberationSans-Regular.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    Font font = new Font(bfComic, 12);
    String text1 = "This is the quite popular True Type font 'LiberationSans'.";
    String text2 = "Some greek characters: \u0393\u0394\u03b6";
    String text3 = "Some cyrillic characters: \u0418\u044f";
    document.add(new Paragraph(text1, font));
    document.add(new Paragraph(text2, font));
    document.add(new Paragraph(text3, font));

    // step 5: we close the document
    document.close();
}
项目:itext2    文件:TrueTypeCollectionsTest.java   
/**
 * Using true type collections.
 * 
 * @param args
 *            no arguments needed
 */
@Test
public void main() throws Exception {

    // TODO multiplatform test
    if (!Executable.isWindows()){
        return;
    }
    // step 1: creation of a document-object
    Document document = new Document();

    BufferedWriter out = new BufferedWriter(new FileWriter(PdfTestBase.OUTPUT_DIR + "msgothic.txt"));
    String[] names = BaseFont.enumerateTTCNames("c:\\windows\\fonts\\msgothic.ttc");
    for (int i = 0; i < names.length; i++) {
        out.write("font " + i + ": " + names[i]);
        out.write("\r\n");
    }
    out.flush();
    out.close();
    // step 2: creation of the writer
    PdfWriter.getInstance(document, PdfTestBase.getOutputStream("truetypecollections.pdf"));

    // step 3: we open the document
    document.open();

    // step 4: we add content to the document
    BaseFont bf = BaseFont.createFont("c:\\windows\\fonts\\msgothic.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

    Font font = new Font(bf, 16);
    String text1 = "\u5951\u7d04\u8005\u4f4f\u6240\u30e9\u30a4\u30f3\uff11";
    String text2 = "\u5951\u7d04\u8005\u96fb\u8a71\u756a\u53f7";
    document.add(new Paragraph(text1, font));
    document.add(new Paragraph(text2, font));

    // step 5: we close the document
    document.close();
}
项目:sistra    文件:PDFDocument.java   
public void onOpenDocument(PdfWriter writer, Document document) {
    if (paginar) {
        tplTotal = writer.getDirectContent().createTemplate(100, 100);
        tplTotal.setBoundingBox(new Rectangle(-20, -20, 100, 100));
        try {
            bFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            throw new ExceptionConverter(e);
        }
    }
}
项目:OSCAR-ConCert    文件:TicklerPrinter.java   
public void start() throws DocumentException, IOException {
    //Create the font we are going to print to
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    font = new Font(bf, FONTSIZE, Font.NORMAL);
    boldFont = new Font(bf, FONTSIZE, Font.BOLD);

    document = new Document();
    writer = PdfWriterFactory.newInstance(document, os, FontSettings.HELVETICA_10PT);
    writer.setStrictImageSequence(true);

    document.setPageSize(PageSize.LETTER);
    document.open();
}
项目:OSCAR-ConCert    文件:FontSettings.java   
/**
 * Creates the specified font encapsulated by this instance
 * 
 * @return
 *      Returns new base font instance
 */
public BaseFont createFont() {
    try {
        return BaseFont.createFont(getFont(), getCodePage(), isEmbedded());
    } catch (Exception e) {
        throw new RuntimeException("Unable to create font", e);
    }
}
项目:OSCAR-ConCert    文件:LabPDFCreator.java   
public void printRtf()throws IOException, DocumentException{
    //create an input stream from the rtf string bytes
    byte[] rtfBytes = handler.getOBXResult(0, 0).getBytes();
    ByteArrayInputStream rtfStream = new ByteArrayInputStream(rtfBytes);

    //create & open the document we are going to write to and its writer
    document = new Document();
    RtfWriter2 writer = RtfWriter2.getInstance(document,os);
    document.setPageSize(PageSize.LETTER);
    document.addTitle("Title of the Document");
    document.addCreator("OSCAR");
    document.open();

    //Create the fonts that we are going to use
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    font = new Font(bf, 11, Font.NORMAL);
    boldFont = new Font(bf, 12, Font.BOLD);
 //   redFont = new Font(bf, 11, Font.NORMAL, Color.RED);

    //add the patient information
    addRtfPatientInfo();

    //add the results
    writer.importRtfDocument(rtfStream, null);

    document.close();
    os.flush();
}