Exporting a TextFlow object in Flex 4

The following example shows how you can export a TextFlow object in Flex 4 by using the TextConverter class (flashx.textLayout.conversion.TextConverter), and specifying HTML format, plain text format, or Text Layout Format.

Full code after the jump.

The following example(s) require Flash Player 10 and the Adobe Flex 4 SDK. To download the Adobe Flash Builder 4 trial, see www.adobe.com/products/flex/. To download the latest nightly build of the Flex 4 SDK, see opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4.

For more information on getting started with Flex 4 and Flash Builder 4, see the official Adobe Flex Team blog.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/07/25/exporting-a-textflow-object-in-flex-4/ -->
<s:Application name="Spark_TextConverter_export_test"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/halo"
        xmlns:comps="comps.*">
    <s:layout>
        <s:VerticalLayout paddingLeft="20" paddingRight="20"
                paddingTop="20" paddingBottom="20" />
    </s:layout>
 
    <fx:Script>
        <![CDATA[
            import flashx.textLayout.conversion.ConversionType;
            import flashx.textLayout.conversion.TextConverter;
        ]]>
    </fx:Script>
 
    <comps:CustomEditor id="customEditor" />
 
    <s:HGroup>
        <s:Button id="htmlBtn"
                label="Export as HTML"
                click="debug.text = TextConverter.export(customEditor.editor.textFlow,
                                        TextConverter.HTML_FORMAT,
                                        ConversionType.STRING_TYPE).toString();" />
        <s:Button id="plainTxtBtn"
                label="Export as plain text"
                click="debug.text = TextConverter.export(customEditor.editor.textFlow,
                                        TextConverter.PLAIN_TEXT_FORMAT,
                                        ConversionType.STRING_TYPE).toString();" />
        <s:Button id="tlfBtn"
                label="Export as TLF"
                click="debug.text = TextConverter.export(customEditor.editor.textFlow,
                                        TextConverter.TEXT_LAYOUT_FORMAT,
                                        ConversionType.STRING_TYPE).toString();" />
    </s:HGroup>
 
    <s:TextArea id="debug" width="100%" height="100%" />
 
</s:Application>

View source is enabled in the following example.

