word文件生成图片C#案例

1、AsposeHelper类

using ESBasic;
using OMCS.Engine.WhiteBoard;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;

namespace WeiXinOASqlErpMysql.Common
{
    public class AsposeHelper : IImageConverter
    {
        private bool cancelled = false;
        public event CbGeneric<int, int> ProgressChanged;
        public event CbGeneric ConvertSucceed;
        public event CbGeneric<string> ConvertFailed;

        public void Cancel()
        {
            if (this.cancelled)
            {
                return;
            }

            this.cancelled = true;
        }

        public void ConvertToImage(string originFilePath, string imageOutputDirPath)
        {
            this.cancelled = false;
            ConvertToImageTwo(originFilePath, imageOutputDirPath, 0, 0, null, 200);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="originFilePath">word网络路径</param>
        /// <param name="imageOutputDirPath">生成图片保存地址</param>
        /// <param name="resolution">分辨率,设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
        public string WordConvertToImage(string originFilePath, string imageOutputDirPath, int resolution)
        {
            this.cancelled = false;
            return  ConvertToImageTwo(originFilePath, imageOutputDirPath, 0, 0, null, resolution);
        }
        /// <summary>
        /// 将Word文档转换为图片的方法     
        /// </summary>
        /// <param name="wordInputPath">Word文件路径</param>
        /// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为Word所在路径</param>      
        /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数</param>
        /// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
        /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
        private void ConvertToImage(string wordInputPath, string imageOutputDirPath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution)
        {
            try
            {
                Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);

                if (doc == null)
                {
                    throw new Exception("Word文件无效或者Word文件被加密!");
                }

                if (imageOutputDirPath.Trim().Length == 0)
                {
                    imageOutputDirPath = Path.GetDirectoryName(wordInputPath);
                }

                if (!Directory.Exists(imageOutputDirPath))
                {
                    Directory.CreateDirectory(imageOutputDirPath);
                }

                if (startPageNum <= 0)
                {
                    startPageNum = 1;
                }

                if (endPageNum > doc.PageCount || endPageNum <= 0)
                {
                    endPageNum = doc.PageCount;
                }

                if (startPageNum > endPageNum)
                {
                    int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
                }

                if (imageFormat == null)
                {
                    imageFormat = ImageFormat.Png;
                }

                if (resolution <= 0)
                {
                    resolution = 128;
                }

                string imageName = Path.GetFileNameWithoutExtension(wordInputPath);
                Aspose.Words.Saving.ImageSaveOptions imageSaveOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png);
                imageSaveOptions.Resolution = resolution;
                for (int i = startPageNum; i <= endPageNum; i++)
                {
                    if (this.cancelled)
                    {
                        break;
                    }

                    MemoryStream stream = new MemoryStream();
                    imageSaveOptions.PageIndex = i - 1;
                    string imgPath = Path.Combine(imageOutputDirPath, imageName) + "_" + i.ToString("000") + "." + imageFormat.ToString();
                    doc.Save(stream, imageSaveOptions);
                    Image img = Image.FromStream(stream);
                    Bitmap bm = ESBasic.Helpers.ImageHelper.Zoom(img, 0.6f);
                    bm.Save(imgPath, imageFormat);
                    img.Dispose();
                    stream.Dispose();
                    bm.Dispose();

                    System.Threading.Thread.Sleep(200);
                    if (this.ProgressChanged != null)
                    {
                        this.ProgressChanged(i - 1, endPageNum);
                    }
                }

                if (this.cancelled)
                {
                    return;
                }

                if (this.ConvertSucceed != null)
                {
                    this.ConvertSucceed();
                }
            }
            catch (Exception ex)
            {
                if (this.ConvertFailed != null)
                {
                    this.ConvertFailed(ex.Message);
                }
            }
        }



