我正在使用以下代码将Word Doc转换为图像文件。但是图片看起来太大了,内容不适合-有没有办法渲染图片或将图片保存为合适的尺寸?

    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);
        }
    }

最佳答案

原来真的很简单:

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

这会将第一页显示为图像,但也应该足够容易来呈现其他页面。

感谢所有回答

关于c# - 将Word文档另存为图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/775153/

10-13 04:15