views:

444

answers:

4

I am using the below code to convert a Word Doc into an image file. But the picture appears too big, and the contents don't fit - is there a way to render the picture or save the picture to size?

    private void btnConvert_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtFileName.Text))
        {
            MessageBox.Show("Choose a document to convert", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            txtFileName.Focus();
            return;
        }

        ApplicationClass wordApp = new ApplicationClass();
        object objectMissing = Missing.Value;

        try
        {
            object fileName = txtFileName.Text;
            FileStream fs = new FileStream(fileName.ToString(), FileMode.Open, FileAccess.Read);
            Byte[] data = new Byte[fs.Length];
            fs.Read(data, 0, data.Length);

            Document doc = wordApp.Documents.Open(ref fileName, ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,
                                   ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,
                                   ref objectMissing, ref objectMissing, ref objectMissing);


            byte[] range = (byte[]) wordApp.ActiveDocument.Content.EnhMetaFileBits;
            if (range != null)
            {
                MemoryStream ms = new MemoryStream(range);
                Metafile mf = new Metafile(ms);
                picImage.Height = mf.Height;
                picImage.Width = mf.Width;
                mf.Save("c:\\test.png", ImageFormat.Png);
                picImage.Image = Image.FromFile("c:\\test.png");
            }
        }
        finally
        {
            wordApp.Quit(ref objectMissing, ref objectMissing, ref objectMissing);
        }
    }
A: 

How about printing the document as a TIFF using the Microsoft Document Image Writer?

Stephen Nutt
A: 

You can also resize image programatically after saving it.

RK
+1  A: 

convert it to whatever size it will, then use imagemagick: http://www.imagemagick.org/script/index.php to resize or do whatever other post-processing you need (it can do a LOT)

Alex
+1  A: 

It turned out to be really simple:

    private void renderImage(byte[] imageData)
    {
        using (MemoryStream ms = new MemoryStream(imageData))
        {
            Image image = Image.FromStream(ms);
            picImage.Image = image;
        }
    }

This is showing the first page as an image, but it should be easy enough to render the other pages also.

Thanks to all those who answered