iTextSharp - How to generate a RTF document in the

2019-07-29 11:52发布

I would like to generate a PDF or RTF document using iTextSharp library that can be copied to the clipboard, using the same code I use to generate the document on a file (FileStream).

This way my application would give the user two options: generate to a file or to the clipboard.

1条回答
放荡不羁爱自由
2楼-- · 2019-07-29 12:10

Basically every iTextSharp document is attached to a System.IO.Stream.

Document doc = new Document(PageSize.A4);
RtfWriter2.GetInstance(doc, stream);

Usually we save the document to a file, using FileStream. To use the same code to paste the document in the Clipboard, we use a MemoryStream instead.

MemoryStream stream = new MemoryStream();
Document doc = new Document(PageSize.A4);
RtfWriter2.GetInstance(doc, stream);

// (...) document content

doc.Close();

string rtfText = ASCIIEncoding.ASCII.GetString(stream.GetBuffer());
stream.Close();

Clipboard.SetText(rtfText, TextDataFormat.Rtf);

I only had problems with Images: It seems that iTextSharp exports images saving the bytes of the image after the \bin tag. Some libraries put the binary content encoded as hex characters. When I paste (from memory) in Word, the images won't appear, but if I load from a file, everything is OK. Any suggestions?

查看更多
登录 后发表回答