Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

objective c - iOS NSAttributedString to HTML

I have an NSAttributed string (coming from HTML) that I set for a UITextView.

- (void)setHtml:(NSString *)html {

    NSData *htmlData = [html dataUsingEncoding:NSUTF8StringEncoding];

    // Create the HTML string
    NSDictionary *importParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSError *error = nil;
    self.htmlString = [[NSAttributedString alloc] initWithData:htmlData options:importParams documentAttributes:NULL error:&error];

    self.editorView.attributedText = self.htmlString;

}

I then let the user edit what they want, and I would like to then convert it out to HTML again, so I use:

- (NSString *)getHTML {
    NSDictionary *exportParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSData *htmlData = [self.editorView.attributedText dataFromRange:NSMakeRange(0, self.editorView.attributedText.length) documentAttributes:exportParams error:nil];
    return [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
}

It does return HTML, but it isn't how I want it. Everything is given a class attribute, and the CSS it put at the top of the document. Things like images and links are not even included in the returned HTML and probably tons more issues.

Is there a better way to get HTML from an NSAttributedString? Or, is there a way I could parse the NSAttributedString and write my own HTML?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...