aspose使用代码(去除水印)(在线显示各种格式文件)(各种格式文件转pdf)(pdf转图片)

1、去除水印代码

public const string Key =
            "PExpY2Vuc2U+DQogIDxEYXRhPg0KICAgIDxMaWNlbnNlZFRvPkFzcG9zZSBTY290bGFuZCB" +
            "UZWFtPC9MaWNlbnNlZFRvPg0KICAgIDxFbWFpbFRvPmJpbGx5Lmx1bmRpZUBhc3Bvc2UuY2" +
            "9tPC9FbWFpbFRvPg0KICAgIDxMaWNlbnNlVHlwZT5EZXZlbG9wZXIgT0VNPC9MaWNlbnNlV" +
            "HlwZT4NCiAgICA8TGljZW5zZU5vdGU+TGltaXRlZCB0byAxIGRldmVsb3BlciwgdW5saW1p" +
            "dGVkIHBoeXNpY2FsIGxvY2F0aW9uczwvTGljZW5zZU5vdGU+DQogICAgPE9yZGVySUQ+MTQ" +
            "wNDA4MDUyMzI0PC9PcmRlcklEPg0KICAgIDxVc2VySUQ+OTQyMzY8L1VzZXJJRD4NCiAgIC" +
            "A8T0VNPlRoaXMgaXMgYSByZWRpc3RyaWJ1dGFibGUgbGljZW5zZTwvT0VNPg0KICAgIDxQc" +
            "m9kdWN0cz4NCiAgICAgIDxQcm9kdWN0PkFzcG9zZS5Ub3RhbCBmb3IgLk5FVDwvUHJvZHVj" +
            "dD4NCiAgICA8L1Byb2R1Y3RzPg0KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl" +
            "0aW9uVHlwZT4NCiAgICA8U2VyaWFsTnVtYmVyPjlhNTk1NDdjLTQxZjAtNDI4Yi1iYTcyLT" +
            "djNDM2OGYxNTFkNzwvU2VyaWFsTnVtYmVyPg0KICAgIDxTdWJzY3JpcHRpb25FeHBpcnk+M" +
            "jAxNTEyMzE8L1N1YnNjcmlwdGlvbkV4cGlyeT4NCiAgICA8TGljZW5zZVZlcnNpb24+My4w" +
            "PC9MaWNlbnNlVmVyc2lvbj4NCiAgICA8TGljZW5zZUluc3RydWN0aW9ucz5odHRwOi8vd3d" +
            "3LmFzcG9zZS5jb20vY29ycG9yYXRlL3B1cmNoYXNlL2xpY2Vuc2UtaW5zdHJ1Y3Rpb25zLm" +
            "FzcHg8L0xpY2Vuc2VJbnN0cnVjdGlvbnM+DQogIDwvRGF0YT4NCiAgPFNpZ25hdHVyZT5GT" +
            "zNQSHNibGdEdDhGNTlzTVQxbDFhbXlpOXFrMlY2RThkUWtJUDdMZFRKU3hEaWJORUZ1MXpP" +
            "aW5RYnFGZkt2L3J1dHR2Y3hvUk9rYzF0VWUwRHRPNmNQMVpmNkowVmVtZ1NZOGkvTFpFQ1R" +
            "Hc3pScUpWUVJaME1vVm5CaHVQQUprNWVsaTdmaFZjRjhoV2QzRTRYUTNMemZtSkN1YWoyTk" +
            "V0ZVJpNUhyZmc9PC9TaWduYXR1cmU+DQo8L0xpY2Vuc2U+";
			
			
			
			
			
//使用下面代码前都加这个下面的		
// new Aspose.Slides.License().SetLicense(new MemoryStream(Convert.FromBase64String(Key)));  //这个是sldes的,其他类似

