iOS NSAttributedString to HTML

為{幸葍}努か 提交于 2019-11-28 17:54:32

May be you could look at that repository: https://github.com/IdeasOnCanvas/Ashton

there is 2 interesting class:

AshtonHTMLReader.h

 - (NSAttributedString *)attributedStringFromHTMLString:(NSString *)htmlString;

And the writer:

AshtonHTMLWriter.h

- (NSString *)HTMLStringFromAttributedString:(NSAttributedString *)input;

The html generated isn't very nice but if you try to display it in a uiwebview, it looks pretty good.

Simple idea for image: encode it with base64 and put it directly in a < img > tag with the right frame.

It's ugly but it works => I've used this process to create and edit some html file few month ago

This is a complex issue, and I will start with a shorter answer. You may ask me questions in the comments, and I will expand on the answer as needed.

We also tried to go the attributed string route, but found it not suited for full HTML editing. Many elements are just not supported, either because the converter is not fully developed, or these elements were deemed outside of scope by Apple. Parsing the attributed string is not good enough, because the attributed string has already lost most of the richness of the HTML by the time you attempt to recreate it.

Instead, we use a webview, load the document normally, and enable contentEditable on the body element. What this does is allow editing of the document in its fullest, limited only by WebKit. At the end, to retrieve the HTML back, we disable contentEditable and take the document.outerHTML to get an entire HTML as it was before, with changes made by the user.

Don't take the decision to implement this method lightly. It is a somewhat complex solution, but certainly possible. A webview is not as nice as a textview, but it can be, given enough massage.

I will expand on this answer as needed.

I also had to convert a NSAtttributedString to HTML in one of my projects. The code for doing this is as follows

//self.attributed String is the attributedString 
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSData *htmlData = [self.attributedString dataFromRange:NSMakeRange(0, self.attributedString.length) documentAttributes:documentAttributes error:NULL];
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
NSLog(@"%@", htmlString);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!