简体   繁体   中英

Saving a word document as an image

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

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

将它转换为任何大小,然后使用imagemagick: http//www.imagemagick.org/script/index.php调整大小或进行其他任何你需要的后处理(它可以做很多)

将内容复制到Powerpoint(如果可以复制),然后您可以将幻灯片保存为所需格式的图像

如何使用Microsoft Document Image Writer将文档打印为TIFF?

保存后,您还可以以编程方式调整图像大小。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM