AS3: Embed font two different fonts with same name - actionscript-3

I'm embedding a font in AS3 with the following command:
[Embed(source="../font/font1.swf", fontName = "FontName1", fontWeight = "bold" )]
private var myEmbeddedFont:Class;
var _tf: TextFormat;
_tf = new TextFormat();
_tf.color = 0x000000;
_tf.size = 18;
_tf.font = "FontName1";
Now I would like to embedd a second font which is the same font but not bold.
My problem now is: Both vonts (the bold one and the non-bold) have the same name.
What can I do to use both fonts? In the embedding-command fontName="" must be the "real" name of the font. Is there some Kind of an alias I can set for the font-name?

you want to use fontFamily and not fontName. Also, why is your font an .swf? here's what I use :
[Embed(source="../font/font1.ttf", embedAsCFF="false", fontFamily="FontName1")]
private static const Font:Class;
[Embed(source="../font/font1_Bd.ttf", embedAsCFF="false", fontFamily="FontName1", fontWeight="bold")]
private static const FontBold:Class;
With that, AS3 should be able to display both normal anf bold text with your font.

There is nothing like you have to set the "Real" name of the font to set, you can use alias for your fonts.
Like :
for ARIEL(normal) : font Name : Ariel
for ARIEL(bold) : font Name : Ariel_Bold

Related

iTextSharp HTML to PDF conversion - unable to change font

I'm creating some PDF documents with iTextSharp (5.5.7.0) from HTML in ASP.NET MVC5 application, but I'm unable to change the font. I've tried almost everything that I was able to find on SO or from some other resources.
Code for PDF generation is as follows:
public Byte[] GetRecordsPdf(RecordsViewModel model)
{
var viewPath = "~/Template/RecordTemplate.cshtml";
var renderedReport = RenderViewToString(viewPath, model);
FontFactory.RegisterDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Fonts));
using (var ms = new MemoryStream())
{
using (var doc = new Document())
{
doc.SetPageSize(PageSize.A4.Rotate());
using (var writer = PdfWriter.GetInstance(doc, ms))
{
doc.Open();
using (var html = new MemoryStream(Encoding.Default.GetBytes(renderedReport)))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, html, Encoding.Default);
}
doc.Close();
}
}
var bytes = ms.ToArray();
return bytes;
}
}
Actual HTML is contained in renderedReport string variable (I have strongly typed .cshtml file which I render using MVC Razor engine and then return HTML in string).
I've tried to register some specific fonts, but that didn't help. I've also tried to register all fonts on my machine (as shown in example above), but that also didn't help. The fonts were loaded I've checked that in debug mode.
CSS is embedded in HTML file (in heading, style tag) like this:
body {
font-size: 7px;
font-family: Comic Sans MS;
}
(for test, I've decided to use Comic Sans, because I can recognize it with ease, I'm more interested in Arial Unicode MS actually).
And I'm actually able to change the font with that font-family attribute from CSS, but only from fonts that are preloaded by iTextSharp by default - Times New Roman, Arial, Courier, and some other (Helvetica i think). When I change it to - Comic Sans, or some other that is not preloaded iTextSharp renders with default font (Arial I would say).
The reason why I need to change the font is because I have some Croatian characters in my rendered HTML (ČĆŠĐŽčćšđž) which are missing from PDF, and currently I think the main reason is - font.
What am I missing?
A couple of things to make this work.
First, XMLWorkerHelper doesn't use FontFactory by default, you need to use one of the overloads to ParseXHtml() that takes an IFontProvider. Both of those overloads require that you specify a Stream for a CSS file but you can just pass null if your CSS lives inside your HTML file. Luckily FontFactory has a static property that implements this that you can use called FontFactory.FontImp
// **This guy**
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHTML, null, Encoding.UTF8, FontFactory.FontImp);
Second, I know that you said that you tried registering your entire font directory out of desperation but that can be a rather expensive call. If you can, always try to just register the fonts you need. Although optional, I also strongly recommend that you explicitly define the font's alias because fonts can have several names and they're not always what we think.
FontFactory.Register(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "comic.ttf"), "Comic Sans MS");
Third, and this might not affect you, but any tags not present in the HTML, even if they're logically implied, won't get styling applied to them from CSS. That sounds weird so to say it differently, if your HTML is just <p>Hello</p> and your CSS is body{font-size: 7px;}, the font size won't get applied because your HTML is missing the <body> tag.
Fourth, and this is optional, but usually its easier to specify your HTML and CSS separately from each other which I'll do in the example below.
Your code was 95% there so with just a couple of tweaks it should work. Instead of a view I'm just parsing raw HTML and CSS but you can modify as needed. Please do remember (and I think you know this) that iTextSharp cannot process ASP.Net, only HTML, so you need to make sure that your ASP.Net to HTML conversion process is sane.
//Sample HTML and CSS
var html = #"<body><p>Sva ljudska bića rađaju se slobodna i jednaka u dostojanstvu i pravima. Ona su obdarena razumom i sviješću i trebaju jedna prema drugima postupati u duhu bratstva.</p></body>";
var css = "body{font-size: 7px; font-family: Comic Sans MS;}";
//Register a single font
FontFactory.Register(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "comic.ttf"), "Comic Sans MS");
//Placeholder variable for later
Byte[] bytes;
using (var ms = new MemoryStream()) {
using (var doc = new Document()) {
doc.SetPageSize(PageSize.A4.Rotate());
using (var writer = PdfWriter.GetInstance(doc, ms)) {
doc.Open();
//Get a stream of our HTML
using (var msHTML = new MemoryStream(Encoding.UTF8.GetBytes(html))) {
//Get a stream of our CSS
using (var msCSS = new MemoryStream(Encoding.UTF8.GetBytes(css))) {
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHTML, msCSS, Encoding.UTF8, FontFactory.FontImp);
}
}
doc.Close();
}
}
bytes = ms.ToArray();
}