And the custom rich text editor component, comps/CustomEditor.mxml, is as follows:

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/07/25/exporting-a-textflow-object-in-flex-4/ -->
<s:Panel name="CustomEditor"
         xmlns:fx="http://ns.adobe.com/mxml/2009"
         xmlns:s="library://ns.adobe.com/flex/spark"
         xmlns:mx="library://ns.adobe.com/flex/halo"
        title="SimpleTextEditor" minWidth="400">
    <s:layout>
        <s:VerticalLayout gap="0" />
    </s:layout>
 
    <fx:Script>
        <![CDATA[
            import flashx.textLayout.conversion.ConversionType;
            import flashx.textLayout.conversion.TextConverter;
            import flash.text.engine.FontPosture;
            import flash.text.engine.FontWeight;
            import flashx.textLayout.formats.TextAlign;
            import flashx.textLayout.formats.TextDecoration;
            import flashx.textLayout.formats.TextLayoutFormat;
            import mx.events.ColorPickerEvent;
            import mx.events.FlexEvent;
            import spark.events.IndexChangeEvent;
 
            protected function editor_selectionChangeHandler(evt:FlexEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                fontDDL.selectedItem = txtLayFmt.fontFamily;
                sizeDDL.selectedItem = txtLayFmt.fontSize;
                boldBtn.selected = (txtLayFmt.fontWeight == FontWeight.BOLD);
                italBtn.selected = (txtLayFmt.fontStyle == FontPosture.ITALIC);
                underBtn.selected = (txtLayFmt.textDecoration == TextDecoration.UNDERLINE);
                colorCP.selectedColor = txtLayFmt.color;
                lineBtn.selected = txtLayFmt.lineThrough;
 
                switch (txtLayFmt.textAlign) {
                    case TextAlign.LEFT:
                        txtAlignBB.selectedIndex = 0;
                        break;
                    case TextAlign.CENTER:
                        txtAlignBB.selectedIndex = 1;
                        break;
                    case TextAlign.RIGHT:
                        txtAlignBB.selectedIndex = 2;
                        break;
                    case TextAlign.JUSTIFY:
                        txtAlignBB.selectedIndex = 3;
                        break;
                    default:
                        txtAlignBB.selectedIndex = -1;
                        break;
                }
            }
 
            protected function fontDDL_changeHandler(evt:IndexChangeEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.fontFamily = fontDDL.selectedItem;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function sizeDDL_changeHandler(evt:IndexChangeEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.fontSize = sizeDDL.selectedItem;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function boldBtn_clickHandler(evt:MouseEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.fontWeight = (txtLayFmt.fontWeight == FontWeight.BOLD) ? FontWeight.NORMAL : FontWeight.BOLD;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function italBtn_clickHandler(evt:MouseEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.fontStyle = (txtLayFmt.fontStyle == FontPosture.ITALIC) ? FontPosture.NORMAL : FontPosture.ITALIC;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function underBtn_clickHandler(evt:MouseEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.textDecoration = (txtLayFmt.fontStyle == TextDecoration.UNDERLINE) ? TextDecoration.NONE : TextDecoration.UNDERLINE;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function colorCP_changeHandler(evt:ColorPickerEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.color = colorCP.selectedColor;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
 
            protected function txtAlignBB_changeHandler(evt:IndexChangeEvent):void {
                if (txtAlignBB.selectedItem) {
                    var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                        editor.selectionAnchorPosition,
                                        editor.selectionActivePosition);
                    txtLayFmt.textAlign = txtAlignBB.selectedItem.value;
                    editor.setFormatOfRange(txtLayFmt,
                                        editor.selectionAnchorPosition,
                                        editor.selectionActivePosition);
                    editor.setFocus();
                }
            }
 
            protected function lineBtn_clickHandler(evt:MouseEvent):void {
                var txtLayFmt:TextLayoutFormat = editor.getFormatOfRange(null,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                txtLayFmt.lineThrough = lineBtn.selected;
                editor.setFormatOfRange(txtLayFmt,
                                    editor.selectionAnchorPosition,
                                    editor.selectionActivePosition);
                editor.setFocus();
            }
        ]]>
    </fx:Script>
 
    <s:TextArea id="editor"
            focusEnabled="false"
            width="100%" height="100%"
            minHeight="200"
            selectionChange="editor_selectionChangeHandler(event);">
        <s:textFlow>
            <s:TextFlow paragraphSpaceBefore="20">
                <s:p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis et nibh lorem. Nulla ut velit magna. Nunc quis libero ac orci porta tincidunt eget in lorem. Aenean vitae nisi vitae urna lacinia congue. Duis nec leo turpis. Phasellus dui orci, lacinia in dictum lacinia, ullamcorper a tortor. Suspendisse lacinia, turpis vel euismod gravida, turpis dui vulputate libero, vel consequat enim sem nec mauris. Curabitur vitae magna vel neque accumsan commodo vitae quis ipsum. Nullam ac condimentum elit. Integer eget magna ac mi fermentum luctus. Ut pharetra auctor pulvinar. Duis lobortis, nulla at vestibulum tincidunt, ante neque scelerisque risus, ac dignissim nunc nisl rhoncus risus. Cras pretium egestas purus, a commodo nunc vehicula at. Fusce vestibulum enim in mi hendrerit a viverra justo tempor. Maecenas eget ipsum ac mauris dictum congue eu id justo.</s:p>
                <s:p>Aliquam tincidunt tempor nisi id porta. Aenean risus dolor, tincidunt a ultrices in, laoreet eu ante. Mauris vel lacus neque, ut scelerisque eros. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec vel lacus sit amet erat vehicula malesuada id in augue. Sed purus massa, placerat non imperdiet nec, venenatis a nulla. Donec vel ligula leo, in rhoncus arcu. Duis semper bibendum facilisis. Duis nibh lorem, egestas rutrum tincidunt non, vulputate accumsan nulla. Nunc ligula nisl, ultrices ut tempor quis, rutrum et enim. Nullam accumsan scelerisque ante id pretium. Mauris nibh metus, blandit in varius congue, pharetra sit amet sem. Phasellus tincidunt lacus quis est semper ut rhoncus sem pretium. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam pulvinar, enim eu consectetur venenatis, dui tortor commodo ante, sit amet sagittis libero odio cursus neque. Aliquam a dui non eros placerat euismod. In at mattis felis. Suspendisse potenti. Morbi posuere condimentum lacus. Suspendisse tellus magna, viverra ac mattis vel, adipiscing eget lectus.</s:p>
                <s:p>Etiam ut eros lectus. Praesent nec massa nibh. Cras venenatis, ligula in condimentum euismod, nisl lorem hendrerit lacus, a imperdiet odio est et odio. Suspendisse eu orci ut augue commodo gravida sed eu risus. Vestibulum venenatis erat ac metus ullamcorper blandit. Integer et sem enim. Vivamus a arcu metus. Nunc sollicitudin commodo placerat. Maecenas vehicula, massa et auctor tempor, felis leo commodo lorem, eget pulvinar felis turpis nec erat. Mauris imperdiet gravida felis a eleifend.</s:p>
                <s:p>Suspendisse mattis tempor fringilla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed molestie arcu. Praesent ut tellus sed orci blandit tristique non eget est. Sed interdum feugiat nisi, sit amet aliquet enim sodales non. Maecenas in velit sit amet tellus tincidunt dapibus. Vivamus est eros, iaculis et venenatis a, malesuada vel lacus. Aliquam vel orci tortor. Etiam ornare ante eget massa dignissim a auctor nunc pellentesque. Pellentesque sodales porta nisi, pretium accumsan eros tincidunt vitae. Cras facilisis accumsan purus ultricies lacinia. Praesent consequat elit imperdiet tellus vehicula ut ornare mauris mattis. Suspendisse non tortor nisl. Etiam ac pretium est.</s:p>
                <s:p>Maecenas tristique, velit aliquam faucibus ornare, justo erat porta elit, sed venenatis neque mi ac elit. Nullam enim metus, gravida ac euismod sit amet, commodo vitae elit. Quisque eget molestie ante. Nulla fermentum pretium augue non tristique. Praesent in orci eu diam ultrices sodales ac quis leo. Aliquam lobortis elit quis mi rutrum feugiat. Aenean sed elit turpis. Duis enim ligula, posuere sit amet semper a, pretium vel leo. Etiam mollis dolor nec elit suscipit imperdiet. Sed a est eros.</s:p>
            </s:TextFlow>
        </s:textFlow>
    </s:TextArea>
    <mx:ControlBar width="100%" cornerRadius="0">
        <mx:ToolBar width="100%" horizontalGap="5">
            <s:DropDownList id="fontDDL"
                    width="150"
                    change="fontDDL_changeHandler(event);">
                <s:dataProvider>
                    <s:ArrayList source="[Arial,Verdana,Times New Roman,Trebuchet MS]" />
                </s:dataProvider>
            </s:DropDownList>
            <s:DropDownList id="sizeDDL"
                    width="60"
                    change="sizeDDL_changeHandler(event);">
                <s:dataProvider>
                    <s:ArrayList source="[8,10,12,14,16,24,36,72]" />
                </s:dataProvider>
            </s:DropDownList>
            <s:ToggleButton id="boldBtn"
                    label="B"
                    fontWeight="bold"
                    width="30"
                    click="boldBtn_clickHandler(event);" />
            <s:ToggleButton id="italBtn"
                    label="I"
                    fontStyle="italic"
                    width="30"
                    click="italBtn_clickHandler(event);" />
            <s:ToggleButton id="underBtn"
                    label="U" 
                    textDecoration="underline"
                    width="30"
                    click="underBtn_clickHandler(event);" />
            <s:ToggleButton id="lineBtn"
                    label="S"
                    lineThrough="true"
                    width="30"
                    click="lineBtn_clickHandler(event);" />
            <mx:ColorPicker id="colorCP"
                    change="colorCP_changeHandler(event);" />
            <s:ButtonBar id="txtAlignBB"
                    arrowKeysWrapFocus="true"
                    labelField="label"
                    width="120"
                    change="txtAlignBB_changeHandler(event);">
                <s:dataProvider>
                    <s:ArrayList>
                        <fx:Object label="L" value="{TextAlign.LEFT}" />
                        <fx:Object label="C" value="{TextAlign.CENTER}" />
                        <fx:Object label="R" value="{TextAlign.RIGHT}" />
                        <fx:Object label="J" value="{TextAlign.JUSTIFY}" />
                    </s:ArrayList>
                </s:dataProvider>
            </s:ButtonBar>
        </mx:ToolBar>
    </mx:ControlBar>
 
</s:Panel>

This entry is based on a beta version of the Flex 4 SDK and therefore is very likely to change as development of the Flex SDK continues. The API can (and will) change causing examples to possibly not compile in newer versions of the Flex 4 SDK.

28 thoughts on “Exporting a TextFlow object in Flex 4

  1. For anyone else having troubles getting this to work, I had to install SDK 4.0.0.8811 and copy the netmon.swc from the 4.0 SDK into the new SDK ../frameworks/libs folder.

    I also had to create the project with an Application Server Type (I chose PHP) otherwise I got a Security Sandbox Violation accessing “textLayout_427.swf”

    Peter, awesome example.

    Thanks!

    1. kevin,

      I’ve never seen the security sandbox violation (although I guess I just run most of these locally).
      As for the network monitor, I always uncheck that feature in the project properties dialog.

      Peter

  2. Frustratingly the only error I got in Flash Builder 4 Beta console was “There was an internal build error.” (tried cleaning the project a few times)

    The logs didn’t say anything that made sense to me – but I did find a post somewhere suggesting that if you restart FB it solves the problem. In my case it didn’t solve the problem, but it gave me a more descriptive message (eg. netmon.swc file could not be found, etc).

    Not sure about the security error – but it occurred if the project was accessed by file:// rather than http://localhost (I’m on OSX).

    As this issue doesn’t seem to occur with my FB3 installation, I thought it worth mentioning.

    Thanks again for the example – I was wondering why there wassn’t a new RichTextEditor component – and then you gave us one.

    1. kevin,

      Yeah, unfortunately the beta 1 build of Flash Builder 4 had a bug where it was caching something, so you’ll need to restart Builder after changing the SDK. The error you’re seeing with the netmon.swc is because nightly builds are not shipped with that SWC. That has also been fixed in newer (internal) builds of Flash Builder, or so I understand. And since the network monitor (netmon.swc) is new in Builder 4, that is why you wouldn’t see either of these problems under Builder 3.

      Still not sure about the security error, but I haven’t tested this via HTTP or on OSX (only locally using WinXP). But that reminds me, I really should start posting SWFs again.

      Peter

  3. No worries – looking forward to the Gumbo final.

    Yeah I’d definitely like to see the SWF’s here again! They come in very handy to have a quick look at whatever new trick you’re showing us.

    I just re-created the security error to get the exact wording:

    *** Security Sandbox Violation ***
    Connection to file:///Users/kevnug/Documents/Adobe Flash Builder Beta/aCustomRTE/bin-debug/textLayout_4.0.0.8811.swf halted – not permitted from file:///Users/kevnug/Documents/Adobe Flash Builder Beta/aCustomRTE/bin-debug/aCustomRTE.swf
    SecurityError: Error #2148: SWF file file:///Users/kevnug/Documents/Adobe Flash Builder Beta/aCustomRTE/bin-debug/aCustomRTE.swf cannot access local resource file:///Users/kevnug/Documents/Adobe Flash Builder Beta/aCustomRTE/bin-debug/textLayout_4.0.0.8811.swf. Only local-with-filesystem and trusted local SWF files may access local resources.
    at flash.net::URLStream/load()
    at flash.net::URLLoader/load()
    at mx.core::CrossDomainRSLItem/load()[E:\dev\trunk\frameworks\projects\framework\src\mx\core\CrossDomainRSLItem.as:235]
    at mx.core::RSLListLoader/loadNext()[E:\dev\trunk\frameworks\projects\framework\src\mx\core\RSLListLoader.as:184]
    at mx.core::RSLListLoader/load()[E:\dev\trunk\frameworks\projects\framework\src\mx\core\RSLListLoader.as:156]
    at mx.preloaders::Preloader/initialize()[E:\dev\trunk\frameworks\projects\framework\src\mx\preloaders\Preloader.as:279]
    at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::initialize()[E:\dev\trunk\frameworks\projects\framework\src\mx\managers\SystemManager.as:1901]
    at mx.managers::SystemManager/initHandler()[E:\dev\trunk\frameworks\projects\framework\src\mx\managers\SystemManager.as:2356]
    [SWF] Users:kevnug:Documents:Adobe Flash Builder Beta:aCustomRTE:bin-debug:aCustomRTE.swf – 332,851 bytes after decompression

  4. can u give me an example of
    geting input from flex web page and show the
    reply on the next text field on the same page
    send at my id

  5. I am trying to complile is Flash Builder, and it says it can’t find ‘spark.events.IndexChangeEvent’ The coode hints for spark.events doesn’t show IndexChangeEvent. Thoughts? It says my Flash Builder is build 235740

  6. Hello Peter
    thank you so much for you examples, and namely this one.
    I am currently testing the TLF and trying to figure how to port content from the Flex 3 markup to TLF. Anyway, it seems that the best format to use with the TextConverter is Text_Layout_Format since its the only that preserves the most amount of information about formatting (tracking, lineHeight, etc….). This can be useful in a CMS situation, where content is pushed by the CMS into a database, then fetched by the front end application to render it.
    I modified your example and i am trying to figure out how to add a link input similar to the one in the in Flex 3 RichTextEditor.
    I added a text input that gets enabled when you highlight some text, and i am managing to add the link by first exporting the textflow into markup, assuming that the selected text is in the middle of span, inserting the link into the markup string and reimporting that using the TextConverter.
    Can you suggest a better way of doing this? Also, once the link is inserted, its highlighted in blue but its missing the hand cursor. any clues?
    Here is my modified example with published source : http://raedatoui.com/TLFTest.html
    cheers
    Raed

  7. Raed again, since my example is rough, based on splitting and merging the markup, you have to highlight a unique portion of the text that appears only once. It would work if you enter your own text, select it, enter the link in the textinput and then hit enter
    Thanks again
    Raed

  8. A BIG thanks for this blog and all of its contents!

    In the above example, when trying to export the TextFlow as HTML the color value changes. I think if one of the RGB values is “OO” it gets omitted.

    I used the SimpleTextEditor to save HTML formatted text and show it in a HTML page (with PHP/MySQL). Everything works fine but there is this issue with the color.

    I’d appreciate any help. Thank you in advance.

  9. The way you apply a link has changed. Here is what worked for me.

    private function createLink(link:String=”http://www.google.com”,title:String=null):void
    {
    var editManager:IEditManager = editor.textFlow.interactionManager as IEditManager;
    editManager.applyLink(link, title);
    }

  10. HI, I get an error:

    Access of undefined property ConversionType.

    when I try

    item.text = TextConverter.export(customEditor.editor.textFlow, TextConverter.TEXT_LAYOUT_FORMAT, ConversionType.STRING_TYPE).toString();

  11. Underline button dosn’t work propperly, it does place underline, but it does not remove it.

    1. I fixed it by exchanging:

      txtLayFmt.textDecoration = (txtLayFmt.fontStyle == TextDecoration.UNDERLINE) ? TextDecoration.NONE : TextDecoration.UNDERLINE;

      with

      if (txtLayFmt.textDecoration == TextDecoration.UNDERLINE) {
          txtLayFmt.textDecoration = TextDecoration.NONE;
      }
      else{
          txtLayFmt.textDecoration = TextDecoration.UNDERLINE;
      }
  12. The html text looks HUGE exported from this RTE. I don’t understand why Adobe export’s the font using FONT and not using SPAN … I mean FONT size 12 it’s like as big as your screen.

  13. Having trouble with Flash builder 4 and burrito. It seems, TextConverter.HTML_FORMAT doesn’t exist anymore, but it works with TextConverter.TEXT_FIELD_HTML_FORMAT which provide Adobe specific html tag … anyone have an idea to clean adobe html flow ?

  14. Hi, can you help me?
    So, I am studying again the “Flex” that is now “Flash Builder,” I’m kind of stuck, and going straight to the point, I’m having trouble using the project described here in the post.
    I use the “Flash Builder 4.5,” and the “CustomEditor” does not work at all, the error in the “mx: ColorPicker” and then on “mx: ControlBar” and then on “mx: ToolBar” and continue so on. tried to use, turned off the “mx: ToolBar” and tried other things but nothing worked.
    Tks Folks

Comments are closed.