Embedding PNGs into RTF files

Recently I had to implement drag and drop of PNG images in WPF so that if you dragged an image from a WPF app to a document in Word or Outlook, the PNG would be displayed as a part of it. As it turned out, MS Word and Outlook plays well with Rich Text Format, so I had to figure out how to embed a PNGs into an RTF stream.

The code for this wasn’t difficult, but finding out how to do it was an adventure. First, I found out the structure that the RTF had to be written as:

{\rtf1\ansi\deff0{\pict\pngblip\picwX\pichY

*The data for the PNG image converted into hex*

}}

The first line tells RTF parsers that we have a png embedded (the \pict\pnblip control words), with \picw and \pich describing the pixel width and height of the image (X and Y).

Following the that, you write the data representing the PNG file. However, you have to write the PNG in a way that RTF parsers understand. Specifically, you have to convert the binary values that represent the encoded PNG into hexadecimal characters. From looking at example files floating around on the web, I also grouped the hex into separate lines composed of 64 character chunks.

After that, I wrote the footer, }}. All of this was done encoding the final stream as ASCII, since RTF seems to understand that well. That’s it, I had a valid RTF stream that Word and Outlook could parse.

As a demonstration to help you get started, I’ve included a demo app, aptly named PngToRtfConverter. The app is a window asking you to select a PNG file to convert into an RTF file. I’ve also factored the actual conversion part into helper classes, but note that since this code was for learning/demonstration purposes, so it isn’t necessarily efficient nor is there extensive error checking.

This demo app was written in Visual Studio 2008:

PngToRtfConverter.zip

Explore posts in the same categories: Rich Text Format

Tags: , ,

You can comment below, or link to this permanent URL from your own site.

One Comment on “Embedding PNGs into RTF files”


  1. [...] "Embedding PNGs into RTF files" in order to implement drag/drop from a WPF app to Word/Outlook. [...]


Comment:

You must be logged in to post a comment.