Does ITextRenderer support font awesome

I am try to render an pdf from html free marker template, I use font awesome fonts, but when I try to render in pdf, the font is not shown, does itextrenderer support such custom font?
I struggled with this as well, but I figured out that I have to add the font manually to get it working. Here's my code:
def html2Pdf(html: String): Array[Byte] = {
val output: ByteArrayOutputStream = new ByteArrayOutputStream
val renderer: ITextRenderer = new ITextRenderer()
renderer.getFontResolver.addFont("fontawesome-webfont.ttf", BaseFont.IDENTITY_H, true)
renderer.setDocumentFromString(html)
renderer.layout()
renderer.createPDF(output)
renderer.finishPDF()
output.flush()
output.close()
output.toByteArray
}

AS3: Using embedded font

I embed font like this (FlashDevelop):
[ Embed( source = "Ubuntu-R.ttf", embedAsCFF = "false", fontFamily = "Ubuntu" ) ]
private static const Ubuntu : Class;
Then try to use like this:
var textField : TextField = new TextField;
textField.embedFonts = true;
textField.defaultTextFormat = new TextFormat( "Ubuntu", 22 );
textField = "免費旋轉 ПРИВЕТ HELLO";
addChild( textField );
Only russian and english parts of the text visible, but not japanese (my PC is russian). If to comment textField.embedFonts = true; line, then the whole text will be visible, but some other (seems like Arial) font used.
Call to Font.enumerateFonts( false ); returns array with one font called "Ubuntu".
Call to Font.registerFont( Ubuntu ); at any place doesn't help.
Adding parameters fontName, unicodeRange = "U+0000-U+FFFF", mimeType = "application/x-font-truetype", fontWeight, advancedAntiAliasing to the font embed directive with different attributes do not change the behavior.
Seems like dead end, but please help.
The font you use does not contain the required glyphs for Japanese. You might try another font, make sure though it has enough glyphs in there. A hint: if the font isn't as big as 1 megabyte, most likely it has neither japanese nor chinese glyphs, if it's bigger, then try embedding and check with hasGlyphs() if it has enough. Once you'll find the correct font, embed and enjoy. But, I'd say use a font that's widely distributed and has japanese glyphs by design, say Arial.

CycleTile puts a shadow on my images windows phone

I'm trying to make some tasty live tile action for my windows phone 8 app. I've chosen to use the Cycle Tile template for some awesome gliding images but there is a problem: Microsoft seem to have kindly added a grey translucent filter to all the images so that the title text at the bottom is legible even in the case of a white image. This is annoying if the developer intends to make a metro style collage by using WritableBitmap. Whites come out as an off-white grey and the theme colour is a shade darker than all the other tiles:
The code (in a usercontrol in the visual tree):
const double TILE_H = 336;
const double TILE_W = 691;
Size TILE_SIZE = new Size(TILE_W, TILE_H);
const string FILEDIREC = "/Shared/ShellContent";
LayoutRoot.Height = TILE_H;
LayoutRoot.Width = TILE_W;
LayoutRoot.Clip = new RectangleGeometry() { Rect = new Rect(new Point(), TILE_SIZE) };
LayoutRoot.Background = new SolidColorBrush(
((Color)Application.Current.Resources["PhoneAccentColor"]));
TextBlock tb = new TextBlock();
Canvas.SetLeft(tb, 200.0);
tb.Text = "Why is this text grey? + lots more text";
tb.FontSize = 50;
tb.Width = 300;
tb.Foreground = new SolidColorBrush(Colors.White);
tb.TextWrapping = TextWrapping.Wrap;
LayoutRoot.Children.Add(tb);
var bmp = new WriteableBitmap((int)TILE_W, (int)TILE_H);
bmp.Render(LayoutRoot, null);
bmp.Invalidate();
var isf = IsolatedStorageFile.GetUserStoreForApplication();
var filename = FILEDIREC + "/tile.jpg";
if (!isf.DirectoryExists(FILEDIREC))
{
isf.CreateDirectory(FILEDIREC);
}
using (var stream = isf.OpenFile(filename, System.IO.FileMode.OpenOrCreate))
{
bmp.SaveJpeg(stream, (int)TILE_W, (int)TILE_H, 0, 100);
}
imageURIs.Add(new Uri("isostore:" + filename, UriKind.Absolute));
//similar process for other images used by CycleTileData
//these images then added to CycleTileData in the usual way
Any help, explanation, advise or workarounds to get degreying will be greatly appreciated. Thanks. I've tried using the images in different tile types, eg. the front of the flip tile has no issues.
I don't see any obvious issues with the code, but something I would try is to use the Isolated Storage Explorer and download the file and see what it looks like.
When generating custom tiles you may want to consider generating a PNG instead of a JPG. One of the benefits is that you then can generate a transparent image (which means your tile will always have the right theme background color) and PNG also uses a non-lossy compression scheme so there are no compression artifacts introduced.
Take a look at this answer where I describe how I generate tiles in one of my apps. Hopefully that will be of some use to you.