2、配套代码(c#)

using Aspose.Cells;
using Aspose.Words;
using Aspose.Words.Fonts;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BorderType = Aspose.Cells.BorderType;

namespace manager.Controllers
{
    public class topdfController : ApiController   //webapi
    {
        public const string Key =
            "PExpY2Vuc2U+DQogIDxEYXRhPg0KICAgIDxMaWNlbnNlZFRvPkFzcG9zZSBTY290bGFuZCB" +
            "UZWFtPC9MaWNlbnNlZFRvPg0KICAgIDxFbWFpbFRvPmJpbGx5Lmx1bmRpZUBhc3Bvc2UuY2" +
            "9tPC9FbWFpbFRvPg0KICAgIDxMaWNlbnNlVHlwZT5EZXZlbG9wZXIgT0VNPC9MaWNlbnNlV" +
            "HlwZT4NCiAgICA8TGljZW5zZU5vdGU+TGltaXRlZCB0byAxIGRldmVsb3BlciwgdW5saW1p" +
            "dGVkIHBoeXNpY2FsIGxvY2F0aW9uczwvTGljZW5zZU5vdGU+DQogICAgPE9yZGVySUQ+MTQ" +
            "wNDA4MDUyMzI0PC9PcmRlcklEPg0KICAgIDxVc2VySUQ+OTQyMzY8L1VzZXJJRD4NCiAgIC" +
            "A8T0VNPlRoaXMgaXMgYSByZWRpc3RyaWJ1dGFibGUgbGljZW5zZTwvT0VNPg0KICAgIDxQc" +
            "m9kdWN0cz4NCiAgICAgIDxQcm9kdWN0PkFzcG9zZS5Ub3RhbCBmb3IgLk5FVDwvUHJvZHVj" +
            "dD4NCiAgICA8L1Byb2R1Y3RzPg0KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl" +
            "0aW9uVHlwZT4NCiAgICA8U2VyaWFsTnVtYmVyPjlhNTk1NDdjLTQxZjAtNDI4Yi1iYTcyLT" +
            "djNDM2OGYxNTFkNzwvU2VyaWFsTnVtYmVyPg0KICAgIDxTdWJzY3JpcHRpb25FeHBpcnk+M" +
            "jAxNTEyMzE8L1N1YnNjcmlwdGlvbkV4cGlyeT4NCiAgICA8TGljZW5zZVZlcnNpb24+My4w" +
            "PC9MaWNlbnNlVmVyc2lvbj4NCiAgICA8TGljZW5zZUluc3RydWN0aW9ucz5odHRwOi8vd3d" +
            "3LmFzcG9zZS5jb20vY29ycG9yYXRlL3B1cmNoYXNlL2xpY2Vuc2UtaW5zdHJ1Y3Rpb25zLm" +
            "FzcHg8L0xpY2Vuc2VJbnN0cnVjdGlvbnM+DQogIDwvRGF0YT4NCiAgPFNpZ25hdHVyZT5GT" +
            "zNQSHNibGdEdDhGNTlzTVQxbDFhbXlpOXFrMlY2RThkUWtJUDdMZFRKU3hEaWJORUZ1MXpP" +
            "aW5RYnFGZkt2L3J1dHR2Y3hvUk9rYzF0VWUwRHRPNmNQMVpmNkowVmVtZ1NZOGkvTFpFQ1R" +
            "Hc3pScUpWUVJaME1vVm5CaHVQQUprNWVsaTdmaFZjRjhoV2QzRTRYUTNMemZtSkN1YWoyTk" +
            "V0ZVJpNUhyZmc9PC9TaWduYXR1cmU+DQo8L0xpY2Vuc2U+";
        #region 把word转化成Pdf
        //转换成pdf
        // GET api/changepdf
        [HttpGet]
        public string changepdf(string ss)
        {

            string path = System.Web.Hosting.HostingEnvironment.MapPath(ss);   //ss是文件名  gg.docx这样

            //return path;
            try
            {
                string inpdf = path;
                string outpdf = @"/filedata/1111.pdf";             //输出文件
                new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String(Key)));




                string outtopdf = System.Web.Hosting.HostingEnvironment.MapPath(outpdf);   //计算出绝对路径

                //ExcelConvert.ExcelConvertManage.StartConvert(inpdf, outpdf);
                Document doc = new Document(inpdf);

                doc.Save(outtopdf, Aspose.Words.SaveFormat.Pdf);

                return outpdf;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }
        #endregion
        #region ppt转换为pdf
        //[Route("topdf/ppttopdf")]
        [HttpGet]
        public string ppttopdf(string ss)
        {

            string path = System.Web.Hosting.HostingEnvironment.MapPath(ss);

            //return path;
            try
            {
                string inpdf = path;

                string outpdf = @"/filedata/1111.pdf";

                new Aspose.Slides.License().SetLicense(new MemoryStream(Convert.FromBase64String(Key)));

                string outtopdf = System.Web.Hosting.HostingEnvironment.MapPath(outpdf);

                //AsposeLicenseHelper.SetSlidesLicense();
                Aspose.Slides.Presentation doc = new Aspose.Slides.Presentation(inpdf);
                doc.Save(outtopdf, Aspose.Slides.Export.SaveFormat.Pdf);
                //doc.Save(outtopdf, Aspose.Words.SaveFormat.Pdf);


                return outpdf;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }
        #endregion
        #region excel转换成pdf
        //[Route("topdf/exceltopdf")]
        [HttpGet]
        public string exceltopdf(string ss)
        {

            string path = System.Web.Hosting.HostingEnvironment.MapPath(ss);

            //return path;
            try
            {
                string inpdf = path;

                string outpdf = @"/filedata/1111.pdf";

                new Aspose.Cells.License().SetLicense(new MemoryStream(Convert.FromBase64String(Key)));

                string outtopdf = System.Web.Hosting.HostingEnvironment.MapPath(outpdf);


                Aspose.Cells.Workbook excel = new Workbook(inpdf);



                excel.Save(outtopdf, Aspose.Cells.SaveFormat.Pdf);


                return outpdf;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }
        #endregion
    }
}

3、aspose操作代码(word,excel,ppt转pdf然后再转图片显示)(这是我转来收藏的代码)

using Aspose.Cells;
using Aspose.Words.Saving;
using ESBasic;
using OMCS.Engine.WhiteBoard;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using SMES.LocaleManagerWeb.DoucmentManager;
using ImageSaveOptions = Aspose.Words.Saving.ImageSaveOptions;
using SaveFormat = Aspose.Words.SaveFormat;
 
namespace SMES.LocaleManagerWeb
{
    public partial class Upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //new Aspose.Words.License().SetLicense(AsposeLicenseHelper.LStream);
            //new Aspose.Cells.License().SetLicense(AsposeLicenseHelper.LStream);
            //new Aspose.Slides.License().SetLicense(AsposeLicenseHelper.LStream);
            //new Aspose.Pdf.License().SetLicense(AsposeLicenseHelper.LStream);
            string documentExts = "pdf|doc|docx|xlsx|xls|ppt|pptx";
            string imageExts = "jpeg|png|jpg|bmp";
            string otherExts = "pdf|xls|xlsx|ppt|pptx";
            HttpFileCollection files = Request.Files;//这里只能用<input type="file" />才能有效果,因为服务器控件是HttpInputFile类型
 
            FileUpModel model = new FileUpModel();
            if (files.Count == 0 || files[0].InputStream.Length == 0)
            {
                model = new FileUpModel() { State = 0, Error = "没有找到文件" };
                Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(model));
                //Response.End();
                return;
            }
 
            try
            {
                HttpPostedFile file = files[0];
                model.Extension = GetExtension(file.FileName);
                if ((documentExts + "|" + imageExts + "|" + otherExts).IndexOf(model.Extension.ToLower()) == -1)
                {
                    model = new FileUpModel() { State = 0, Error = "不允许上传" + model.Extension + "类型文件" };
                    Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(model));
                    //Response.End();
                    return;
                }
 
                model.Size = file.ContentLength / 1024;
                DateTime nowtime = DateTime.Now;
                string dic = "/UpLoadFile/" + nowtime.ToString("yy/MM/dd/");
                string newFilename = "/UpLoadFile/" + nowtime.ToString("yy/MM/dd/") + Guid.NewGuid().ToString("N") + "." + model.Extension;
                string filepath = Server.MapPath("~" + newFilename);
                if (!System.IO.Directory.Exists(Server.MapPath(dic)))
                {
                    System.IO.Directory.CreateDirectory(Server.MapPath(dic));
                }
                file.SaveAs(filepath);
                //将文档装换为图图片
                if (documentExts.IndexOf(model.Extension.ToLower()) != -1)
                {
                    //图片目录
                    string imagedic = newFilename.Replace("." + model.Extension, "");
                    IImageConverterFactory f = new ImageConverterFactory();
                    IImageConverter imageConverter = f.CreateImageConverter("." + model.Extension);
                    string opath = Server.MapPath("~" + newFilename);
                    string imgpath = Server.MapPath("~" + imagedic + "/");
                    Thread thd = new Thread(new ThreadStart(() => { imageConverter.ConvertToImage(opath, imgpath); }));
                    thd.Start();
                    //DocumentToImage(newFilename, imagedic);
                    model.ImagePath = imagedic;
                }
 
                model.State = 1;
                model.Path = newFilename;
 
                Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(model));
 
            }
            catch (Exception ee)
            {
                model = new FileUpModel() { State = 0, Error = ee.Message };
                Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(model));
                Response.End();
            }
        }
 
        private void DocumentToImage(string filename, string imagedic)
        {
            Thread thd = new Thread(new ThreadStart(() =>
            {
                ConvertWordToImage(Server.MapPath("~" + filename), Server.MapPath("~" + imagedic + "/"), "A", 0, 0, ImageFormat.Png, 0);
            }));
            thd.Start();
 
        }
 
        private string GetExtension(string filename)
        {
            if (string.IsNullOrEmpty(filename))
                return "";
 
            string[] strs = filename.Split('.');
 
            if (strs.Length > 0)
            {
                return strs[strs.Length - 1];
            }
            else
            {
                return "";
            }
        }
 
        public void ConvertWordToImage(string wordInputPath, string imageOutputPath,
            string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, float resolution)
        {
            try
            {
                AsposeLicenseHelper.SetWordsLicense();
                // open word file
                Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);
 
                // validate parameter
                if (doc == null) { throw new Exception("Word文件无效或者Word文件被加密!"); }
                if (imageOutputPath.Trim().Length == 0) { imageOutputPath = Path.GetDirectoryName(wordInputPath); }
                if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); }
                if (imageName.Trim().Length == 0) { imageName = Path.GetFileNameWithoutExtension(wordInputPath); }
                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; }
 
                var imageSaveOptions = new ImageSaveOptions(GetSaveFormat(imageFormat))
                {
                    Resolution = resolution
                };
 
                // start to convert each page
                for (int i = startPageNum; i <= endPageNum; i++)
                {
                    imageSaveOptions.PageIndex = i - 1;
                    doc.Save(Path.Combine(imageOutputPath, imageName) + "_" + i.ToString() + "." + imageFormat.ToString(), imageSaveOptions);
                }
            }
            catch (Exception ex)
            {
 
            }
        }
 
        private SaveFormat GetSaveFormat(ImageFormat imageFormat)
        {
            SaveFormat sf = SaveFormat.Unknown;
            if (imageFormat.Equals(ImageFormat.Png))
                sf = SaveFormat.Png;
            else if (imageFormat.Equals(ImageFormat.Jpeg))
                sf = SaveFormat.Jpeg;
            else if (imageFormat.Equals(ImageFormat.Tiff))
                sf = SaveFormat.Tiff;
            else if (imageFormat.Equals(ImageFormat.Bmp))
                sf = SaveFormat.Bmp;
            else
                sf = SaveFormat.Unknown;
            return sf;
        }
 
 
    }
 
 
    public class FileUpModel
    {
        /// <summary>
        /// 状态  1成功  0失败
        /// </summary>
        public int State
        { get; set; }
 
        /// <summary>
        /// 错误信息
        /// </summary>
        public string Error
        { get; set; }
 
        /// <summary>
        /// 文件大小
        /// </summary>
        public decimal Size
        {
            get;
            set;
        }
 
        /// <summary>
        /// 服务端路径
        /// </summary>
        public string Path
        { get; set; }
 
        public string ImagePath
        { get; set; }
 
        public string Extension
        { get; set; }
 
    }
 
    #region 图片转换器工厂 -> 将被注入到OMCS的多媒体管理器IMultimediaManager的ImageConverterFactory属性
    /// <summary>
    /// 图片转换器工厂。
    /// </summary>
    public class ImageConverterFactory : IImageConverterFactory
    {
        public IImageConverter CreateImageConverter(string extendName)
        {
            if (extendName == ".doc" || extendName == ".docx")
            {
                return new Word2ImageConverter();
            }
 
            if (extendName == ".pdf")
            {
                return new Pdf2ImageConverter();
            }
 
            if (extendName == ".ppt" || extendName == ".pptx")
            {
                return new Ppt2ImageConverter();
            }
            if (extendName == ".xls" || extendName == ".xlsx")
            {
                return new Xls2ImageConverter();
            }
            return null;
        }
 
        public bool Support(string extendName)
        {
            return extendName == ".doc" || extendName == ".docx" || extendName == ".pdf" || extendName == ".ppt" || extendName == ".pptx" || extendName == ".rar";
        }
    }
    #endregion
 
    #region 将word文档转换为图片
    public class Word2ImageConverter : 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;
            ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, null, 200);
        }
 
        /// <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
            {
 
                AsposeLicenseHelper.SetWordsLicense();
                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(Path.GetFileNameWithoutExtension(wordInputPath));
                //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();
                    string imgPath = Path.Combine(imageOutputDirPath, "A") + "_" + i + ".Png";
                    doc.Save(stream, imageSaveOptions);
                    System.Drawing.Image img = System.Drawing.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);
                }
            }
        }
    }
    #endregion
 
    #region 将pdf文档转换为图片
    public class Pdf2ImageConverter : 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;
            ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, 200);
        }
 
        /// <summary>
        /// 将pdf文档转换为图片的方法     
        /// </summary>
        /// <param name="originFilePath">pdf文件路径</param>
        /// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为pdf所在路径</param>      
        /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为pdf总页数</param>      
        /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
        private void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution)
        {
            try
            {
                AsposeLicenseHelper.SetPdfLicense();
                Aspose.Pdf.Document doc = new Aspose.Pdf.Document(originFilePath);
 
                if (doc == null)
                {
                    throw new Exception("pdf文件无效或者pdf文件被加密!");
                }
 
                if (imageOutputDirPath.Trim().Length == 0)
                {
                    imageOutputDirPath = Path.GetDirectoryName(originFilePath);
                }
 
                if (!Directory.Exists(imageOutputDirPath))
                {
                    Directory.CreateDirectory(imageOutputDirPath);
                }
 
                if (startPageNum <= 0)
                {
                    startPageNum = 1;
                }
 
                if (endPageNum > doc.Pages.Count || endPageNum <= 0)
                {
                    endPageNum = doc.Pages.Count;
                }
 
                if (startPageNum > endPageNum)
                {
                    int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
                }
 
                if (resolution <= 0)
                {
                    resolution = 128;
                }
 
                string imageNamePrefix = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(originFilePath));
                for (int i = startPageNum; i <= endPageNum; i++)
                {
                    if (this.cancelled)
                    {
                        break;
                    }
 
                    MemoryStream stream = new MemoryStream();
                    //string imgPath = Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString("000") + ".Png";
                    string imgPath = Path.Combine(imageOutputDirPath, "A") + "_" + i + ".Png";
                    Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(resolution);
                    Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100);
                    jpegDevice.Process(doc.Pages[i], stream);
 
                    Image img = Image.FromStream(stream);
                    Bitmap bm = ESBasic.Helpers.ImageHelper.Zoom(img, 0.6f);
                    bm.Save(imgPath, ImageFormat.Jpeg);
                    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);
                }
            }
        }
    }
    #endregion
 
    #region 将ppt文档转换为图片
    public class Ppt2ImageConverter : IImageConverter
    {
        private Pdf2ImageConverter pdf2ImageConverter;
        public event CbGeneric<int, int> ProgressChanged;
        public event CbGeneric ConvertSucceed;
        public event CbGeneric<string> ConvertFailed;
 
        public void Cancel()
        {
            if (this.pdf2ImageConverter != null)
            {
                this.pdf2ImageConverter.Cancel();
            }
        }
 
        public void ConvertToImage(string originFilePath, string imageOutputDirPath)
        {
            ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, 200);
        }
 
        /// <summary>
        /// 将pdf文档转换为图片的方法     
        /// </summary>
        /// <param name="originFilePath">ppt文件路径</param>
        /// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为pdf所在路径</param>      
        /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为pdf总页数</param>      
        /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
        private void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution)
        {
            try
            {
                AsposeLicenseHelper.SetSlidesLicense();
                Aspose.Slides.Presentation doc = new Aspose.Slides.Presentation(originFilePath);
 
                if (doc == null)
                {
                    throw new Exception("ppt文件无效或者ppt文件被加密!");
                }
 
                if (imageOutputDirPath.Trim().Length == 0)
                {
                    imageOutputDirPath = Path.GetDirectoryName(originFilePath);
                }
 
                if (!Directory.Exists(imageOutputDirPath))
                {
                    Directory.CreateDirectory(imageOutputDirPath);
                }
 
                if (startPageNum <= 0)
                {
                    startPageNum = 1;
                }
 
                if (endPageNum > doc.Slides.Count || endPageNum <= 0)
                {
                    endPageNum = doc.Slides.Count;
                }
 
                if (startPageNum > endPageNum)
                {
                    int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
                }
 
                if (resolution <= 0)
                {
                    resolution = 128;
                }
 
                //先将ppt转换为pdf临时文件
                string tmpPdfPath = originFilePath + ".pdf";
                doc.Save(tmpPdfPath, Aspose.Slides.Export.SaveFormat.Pdf);
 
                //再将pdf转换为图片
                Pdf2ImageConverter converter = new Pdf2ImageConverter();
                converter.ConvertFailed += new CbGeneric<string>(converter_ConvertFailed);
                converter.ConvertSucceed += new CbGeneric(converter_ConvertSucceed);
                converter.ProgressChanged += new CbGeneric<int, int>(converter_ProgressChanged);
                converter.ConvertToImage(tmpPdfPath, imageOutputDirPath);
 
                //删除pdf临时文件
                File.Delete(tmpPdfPath);
 
                if (this.ConvertSucceed != null)
                {
                    this.ConvertSucceed();
                }
            }
            catch (Exception ex)
            {
                if (this.ConvertFailed != null)
                {
                    this.ConvertFailed(ex.Message);
                }
            }
 
            this.pdf2ImageConverter = null;
        }
 
        void converter_ProgressChanged(int done, int total)
        {
            if (this.ProgressChanged != null)
            {
                this.ProgressChanged(done, total);
            }
        }
 
        void converter_ConvertSucceed()
        {
            if (this.ConvertSucceed != null)
            {
                this.ConvertSucceed();
            }
        }
 
        void converter_ConvertFailed(string msg)
        {
            if (this.ConvertFailed != null)
            {
                this.ConvertFailed(msg);
            }
        }
    }
    #endregion
 
    #region Excel
    public class Xls2ImageConverter : IImageConverter
    {
        private Xls2ImageConverter xls2ImageConverter;
        public event CbGeneric<int, int> ProgressChanged;
        public event CbGeneric ConvertSucceed;
        public event CbGeneric<string> ConvertFailed;
 
        public void Cancel()
        {
            if (this.xls2ImageConverter != null)
            {
                this.xls2ImageConverter.Cancel();
            }
        }
 
        public void ConvertToImage(string originFilePath, string imageOutputDirPath)
        {
            ConvertToImage(originFilePath, imageOutputDirPath, 0, 0, 200);
        }
 
        private void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution)
        {
            try
            {
                AsposeLicenseHelper.SetCellsLicense();
                Aspose.Cells.Workbook excel = new Workbook(originFilePath);
 
                if (excel == null)
                {
                    throw new Exception("excel文件无效或者excel文件被加密!");
                }
 
                if (imageOutputDirPath.Trim().Length == 0)
                {
                    imageOutputDirPath = Path.GetDirectoryName(originFilePath);
                }
 
                if (!Directory.Exists(imageOutputDirPath))
                {
                    Directory.CreateDirectory(imageOutputDirPath);
                }
 
                if (startPageNum <= 0)
                {
                    startPageNum = 1;
                }
 
                if (endPageNum > excel.Worksheets.Count || endPageNum <= 0)
                {
                    endPageNum = excel.Worksheets.Count;
                }
 
                if (startPageNum > endPageNum)
                {
                    int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
                }
 
                if (resolution <= 0)
                {
                    resolution = 128;
                }
 
                //先将excel转换为pdf临时文件
                string tmpPdfPath = originFilePath + ".pdf";
                excel.Save(tmpPdfPath, Aspose.Cells.SaveFormat.Pdf);
 
                //再将pdf转换为图片
                Pdf2ImageConverter converter = new Pdf2ImageConverter();
                converter.ConvertFailed += new CbGeneric<string>(converter_ConvertFailed);
                converter.ConvertSucceed += new CbGeneric(converter_ConvertSucceed);
                converter.ProgressChanged += new CbGeneric<int, int>(converter_ProgressChanged);
                converter.ConvertToImage(tmpPdfPath, imageOutputDirPath);
 
                //删除pdf临时文件
                File.Delete(tmpPdfPath);
 
                if (this.ConvertSucceed != null)
                {
                    this.ConvertSucceed();
                }
            }
            catch (Exception ex)
            {
                if (this.ConvertFailed != null)
                {
                    this.ConvertFailed(ex.Message);
                }
            }
 
            this.xls2ImageConverter = null;
        }
 
        void converter_ProgressChanged(int done, int total)
        {
            if (this.ProgressChanged != null)
            {
                this.ProgressChanged(done, total);
            }
        }
 
        void converter_ConvertSucceed()
        {
            if (this.ConvertSucceed != null)
            {
                this.ConvertSucceed();
            }
        }
 
        void converter_ConvertFailed(string msg)
        {
            if (this.ConvertFailed != null)
            {
                this.ConvertFailed(msg);
            }
        }
    }
    #endregion
}