        /// <summary>
        /// 将Word文档转换为图片的方法,modefied by huangkailong 20171220      
        /// </summary>
        /// <param name="wordInputPath">Word文件路径</param>
        /// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为Word所在路径</param>      
        /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数</param>
        /// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
        /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
        private string ConvertToImageTwo(string wordInputPath, string imageOutputDirPath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution)
        {
            string PicName = string.Empty;
            string imgPath = string.Empty;
            try
            {
                Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);
                if (doc == null)
                {
                    throw new Exception("Word文件无效或者Word文件被加密!");
                }

                if (imageOutputDirPath.Trim().Length == 0)
                {
                    imageOutputDirPath = Path.GetDirectoryName(wordInputPath);
                }

                if (!Directory.Exists(imageOutputDirPath))
                {
                    Directory.CreateDirectory(imageOutputDirPath);
                }
                if (startPageNum <= 0)
                {
                    startPageNum = 1;
                }
                if (endPageNum > doc.PageCount || endPageNum <= 0)
                {
                    endPageNum = doc.PageCount;
                }
                if (startPageNum > endPageNum)
                {
                    int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
                }
                if (imageFormat == null)
                {
                    imageFormat = ImageFormat.Png;
                }

                if (resolution <= 0)
                {
                    resolution = 128;
                }
                string imageName = Path.GetFileNameWithoutExtension(wordInputPath);
                Aspose.Words.Saving.ImageSaveOptions imageSaveOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png);
                imageSaveOptions.Resolution = resolution;
                List<Image> listImage = new List<Image>();
                Image img = null;
                MemoryStream stream = null;
                for (int i = startPageNum; i <= endPageNum; i++)
                {
                    if (this.cancelled)
                    {
                        break;
                    }

                    stream = new MemoryStream();
                    imageSaveOptions.PageIndex = i - 1;
                    //string imgPath = Path.Combine(imageOutputDirPath, imageName) + "_" + i.ToString("000") + "." + imageFormat.ToString();
                    doc.Save(stream, imageSaveOptions);
                    img = Image.FromStream(stream);
                    //将img对象使用集合保存,合并iamge对象
                    listImage.Add(img);
                    Thread.Sleep(200);
                    if (this.ProgressChanged != null)
                    {
                        this.ProgressChanged(i - 1, endPageNum);
                    }
                }
                Image NewImg = CombineImages(listImage);
                Bitmap bm = ESBasic.Helpers.ImageHelper.Zoom(NewImg, 0.6f);
                PicName = imageName + "_" + Guid.NewGuid() + "_" + new PublicMethod().GenerateRandomNumber(10);
                imgPath = Path.Combine(imageOutputDirPath, PicName) + "." + imageFormat.ToString();
                PicName += "." + imageFormat.ToString();
                bm.Save(imgPath, imageFormat);
                bm.Dispose();
                img.Dispose();
                stream.Dispose();
                if (this.cancelled)
                {
                    return "";
                }
                if (this.ConvertSucceed != null)
                {
                    this.ConvertSucceed();
                }
            }
            catch (Exception ex)
            {
                if (this.ConvertFailed != null)
                {
                    this.ConvertFailed(ex.Message);
                }
                PublicMethod.WriteLogFile(new PublicMethod().getErrorLogFile("AsposeHelper_WordToPicture"), "word转图片出错,时间" + DateTime.Now + ",文件访问路径:"+ wordInputPath + ",\r\n错误信息:" + ex);

                return "";
            }
            return PicName;
        }


        /// <summary>
        /// 合并image对象
        /// </summary>
        /// <param name="images">Images对象集合</param>
        /// <returns></returns>
        private Image CombineImages(List<Image> images)
        {
            Image image = null;
            Graphics g = null;
            try
            {
                int width = 0, height = 0;
                for (int i = 0; i < images.Count; i++)
                {
                    width = images[i].Width > width ? images[i].Width : width;
                    height += images[i].Height + 5;
                }
                image = new Bitmap(width, height);
                g = Graphics.FromImage(image);
                int offset = 0;
                foreach (Image tempImage in images)
                {
                    g.DrawImage(tempImage, new System.Drawing.Rectangle(0, offset, tempImage.Width, tempImage.Height));
                    offset += tempImage.Height + 5;
                }
                return image;
            }
            finally
            {
                g.Dispose();
            }
        }
    }
}

2、调用方法

private string SavePic(string fileurl)
        {
            AsposeHelper asposeHelper = new AsposeHelper();
            return asposeHelper.WordConvertToImage(fileurl, HttpContext.Current.Server.MapPath("~/DocumentPic/"), 150);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大海中一粒沙子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值