public static Boolean ConvertWordToJpg(string wordDocName, string jpgPath) { Boolean b = false; try { Aspose.Words.Document doc = new Aspose.Words.Document(wordDocName); Aspose.Words.Saving.ImageSaveOptions iso = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png); iso.Resolution = 768; iso.PaperColor = System.Drawing.Color.Transparent; iso.PrettyFormat = true; iso.UseAntiAliasing = true; for (int i = 0; i < doc.PageCount; i++) { iso.PageIndex = i; doc.Save(jpgPath + i + ".png", iso); } b = true; } catch (Exception e1) { b = false; System.Windows.MessageBox.Show("word转换失败:" + e1.Message); } return(b); }
/// <summary> /// /// </summary> /// <param name="filePath">文件路径</param> /// <param name="currentNo">当前页</param> /// <param name="pageSize">每页大小</param> private static void DocToImg(string filePath, int currentNo, int pageSize) { string filename = Path.GetFileNameWithoutExtension(filePath).ToLower(); var words = new Aspose.Words.Document(filePath); Aspose.Words.Saving.ImageSaveOptions imageSaveOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Jpeg); imageSaveOptions.Resolution = 90; // 默认128 int pageindex = 0; int pagecount = words.PageCount; int num = ((currentNo - 1) * pageSize) + 1; if (pagecount >= (num + pageSize)) { for (int i = num; i < num + pageSize; i++) { pageindex = DocToImgMethod(filename, words, imageSaveOptions, pageindex, i); } } if (pagecount < (num + pageSize) && num < pagecount) { for (int i = num; i < pagecount + 1; i++) { pageindex = DocToImgMethod(filename, words, imageSaveOptions, pageindex, i); } } }
private static void GenerateWordPreview(int previewsFolderId, Stream docStream) { var document = new Aspose.Words.Document(docStream); var pc = document.BuiltInDocumentProperties.Pages; // double-check if (pc == 0) { pc = document.PageCount; } //save the document only if this is the first round if (StartIndex == 0 || pc < 1) { SetPageCount(pc); } var firstIndex = 0; var lastIndex = 0; if (pc > 0) { SetIndexes(StartIndex, pc, out firstIndex, out lastIndex, MaxPreviewCount); for (var i = firstIndex; i <= lastIndex; i++) { //TODO: compare original file timestamp with current timestamp //if (!CheckActuality(file)) // break; try { using (var imgStream = new MemoryStream()) { var options = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png) { PageIndex = i, Resolution = 300 }; document.Save(imgStream, options); if (imgStream.Length == 0) { continue; } SavePreviewAndThumbnail(imgStream, i + 1, previewsFolderId); } } catch (Exception ex) { Logger.WriteError(ContentId, i + 1, ex: ex, startIndex: StartIndex, version: Version); SaveEmptyPreview(i + 1, previewsFolderId); } } } }
/// <summary> /// 添加骑缝章 /// 新添加方式,需要word生成多张图片-图片盖章后再转PDF /// </summary> private void AddPageSeal(string strFileName, int pageCount) { List <string> sealImageList = new List <string>(); //章的图片列表 List <string> fileImageList = new List <string>(); //word生成的图片列表,盖好章的 string directoryName = System.IO.Path.GetDirectoryName(strFileName); //获取文件路径 if (!string.IsNullOrEmpty(TempPath)) { //directoryName = TempPath; } if (pageCount > 1) { sealImageList = kalikoImage(pageCount); Aspose.Words.Saving.ImageSaveOptions iso = new Aspose.Words.Saving.ImageSaveOptions(SaveFormat.Jpeg); iso.Resolution = 256; iso.PrettyFormat = true; iso.UseAntiAliasing = true; for (int i = 0; i < pageCount; i++) { iso.PageIndex = i; string imgPath = directoryName + "\\IMG\\" + i + ".jpg"; //图片路径 oDoc.Save(imgPath, iso); //保存多张图片 Bitmap bm1 = new Bitmap(imgPath); Bitmap bm2 = new Bitmap(sealImageList[i]); Graphics g = Graphics.FromImage(bm1); //盖章操作,需要根据页数计算X轴位置 256 像素下生成图片像素为 2117*2993 //完整章图片像素为425*425,需要根据页数计算X轴位置,Y轴固定中间位置 int x = 2117 - (425 / pageCount); g.DrawImage(bm2, x, 1284, 425 / pageCount, 425); string finishImgPath = Path.GetDirectoryName(imgPath) + "\\Finish\\" + Path.GetFileName(imgPath); if (!System.IO.Directory.Exists(finishImgPath.Substring(0, finishImgPath.LastIndexOf("\\")))) { System.IO.Directory.CreateDirectory(finishImgPath.Substring(0, finishImgPath.LastIndexOf("\\")));//不存在就创建目录 } bm1.Save(finishImgPath, ImageFormat.Jpeg); bm2.Dispose(); g.Dispose(); bm1.Dispose(); fileImageList.Add(finishImgPath); } MergePDFHelper mpHelper = new MergePDFHelper(); string msg = ""; mpHelper.MergePDFFile(fileImageList, strFileName, ref msg);//多张图片合并到PDF } }
///<Summary> /// ConvertEmailToImages method to convert email to messages ///</Summary> public Response ConvertEmailToImages(string fileName, string folderName, string outputType) { if (outputType.Equals("bmp") || outputType.Equals("jpg") || outputType.Equals("png")) { var format = Aspose.Words.SaveFormat.Bmp; if (outputType.Equals("jpg")) { format = Aspose.Words.SaveFormat.Jpeg; } else if (outputType.Equals("png")) { format = Aspose.Words.SaveFormat.Png; } return(ProcessTask(fileName, folderName, "." + outputType, true, true, delegate(string inFilePath, string outPath, string zipOutFolder) { var msg = MapiHelper.GetMailMessageFromFile(inFilePath); var msgStream = new MemoryStream(); msg.Save(msgStream, SaveOptions.DefaultMhtml); msgStream.Position = 0; var options = new Aspose.Words.Saving.ImageSaveOptions(format); options.PageCount = 1; var outfileName = Path.GetFileNameWithoutExtension(fileName) + "_{0}"; var doc = new Document(msgStream); var pageCount = doc.PageCount; for (int i = 0; i < doc.PageCount; i++) { if (pageCount > 1) { outPath = zipOutFolder + "/" + outfileName; options.PageIndex = i; doc.Save(string.Format(outPath, (i + 1) + "." + outputType), options); } else { outPath = zipOutFolder + "/" + Path.GetFileNameWithoutExtension(fileName); options.PageIndex = i; doc.Save(outPath + "." + outputType, options); } } })); } return(new Response { FileName = null, Status = "Output type not found", StatusCode = 500 }); }
/// <summary> ///获取Doc页总数 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static int getDocCount(string filePath) { var words = new Aspose.Words.Document(filePath); Aspose.Words.Saving.ImageSaveOptions imageSaveOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Jpeg); imageSaveOptions.Resolution = 90; // 默认128 int pagecount = words.PageCount; return(pagecount); }
public override void GeneratePreview(Stream docStream, IPreviewGenerationContext context) { var document = new Aspose.Words.Document(docStream); var pc = document.PageCount; // save the document only if this is the first round if (context.StartIndex == 0 || pc < 1) { context.SetPageCount(pc); } if (pc <= 0) { return; } int firstIndex; int lastIndex; var loggedPageError = false; context.SetIndexes(pc, out firstIndex, out lastIndex); for (var i = firstIndex; i <= lastIndex; i++) { try { using (var imgStream = new MemoryStream()) { var options = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png) { PageIndex = i, Resolution = context.PreviewResolution }; document.Save(imgStream, options); if (imgStream.Length == 0) { continue; } context.SavePreviewAndThumbnail(imgStream, i + 1); } } catch (Exception ex) { if (Tools.HandlePageError(ex, i + 1, context, !loggedPageError)) { return; } loggedPageError = true; } } }
/// <summary> /// Convert the documents into images /// </summary> /// <param name="sourcePath"></param> /// <param name="targetPath">Path were the documents were generated</param> /// <param name="currentPage"></param> /// <param name="originalDocumentName"></param> /// <returns></returns> public int Process(string sourcePath, string targetPath, int currentPage, string originalDocumentName, int qualitySet) { var qSet = new QualitySet(); var doc = new Aspose.Words.Document(sourcePath); var targetFileName = targetPath.PathSplit(); var targetFileExt = targetFileName[targetFileName.Length - 1].Split('.'); var options = new Aspose.Words.Saving.ImageSaveOptions(SaveFormat.Jpeg) { PageCount = 1, PageIndex = currentPage - 1, Resolution = qSet.Get(qualitySet).Resolution, JpegQuality = qSet.Get(qualitySet).Quality }; var targetImage = targetPath.Replace("." + targetFileExt[targetFileExt.Length - 1], string.Empty) + currentPage + ConfigurationManager.AppSettings["ImageExtension"]; doc.Save(targetImage, options); return doc.PageCount; }
private List <PageInfo> ConvertWithWords(String inputFile, ImageConversionOptions options) { Document doc = new Document(inputFile); // Adjust margins foreach (Section section in doc.Sections) { section.PageSetup.LeftMargin = (section.PageSetup.LeftMargin / 2.54) / 2; section.PageSetup.RightMargin = (section.PageSetup.RightMargin / 2.54) / 2; section.PageSetup.TopMargin = (section.PageSetup.TopMargin / 2.54) / 2; section.PageSetup.BottomMargin = (section.PageSetup.BottomMargin / 2.54) / 2; } if (options.BinarisationAlgorithm == BinarisationAlgorithm.Default) { options.BinarisationAlgorithm = BinarisationAlgorithm.OtsuThreshold; } var pages = new List <PageInfo>(); var saveOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png); saveOptions.Resolution = options.Resolution; saveOptions.PageCount = 1; for (int i = 0; i < doc.PageCount; i++) { saveOptions.PageIndex = i; using (MemoryStream ms = new MemoryStream()) { // Save the page to the memory stream doc.Save(ms, saveOptions); // Set the position back to the start of the stream ms.Seek(0, SeekOrigin.Begin); // Convert the page and add it to the list pages.AddRange(ImageProcessingEngine.Instance.Convert(ms, options)); } } return(pages); }
/// <summary> /// /// </summary> /// <param name="sourcePath"></param> /// <param name="targetPath"></param> /// <param name="currentPage"></param> /// <param name="originalDocumentName"></param> /// <returns></returns> public int Process(string sourcePath, string targetPath, int currentPage, string originalDocumentName, int qualitySet) { var msg = MailMessage.Load(sourcePath, MailMessageLoadOptions.DefaultMsg); var targetFileName = targetPath.PathSplit(); var targetFileExt = targetFileName[targetFileName.Length - 1].Split('.'); var ms = new MemoryStream(); msg.Save(ms, MailMessageSaveType.MHtmlFromat); var loadOptions = new LoadOptions { LoadFormat = (LoadFormat)Aspose.Cells.LoadFormat.MHtml }; var document = new Aspose.Words.Document(ms, loadOptions); var qSet = new QualitySet(); var options = new Aspose.Words.Saving.ImageSaveOptions(SaveFormat.Jpeg) { PageCount = 1, PageIndex = currentPage - 1, Resolution = qSet.Get(qualitySet).VerticalResolution, JpegQuality = qSet.Get(qualitySet).Quality }; var targetImage = targetPath.Replace("." + targetFileExt[targetFileExt.Length - 1], string.Empty) + currentPage + ConfigurationManager.AppSettings["ImageExtension"]; document.Save(targetImage, options); return document.PageCount; }
void SaveDocumentStreamToFolder(Stream stream, string fileName, string outPath, SaveFormat format) { var document = new Document(stream); var shortFileName = Path.GetFileNameWithoutExtension(fileName); var formatExt = "." + format.ToString().ToLowerInvariant(); switch (format) { //case SaveFormat.Svg: //case SaveFormat.Tiff: case SaveFormat.Png: case SaveFormat.Bmp: case SaveFormat.Emf: case SaveFormat.Jpeg: case SaveFormat.Gif: { var pageCount = document.PageCount; if (pageCount == 1) { document.Save(Path.Combine(outPath, shortFileName + formatExt), format); break; } var options = new Aspose.Words.Saving.ImageSaveOptions(format); options.PageCount = 1; for (int i = 0; i < document.PageCount; i++) { options.PageIndex = i; document.Save(Path.Combine(outPath, shortFileName + i + formatExt), format); } break; } default: document.Save(Path.Combine(outPath, shortFileName + formatExt), format); break; } }
/// <summary> /// 将word文档转换为jpg图片 /// </summary> /// <param name="filePath">选择文件的路径</param> /// <param name="fileName">选择文件的文件名</param> private void wordConverToImage(string filePath, string fileName) { try { Aspose.Words.Document document = new Aspose.Words.Document(filePath); Aspose.Words.Saving.ImageSaveOptions imageSaveOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Jpeg); imageSaveOptions.Resolution = 300; for (int i = 0; i < document.PageCount; i++) { document.Save(fileName.Split('.')[0] + ".jpg", imageSaveOptions); } lblConver.Visible = false; DialogResult dialogResult = MessageBox.Show("转换成功,是否打开转换图片文件夹", "转换结果", MessageBoxButtons.OKCancel); if (dialogResult == DialogResult.OK) { System.Diagnostics.Process.Start("Explorer.exe", Environment.CurrentDirectory); } } catch (Exception) { lblConver.Visible = false; MessageBox.Show("转换失败", "转换结果"); } }
/// <summary> /// 将Doc转换为图片 /// </summary> /// <param name="filepath"></param> /// <param name="imageFolderName"></param> /// <param name="imageFolderRootPath"></param> public void ConvertToImage(string filepath, string imageFolderName, string imageFolderRootPath) { if (!Directory.Exists(imageFolderRootPath)) { ///若路径不存在,创建路径 Directory.CreateDirectory(imageFolderRootPath); } Aspose.Words.Document doc = new Aspose.Words.Document(filepath); for (var i = 0; i < doc.PageCount; i++) { Aspose.Words.Saving.ImageSaveOptions options = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png); options.DmlEffectsRenderingMode = Aspose.Words.Saving.DmlEffectsRenderingMode.Fine; options.PageIndex = i; string imageFilePath = string.Format(@"{0}\{1}\{2}.png", imageFolderRootPath, imageFolderName, i); doc.Save(imageFilePath, options); } string jsFileName = string.Format(@"{0}\{1}\{2}.js", imageFolderRootPath, imageFolderName, "info"); var fileType = (filepath.EndsWith(".docx")) ? "docx" : "doc"; File.WriteAllText(jsFileName, "var imageInfo={PageCount:" + doc.PageCount + ",FileType:'" + fileType + "'}"); }
/// <summary> /// DocToImgMethod /// </summary> /// <param name="filename"></param> /// <param name="words"></param> /// <param name="imageSaveOptions"></param> /// <param name="pageindex"></param> /// <param name="i"></param> /// <returns></returns> private static int DocToImgMethod(string filename, Aspose.Words.Document words, Aspose.Words.Saving.ImageSaveOptions imageSaveOptions, int pageindex, int i) { try { string imgpath = imageDirectoryPath + "/" + filename + "_" + i + ".jpeg"; if (!File.Exists(imgpath)) { imageSaveOptions.PageIndex = pageindex; words.Save(imgpath, imageSaveOptions); pageindex++; } } catch (Exception) { } return(pageindex); }
/// <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文档转换为图片的方法 /// </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 bool ConvertToImageNew(string sourcePath, string wordInputPath, string imageOutputDirPath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution, int attachmentId, out string message) { try { StringBuilder sb = new StringBuilder(); System.Threading.Thread.Sleep(200); 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; sb.Append(string.Format("delete from PreviewFile where AttachmentId={0}", attachmentId)); for (int i = startPageNum; i <= endPageNum; i++) { if (this.cancelled) { break; } MemoryStream stream = new MemoryStream(); imageSaveOptions.PageIndex = i - 1; string imgPath = Path.Combine(imageOutputDirPath, i.ToString()) + "." + 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); } sb.Append(string.Format("insert into PreviewFile(AttachmentId,SavePath,CreateTime)values({0},'{1}','{2}');", attachmentId, imgPath.Replace(sourcePath, "").Replace("\\", "/"), DateTime.Now)); } if (this.cancelled) { message = "文档操作失败;"; return(false); } if (this.ConvertSucceed != null) { this.ConvertSucceed(); //执行数据库插入操作 } int result = SqlHelper.ExecteNonQueryText(sb.ToString(), null); message = result > 0?"操作成功":"数据库操作失败;"; return(result > 0); } catch (Exception ex) { if (this.ConvertFailed != null) { this.ConvertFailed(ex.Message); } message = ex.Message.ToString(); return(false); } }
/// <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> public void WordToImage(Document file, string imageOutputDirPath, int startPageNum, int endPageNum, ImageFormat imageFormat, int resolution = 128) { file.isyl = "1"; new DocumentB().Update(file); Task <string> TaskCover = Task.Factory.StartNew <string>(() => { Aspose.Words.Document doc = new Aspose.Words.Document(file.FullPath); if (doc == null) { Logger.LogError("Word文件无效或者Word文件被加密!"); } if (imageOutputDirPath.Trim().Length == 0) { imageOutputDirPath = Path.GetDirectoryName(file.FullPath); } 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; } string imageName = Path.GetFileNameWithoutExtension(file.FullPath); Aspose.Words.Saving.ImageSaveOptions imageSaveOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png); imageSaveOptions.Resolution = resolution; for (int i = startPageNum; i <= endPageNum; i++) { MemoryStream stream = new MemoryStream(); imageSaveOptions.PageIndex = i - 1; string imgPath = Path.Combine(imageOutputDirPath, imageName) + "_" + i.ToString() + "." + imageFormat.ToString(); doc.Save(stream, imageSaveOptions); Image img = Image.FromStream(stream); Bitmap bm = new Bitmap(img); bm.Save(imgPath, imageFormat); img.Dispose(); stream.Dispose(); bm.Dispose(); } file.ylinfo = endPageNum.ToString(); file.isyl = "2"; new DocumentB().Update(file); return("success"); }); }
/// <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, i.ToString()) + "." + 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); } } }
public List <PageInfo> Convert(String inputFile, ImageConversionOptions options) { var ext = (options.ProcessAs ?? Path.GetExtension(inputFile).Trim('.', ' ')).ToUpper(); var isTextFile = (ext == "TXT"); // Open the document Document doc = OpenDocument(inputFile, ext); // Specific processing for MHT, HTM and HTML if (ext == "MHT" || ext == "HTM" || ext == "HTML" || isTextFile) { // Adjust Margins, Paper Size and Orientation foreach (Section section in doc.Sections) { section.PageSetup.PaperSize = PaperSize.A4; section.PageSetup.Orientation = isTextFile ? Orientation.Landscape : Orientation.Portrait; section.PageSetup.LeftMargin = (section.PageSetup.LeftMargin / 2.54) / 2; section.PageSetup.RightMargin = (section.PageSetup.RightMargin / 2.54) / 2; section.PageSetup.TopMargin = (section.PageSetup.TopMargin / 2.54) / 2; section.PageSetup.BottomMargin = (section.PageSetup.BottomMargin / 2.54) / 2; if (isTextFile) { FontChanger changer = new FontChanger("Courier New"); doc.Accept(changer); } else { // Get the portrait and landscape widths var portraitWidth = section.PageSetup.PageWidth - section.PageSetup.LeftMargin - section.PageSetup.RightMargin; var landscapeWidth = section.PageSetup.PageHeight - section.PageSetup.TopMargin - section.PageSetup.BottomMargin; // Adjust table fit foreach (Table table in section.Body.Tables) { var width = GetTableWidth(table); if (width > portraitWidth) { if (section.PageSetup.Orientation != Orientation.Landscape) { section.PageSetup.Orientation = Orientation.Landscape; } if (width > landscapeWidth) { table.AutoFit(AutoFitBehavior.AutoFitToWindow); } } } // Get the usable width/height var usableWidth = section.PageSetup.PageWidth - section.PageSetup.LeftMargin - section.PageSetup.RightMargin; var usableHeight = section.PageSetup.PageHeight - section.PageSetup.TopMargin - section.PageSetup.BottomMargin; // Adjust image size foreach (Shape shape in section.GetChildNodes(NodeType.Shape, true)) { if (shape.HasImage && (shape.Width > usableWidth || shape.Height > usableHeight)) { // Adjust shape size var scale = Math.Min((usableWidth / shape.Width), (usableHeight / shape.Height)); shape.Width = shape.Width * scale; shape.Height = shape.Height * scale; } } } } if (!isTextFile) { // Update table layout following adjustments doc.UpdateTableLayout(); } } if (options.BinarisationAlgorithm == BinarisationAlgorithm.Default) { options.BinarisationAlgorithm = BinarisationAlgorithm.OtsuThreshold; } var pages = new List <PageInfo>(); var saveOptions = new Aspose.Words.Saving.ImageSaveOptions(SaveFormat.Png); saveOptions.Resolution = options.Resolution; saveOptions.PageCount = 1; for (int i = 0; i < doc.PageCount; i++) { saveOptions.PageIndex = i; using (MemoryStream ms = new MemoryStream()) { // Save the page to the memory stream doc.Save(ms, saveOptions); // Set the position back to the start of the stream ms.Seek(0, SeekOrigin.Begin); try { // Convert the page and add it to the list pages.AddRange(ImageProcessingEngine.Instance.Convert(ms, options)); } catch (Exception e) { if (e.Message == "Decode: Unknown or wrong format [Stream][CiImage::Open]") { // This is a known error, there is an occasional issue with the ClearImage Open method // Loading the stream into a Bitmap object works around the issue for now... using (var stream = new MemoryStream(ms.ToArray())) using (var bitmap = (Bitmap)Bitmap.FromStream(stream, true, false)) { pages.AddRange(ImageProcessingEngine.Instance.Convert(bitmap, options)); } } else { throw; } } } } return(pages); }