配套aspose.dll
链接:https://pan.baidu.com/s/1kOG4rK7jxDk5yUjYhNa3VQ
提取码:g3iq

  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 26
    评论
### 回答1: 使用AsposePDF换为图片后再换回PDF并进行压缩的代码示例如下: ```java import com.aspose.pdf.*; import java.io.FileOutputStream; import java.io.OutputStream; public class PDFToImage { public static void main(String[] args) { // 创建PdfDocument实例并加载PDF文件 PdfDocument pdf = new PdfDocument("input.pdf"); // 遍历所有页面 for (int i = 1; i <= pdf.getPages().size(); i++) { // 获取当前页面 PdfPage page = pdf.getPages().get_Item(i); // 将当前页面换为图片 com.aspose.pdf.Image image = page.convertToImage(); // 保存图片 image.save("image" + i + ".jpg"); } // 创建新的PdfDocument实例 PdfDocument doc = new PdfDocument(); // 遍历所有图片 for (int i = 1; i <= pdf.getPages().size(); i++) { // 创建新页面并添加到文档中 PdfPage page = doc.getPages().add(); // 从图片创建PdfImage实例 PdfImage pdfImage = new PdfImage("image" + i + ".jpg"); // 将图像添加到页面 page.getResources().getImages().add(pdfImage); // 创建PdfGraphics实例并获取当前页面的图形上下文 PdfGraphics graphics = page.getGraphics(); // 绘制图像 graphics.drawImage(pdfImage, 0, 0, page.getClientRectangle().getWidth(), page.getClientRectangle().getHeight()); } // 设置压缩级别 doc.compress(); // 保存文档 doc.save("output.pdf"); // 关闭文档 doc.close(); } } ``` 请注意,在上面的代码中,需要先安装Aspose.PDF for Java库,可以通过在maven中添加如下依赖来安 ### 回答2: 使用Aspose换Java PDF图片,再将图片换为PDF,并压缩的代码示例如下: ``` import com.aspose.pdf.Document; import com.aspose.pdf.devices.Resolution; import com.aspose.pdf.devices.TiffDevice; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.imageio.ImageIO; import javax.imageio.ImageWriter; import javax.imageio.ImageWriteParam; import javax.imageio.stream.ImageOutputStream; public class PdfToImageToPdf { public static void main(String[] args) { try { // 加载PDF文档 Document pdfDocument = new Document("input.pdf"); // 创建输出文件夹 Path outputFolder = Paths.get("output"); Files.createDirectories(outputFolder); // PDF图片 TiffDevice tiffDevice = new TiffDevice(new Resolution(300)); for (int pageCount = 1; pageCount <= pdfDocument.getPages().size(); pageCount++) { String outputFilePath = outputFolder.resolve("page" + pageCount + ".tiff").toString(); tiffDevice.process(pdfDocument.getPages().get_Item(pageCount), outputFilePath); } // 将图片换为PDF Document imagePdf = new Document(); for (int pageCount = 1; pageCount <= pdfDocument.getPages().size(); pageCount++) { String inputImagePath = outputFolder.resolve("page" + pageCount + ".tiff").toString(); imagePdf.getPages().add().getPageInfo().setHeight(792); imagePdf.getPages().add().getPageInfo().setWidth(612); imagePdf.getPages().add().getResources().getImages().add(inputImagePath); } // 保存换后的PDF imagePdf.save("output.pdf"); // 压缩PDF文件 compressPDF("output.pdf", "compressed.pdf"); } catch (Exception ex) { ex.printStackTrace(); } } private static void compressPDF(String inputFileName, String outputFileName) { try { // 加载PDF文档 Document pdf = new Document(inputFileName); // 设置压缩参数 pdf.compressImages(); // 保存压缩后的PDF pdf.save(outputFileName); } catch (Exception ex) { ex.printStackTrace(); } } } ``` 以上代码会将输入的PDF换为TIFF格式的图片,然后将这些图片换回PDF格式。最后,压缩生成的PDF文件。请确保已经导入Aspose PDF库,并替换文件的输入和输出路径。 ### 回答3: 使用Aspose换Java PDF到图像的代码如下: ```java import com.aspose.pdf.Document; import com.aspose.pdf.ImageFormat; import com.aspose.pdf.devices.Resolution; public class PdfToImageConverter { public static void convertToImages(String inputFilePath, String outputFolderPath) { // Load the PDF document Document pdfDocument = new Document(inputFilePath); // Loop through all the pages and convert each page to an image for (int pageCount = 1; pageCount <= pdfDocument.getPages().size(); pageCount++) { // Define the output image file path String outputImagePath = outputFolderPath + "/page" + pageCount + ".png"; // Convert the PDF page to an image using default resolution pdfDocument.getPages().get_Item(pageCount).save(outputImagePath, ImageFormat.getPng()); } } } ``` 然后,你可以使用Aspose来将这些图像换回PDF,并对生成的PDF进行压缩。代码示例如下: ```java import com.aspose.pdf.Document; import com.aspose.pdf.ImagePlacementAbsorber; import com.aspose.pdf.ImagePlacementProperties; import com.aspose.pdf.Page; public class ImageToPdfConverter { public static void convertToPdf(String inputFolderPath, String outputFilePath) { // Create a new PDF document Document pdfDocument = new Document(); // Get the list of image files in the input folder File[] imageFiles = new File(inputFolderPath).listFiles(); // Loop through all the image files and add them to the PDF document as pages for (File imageFile : imageFiles) { // Create a new page in the PDF document Page pdfPage = pdfDocument.getPages().add(); // Add the image to the PDF page ImagePlacementProperties placementProperties = new ImagePlacementProperties(); placementProperties.setImageFilePath(imageFile.getAbsolutePath()); ImagePlacementAbsorber imagePlacementAbsorber = new ImagePlacementAbsorber(); imagePlacementAbsorber.visit(pdfPage); imagePlacementAbsorber.getPlacementProperties().add(placementProperties); } // Save the PDF document pdfDocument.save(outputFilePath); } } ``` 最后,使用Aspose来对生成的PDF进行压缩。代码示例如下: ```java import com.aspose.pdf.Document; import com.aspose.pdf.OptimizationOptions; public class PdfCompressor { public static void compressPdf(String inputFilePath, String outputFilePath) { // Load the PDF document Document pdfDocument = new Document(inputFilePath); // Enable compression options OptimizationOptions optimizationOptions = new OptimizationOptions(); optimizationOptions.setCompressImages(true); optimizationOptions.setRemoveUnusedObjects(true); // Optimize and save the compressed PDF pdfDocument.optimizeResources(optimizationOptions); pdfDocument.save(outputFilePath); } } ``` 以上是使用Aspose将Java PDF换为图像,然后将图像换回PDF,并对生成的PDF进行压缩的代码示例。请注意,你需要将Aspose PDF库添加到你的项目中,以便能够使用相关的类和方法。
评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值