How to show html style text in excel cell with SpreadsheetGear - html

I get a string that contains html content, like this:
"i am headhello"
now, i want to write this string into excel cell, and let these html tags render the bold style.
How can i do this with spreadsheetgear?

SpreadsheetGear does not support parsing and rendering HTML. If you put this type of content in a cell, the raw markup will be displayed instead.
SpreadsheetGear does support adding rich-text (RTF) to a cell, but you would need to do this with SpreadsheetGear API using:
IRange.GetCharacters(...)
ICharacters interface
The following example code would render something similar to this:
// Create new workbook.
IWorkbook workbook = Factory.GetWorkbook();
IWorksheet worksheet = workbook.ActiveWorksheet;
IRange cells = worksheet.Cells;
// Add text to A1 which we'll format below...
cells["A1"].Value = "This Is My Header\n\nHello World!";
// Format "header" as bold and with a larger font size.
ICharacters charsHeader = cells["A1"].GetCharacters(0, 17);
charsHeader.Font.Bold = true;
charsHeader.Font.Size = 18;
// Format "Hello" text.
ICharacters charsHello = cells["A1"].GetCharacters(19, 5);
charsHello.Font.Italic = true;
charsHello.Font.Color = SpreadsheetGear.Colors.DarkRed;
// Format "World" text.
ICharacters charsWorld = cells["A1"].GetCharacters(25, 5);
charsWorld.Font.Underline = UnderlineStyle.Single;
charsWorld.Font.Color = SpreadsheetGear.Colors.DarkBlue;
// Expand column width to accommodate header text
cells["A:A"].ColumnWidth = 30;
// Save and view in Excel...
workbook.SaveAs(#"c:\temp\rtf.xlsx", FileFormat.OpenXMLWorkbook);
// ...or attach to SpreadsheetGear's WPF WorkbookView to
// confirm RTF is displaying as expected (NOTE: the WinForms
// WorkbookView does not support rendering RTF).
workbookView.ActiveWorkbook = workbook;

Related

Centering in a gDoc after a replace

I am looking to replace a string within a Google Doc via an app script. The string will exist on a line, but after the replace, I want it to have a specific font, size and justification.
I've created a style to address all these attributes (I included both Horiz. and Vert. alignment) and most of it works fine. When the string is replaced, the replacement has the right font, size and bold attributes. For some reason, I cannot get the justification to get changed.
// Define the style for the replacement string.
var hdrStyle = {};
hdrStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] =
DocumentApp.HorizontalAlignment.CENTER;
hdrStyle[DocumentApp.Attribute.VERTICAL_ALIGNMENT] =
DocumentApp.VerticalAlignment.CENTER;
hdrStyle[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
hdrStyle[DocumentApp.Attribute.FONT_SIZE] = 24;
hdrStyle[DocumentApp.Attribute.BOLD] = true;
{ then later }
documentBody = DocumentApp.openById(fileId).getBody();
hdrElem = documentBody.findText("old string").getElement();
hdrText = hdrElem.asText().setText("new string");
// Force our 'header style':
hdrElem.setAttributes(hdrStyle);
I've tried setting the style after the findText and (as here) after, but no change in centering.
I see there is a paragraph centering, but I am not clear how to 'get' the paragraph associated with the element that is returned on the find.
I'm hoping this is some simple set of calls - but have run out of ideas (and patience)..!
Any help would be appreciated!
You can use getParent() on hdrElem to get the parent paragraph to apply the styling to.
https://developers.google.com/apps-script/reference/document/text#getParent()
documentBody = DocumentApp.openById(fileId).getBody();
hdrElem = documentBody.findText("old string").getElement();
hdrText = hdrElem.asText().setText("new string");
var hdrParent = hdrElem.getParent()
// Force our 'header style':
hdrParent.setAttributes(hdrStyle);

Can I assign HTML to a Paragraph in iTextSharp rather than concatenating Chunks? [duplicate]

I have a rich text box named:”DocumentContent” which I’m going to add its content to pdf using the below code:
iTextSharp.text.Font font = FontFactory.GetFont(#"C:\Windows\Fonts\arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12f, Font.NORMAL, BaseColor.BLACK);
DocumentContent = System.Web.HttpUtility.HtmlDecode(DocumentContent);
Chunk chunkContent = new Chunk(DocumentContent);
chunkContent.Font = font;
Phrase PhraseContent = new Phrase(chunkContent);
PhraseContent.Font = font;
PdfPTable table = new PdfPTable(2);
table.WidthPercentage = 100;
PdfPCell cell;
cell = new PdfPCell(new Phrase(PhraseContent));
cell.Border = Rectangle.NO_BORDER;
table.AddCell(cell);
The problem is when I open PDF file the content appears as HTML not a text as below:
<p>Overview  line1 </p><p>Overview  line2
</p><p>Overview  line3 </p><p>Overview 
line4</p><p>Overview  line4</p><p>Overview 
line5 </p>
But it should look like below
Overview line1
Overview line2
Overview line3
Overview line4
Overview line4
Overview line5
What I'm going to do is to keep all the styling which user apply to the rich text and just change font family to Arial.
I can change Font Family but I need to Decode this content from HTML to Text.
Could you please advise?
Thanks
Please take a look at the HtmlContentForCell example.
In this example, we have the HTML you mention:
public static final String HTML = "<p>Overview line1</p>"
+ "<p>Overview line2</p><p>Overview line3</p>"
+ "<p>Overview line4</p><p>Overview line4</p>"
+ "<p>Overview line5 </p>";
We also create a font for the <p> tag:
public static final String CSS = "p { font-family: Cardo; }";
In your case, you may want to replace Cardo with Arial.
Note that we registered the regular version of the Cardo font:
FontFactory.register("resources/fonts/Cardo-Regular.ttf");
If you need bold, italic and bold-italic, you also need to register those fonts of the same Cardo family. (In case of arial, you'd register arial.ttf, arialbd.ttf, ariali.ttf and arialbi.ttf).
Now we can parse this HTML and CSS into a list of Element objects with the parseToElementList() method. We can use these objects inside a cell:
PdfPTable table = new PdfPTable(2);
table.addCell("Some rich text:");
PdfPCell cell = new PdfPCell();
for (Element e : XMLWorkerHelper.parseToElementList(HTML, CSS)) {
cell.addElement(e);
}
table.addCell(cell);
document.add(table);
See html_in_cell.pdf for the resulting PDF.
I do not have the time/skills to provide this example in iTextSharp, but it should be very easy to port this to C#.
Finally I write this code in c# which is working perfectly, Thanks to Bruno who helped me to understand XMLWorker.
Here is an example using XMLWorker in C#.
I used a sample HTML as below:
public static string HTML = "<p>Overview line1âââŵẅẃŷûâàêÿýỳîïíìôöóòêëéèẁẃẅŵùúúüûàáäâ</p>"
+ "<p>Overview line2</p><p>Overview line3</p>"
+ "<p>Overview line4</p><p>Overview line4</p>"
+ "<p>Overview line5 </p>";
I have created Test.css file and saved it in SharePoint Style Library. (for this test I saved it in D drive to keep it simple)
Here is the content of my test css file:
p { font-family: arial; }
Then using the below c# code I saved the PDF file in D drive. ( In SharePoint I used Memorystream. I keep this example very simple to understand )
string fileName = #"D:\Test.pdf";
var css = #"D:\Test.css";
using (var ActionStream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(HTML)))
{
using (FileStream cssFile = new FileStream(css, FileMode.Open))
{
var document = new Document(PageSize.A4, 30, 30, 10, 10);
var worker = XMLWorkerHelper.GetInstance();
var writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
document.Open();
worker.ParseXHtml(writer, document, ActionStream, cssFile);
writer.CloseStream = false;
document.Close();
}
}
It creates Test.pdf file adding my HTML with Font Family:Arial. So all of the Welsh Characters can be saved in PDF file.
Note: I have added iTextSharp.dll v:5.5.3 and XMLworker.dll v: 5.5.3 to my project.
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.css;
using iTextSharp.tool.xml.html;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline;
Hope this can be useful.
Kate

How to get cfspreadsheet to render html

I'm trying to create an excel file with cfspreadsheet. In one of the columns I have html code, but for some reason, in the excel file the html doesn't get rendered it's just plain text. eg. <b>blabla</b> instead of being bolded.
Do you know any solutions to this?
The reason is that cfspreadsheet is based on POI which does not support html content.
As user1450455 mentions, you can format whole cells using any of the built in formatting functions such as SpreadsheetFormatCell.
sheet = spreadSheetNew();
spreadSheetFormatCell( sheet, {bold=true} , 1, 1 );
spreadSheetSetCellValue( sheet, "blablah", 1, 1 );
If you are looking to create cells with multiple formats (ie bold some characters but not others) that is only possible using the underlying POI library by creating a RichTextString. So it requires much lower level code.
<cfscript>
sheet = spreadSheetNew();
workbook = sheet.getWorkBook();
helper = workbook.getCreationHelper();
richText = helper.createRichTextString("ColdFusion");
// make first few characters bold ie "Cold"
firstFont = workbook.createFont();
firstFont.setBoldweight( firstFont.BOLDWEIGHT_BOLD );
richText.applyFont( 0, 4, firstFont );
// make next characters red ie "Fusion"
secondFont = workbook.createFont();
secondFont.setColor( secondFont.COLOR_RED );
richText.applyFont( 4, 10, secondFont );
// create cell via CF and apply formats
// note, in POI indexes are base 0
spreadSheetSetCellValue( sheet, "", 2, 1);
cellA2 = workbook.getSheetAt(0).getRow(1).getCell(0);
cellA2.setCellValue( richText );
</cfscript>
You can use the spreadsheet formatting functions like SpreadsheetFormatRow or SpreadsheetFormatrows or SpreadsheetFormatColumns.

Modify TLF Text Field properties that is on stage

I have a TLF Text field on the stage. I am trying to test this out in simple flash document.
My code takes in some xml that I parse. The xml will vary and will not always change all the properties of the text field. For instance in one case I only want to change the size of the font. In another case I only want to change the alignment of the font.
I am using TLF Text fields because we will translating into Arabic and I already have gotten Right to Left text working with them.
These are some properties I will need to edit in code:
Font Size
Font
Alignment
Leading
Bold, Italic, Underline (weight)
Any coding help would be great. I have seen ideas out there for text flow and text layout but I am obviously not using it correctly because I can't get it to work.
Long ago before I give up and stop using TLF fields. I have a project that requests dynamic addind and removing tlf fileds from/to stage. This is a code from this project:
This will generate default format dynamically
var config:Configuration = new Configuration();
var defTextFormat: TextLayoutFormat = new TextLayoutFormat();
defTextFormat.textAlign = TextAlign.LEFT;
defTextFormat.fontFamily = m_strFontName;
defTextFormat.fontSize = m_nFontSize;
defTextFormat.fontWeight = FontWeight.BOLD
defTextFormat.paddingLeft = 3;
defTextFormat.paddingTop = 3;
defTextFormat.paragraphStartIndent = 3;
defTextFormat.paragraphSpaceBefore = 3;
config.defaultLinkActiveFormat = defTextFormat;
config.defaultLinkHoverFormat = defTextFormat;
config.defaultLinkNormalFormat = defTextFormat;
config.textFlowInitialFormat = ITextLayoutFormat( defTextFormat );
m_textFlow = new TextFlow( config );
member m_textFlow holds a ref to TLF field.
To add and remove elements use m_textFlow.addChild( p ); where p is paragraph element
see: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flashx/textLayout/elements/ParagraphElement.html
To change the FontSize and color an element for example :
var _p:ParagraphElement = ParagraphElement( m_textFlow.getChildAt( iChild ) );
for ( var iParChild: uint = 0; iParChild < _p.numChildren; ++iParChild )
{
_p.getChildAt( iParChild ).color = color;
_p.getChildAt( iParChild ).fontSize = nRatio;
...
Maybe this can help you.

JSFL: convert text from a textfield to a HTML-format string

I've got a deceptively simple question: how can I get the text from a text field AND include the formatting? Going through the usual docs I found out it is possible to get the text only. It is also possible to get the text formatting, but this only works if the entire text field uses only one kind of formatting. I need the precise formatting so that I convert it to a string with html-tags.
Personally I need this so I can pass it to a custom-made text field component that uses HTML for formatting. But it could also be used to simply export the contents of any text field to any other format. This could be of interest to others out there, too.
Looking for a solution elsewhere I found this:
http://labs.thesedays.com/blog/2010/03/18/jsfl-rich-text/
Which seems to do the reverse of what I need, convert HTML to Flash Text. My own attempts to reverse this have not been successful thus far. Maybe someone else sees an easy way to reverse this that I’m missing? There might also be other solutions. One might be to get the EXACT data of the text field, which should include formatting tags of some kind(XML, when looking into the contents of the stored FLA file). Then remove/convert those tags. But I have no idea how to do this, if at all possible. Another option is to cycle through every character using start- and endIndex, and storing each formatting kind in an array. Then I could apply the formatting to each character. But this will result in excess tags. Especially for hyperlinks! So can anybody help me with this?
A bit late to the party but the following function takes a JSFL static text element as input and returns a HTML string (using the Flash-friendly <font> tag) based on the styles found it its TextRuns array. It's doing a bit of basic regex to clear up some tags and double spaces etc. and convert /r and /n to <br/> tags. It's probably not perfect but hopefully you can see what's going on easy enough to change or fix it.
function tfToHTML(p_tf)
{
var textRuns = p_tf.textRuns;
var html = "";
for ( var i=0; i<textRuns.length; i++ )
{
var textRun = textRuns[i];
var chars = textRun.characters;
chars = chars.replace(/\n/g,"<br/>");
chars = chars.replace(/\r/g,"<br/>");
chars = chars.replace(/ /g," ");
chars = chars.replace(/. <br\/>/g,".<br/>");
var attrs = textRun.textAttrs;
var font = attrs.face;
var size = attrs.size;
var bold = attrs.bold;
var italic = attrs.italic;
var colour = attrs.fillColor;
if ( bold )
{
chars = "<b>"+chars+"</b>";
}
if ( italic )
{
chars = "<i>"+chars+"</i>";
}
chars = "<font size=\""+size+"\" face=\""+font+"\" color=\""+colour+"\">"+chars+"</font>";
html += chars;
}
return html;
}