AS3 > Use different text styles (bold and regular) in the same dynamic text field

I've been using as3 for a lot of years but everytime I need to manipulate fonts I get crazy :(
My setup:
I'm filling up via code a movieClip with a lot of dynamic textFields. Their values come from an external XML.
My problem:
my client wants to insert html tags inside of the xml to have bold text in part of them. For example they want to have: "this string with this part bold".
The Xml part is ok, formatted with CDATA and so on. If I trace the value coming from the xml is html, but it is shown as regular text inside the textfield....
The textfields are using client custom font (not system font), and have the font embedded via embedding dialog panel in Flash by the graphic designer.
Any help?
This is the part of code that fills up the textfields (is inside a for loop)
var labelToWrite:String = labelsData.label.(#id == nameOfChildren)[VarHolder.activeLang];
if (labelToWrite != "") {
foundTextField.htmlText = labelToWrite;
// trace ("labelToWrite is -->" +labelToWrite);
}
And the trace outputs me
This should be <b>bold text with b tag</b> and this should be <strong>strong text </strong>.
Your code looks good. So the issue will be with the embedded Font. When you embed a font in flash, it doesn't embed any separate bold versions, so you may need to embed a bold version of your font.
Some resources:
Flash CS4 <b> tag in with htmlText
I find that html text works best by using the style sheets to declare your fonts instead of text formats.
var style:StyleSheet = new StyleSheet();
style.setStyle(".mainFont", { fontFamily: "Verdana", fontSize: 50, color: "#ff0000" } );
var foundTextField:TextField = new TextField();
foundTextField.embedFonts = true;
foundTextField.autoSize = TextFieldAutoSize.LEFT;
foundTextField.antiAliasType = AntiAliasType.ADVANCED;
foundTextField.styleSheet = style;
foundTextField.htmlText = "<div class=\"mainFont\">" + labelToWrite + "</div>";
See: flash as3 xml cdata bold tags rendered in htmlText with an embedded font
Other reasons maybe:
Are you embedding the right type of font (TLF vs CFF)?
If not using the flash IDE to make your textField, are you registering the font?
Font.registerFont(MyFontClass);
You can work with embeded fonts in Animate graphic design. Just add fonts and create them with a class name.
At Adobe Animate objects library you can add and create fonts as class objects like this:
Select a font and styles to add
Assign a name and export as a Action Script Class
At code frame, you must add the fonts with same classes names created before:
var gothamMediumItalic = new GothamMediumItalic();
var formatMediumItalic:TextFormat = new TextFormat();
formatMediumItalic.font = gothamMediumItalic.fontName;
var gothamBookItalic = new GothamBookItalic();
var formatBookItalic:TextFormat = new TextFormat();
formatBookItalic.font = gothamBookItalic.fontName;
var gothamBoldItalic = new GothamBoldItalic();
var formatBoldItalic:TextFormat = new TextFormat();
formatBoldItalic.font = gothamBoldItalic.fontName;
this.embedFonts = true;
this.antiAliasType = AntiAliasType.ADVANCED;
Finally, you just need to use your box added as graphic object, and set format and content:
var yourText:String = "Some Text";
boxText.defaultTextFormat = formatBook; //My default text font style
boxText.text = yourText; //Full text in same format
boxText.setTextFormat(formatBookItalic,yourText.indexOf("<i>"),yourText.indexOf("</i>")); //Some text in another format found by custom chars
That works fine and lets you use less code and more interface options. I hope this could be usefull for someone.