static void Example1() { // Load a Word file into the DocumentModel object. var document = DocumentModel.Load("Input.docx"); var section = document.Sections[0]; // Calculate the default image width based on the page size and DPI resolution. var widthInPoints = section.PageSetup.PageWidth; var resolution = 300; var widthInPixels = widthInPoints * resolution / 72; var imageOptions = new ImageSaveOptions(ImageSaveFormat.Png) { // Select the first Word page. PageNumber = 0, // Set the DPI resolution. DpiX = resolution, DpiY = resolution, // Set the image width to half and keep the aspect ratio. Width = widthInPixels / 2 }; // Save the DocumentModel object to a PNG file. document.Save("Output.png", imageOptions); }
static void Main(string[] args) { // Check for license and apply if exists string licenseFile = AppDomain.CurrentDomain.BaseDirectory + "Aspose.Words.lic"; if (File.Exists(licenseFile)) { // Apply Aspose.Words API License Aspose.Words.License license = new Aspose.Words.License(); // Place license file in Bin/Debug/ Folder license.SetLicense("Aspose.Words.lic"); } // define document file location string fileDir = "../../data/"; // load the document. Document doc = new Document(fileDir + "document.doc"); //Create an ImageSaveOptions object to pass to the Save method ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png); // Save each page of the document as Png in data folder for (int i = 0; i < doc.PageCount; i++) { options.PageIndex = i; doc.Save(string.Format(i + "WordDocumentAsPNG out.Png", i), options); } }
public static void ConvertDocumentToImage() { // ExStart:ConvertSpecificPageToImage // ExFor:Document // ExFor:ImageSaveOptions // ExFor:ImageSaveOptions.PageIndex // ExSummary:Shows how to save a document in png format. // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadingAndSaving(); // Load the document into Aspose.Note. Document oneFile = new Document(dataDir + "Aspose.one"); // Initialize ImageSaveOptions object ImageSaveOptions opts = new ImageSaveOptions(SaveFormat.Png) { // Set page index PageIndex = 1 }; dataDir = dataDir + "ConvertSpecificPageToImage_out.png"; // Save the document as PNG. oneFile.Save(dataDir, opts); // ExEnd:ConvertSpecificPageToImage Console.WriteLine("\nOneNote document converted successfully to image.\nFile saved at " + dataDir); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName); // ExStart:PrintProjectPagesToSeparateFiles Project project = new Project(dataDir + "CreateProject2.mpp"); ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFileFormat.PNG); saveOptions.StartDate = project.Get(Prj.StartDate).AddDays(-3); saveOptions.EndDate = project.Get(Prj.FinishDate); saveOptions.MarkCriticalTasks = true; saveOptions.LegendOnEachPage = false; saveOptions.Gridlines = new List <Gridline>(); Gridline gridline = new Gridline(); gridline.GridlineType = GridlineType.GanttRow; gridline.Color = Color.CornflowerBlue; gridline.Pattern = LinePattern.Dashed; saveOptions.Gridlines.Add(gridline); // Save the whole project layout to one file project.Save(dataDir + "PrintProjectPagesToSeparateFiles1_out.png", (SaveOptions)saveOptions); // Save project layout to separate files saveOptions.SaveToSeparateFiles = true; project.Save(dataDir + "PrintProjectPagesToSeparateFiles2_out.png", (SaveOptions)saveOptions); // ExEnd:PrintProjectPagesToSeparateFiles }
public void SVGtoJPGWithImageSaveOptionsTest() { // Prepare a path to a source SVG file string documentPath = Path.Combine(DataDir, "flower.svg"); // Prepare a path for converted file saving string savePath = Path.Combine(OutputDir, "flower-options.jpg"); // Initialize an SVG document from the file using var document = new SVGDocument(documentPath); // Initialize ImageSaveOptions. Set up the resolutions, SmoothingMode and change the background color to AliceBlue var options = new ImageSaveOptions(ImageFormat.Jpeg) { SmoothingMode = SmoothingMode.HighQuality, HorizontalResolution = 200, VerticalResolution = 200, BackgroundColor = Color.AliceBlue }; // Convert SVG to JPG Converter.ConvertSVG(document, options, savePath); Assert.True(File.Exists(Path.Combine(OutputDir, "flower-options_1.jpg"))); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName); // ExStart:PrintProjectPagesToSeparateFiles Project project = new Project(dataDir + "CreateProject2.mpp"); ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFileFormat.PNG); saveOptions.StartDate = project.Get(Prj.StartDate).AddDays(-3); saveOptions.EndDate = project.Get(Prj.FinishDate); saveOptions.MarkCriticalTasks = true; saveOptions.LegendOnEachPage = false; saveOptions.Gridlines = new List<Gridline>(); Gridline gridline = new Gridline(); gridline.GridlineType = GridlineType.GanttRow; gridline.Color = Color.CornflowerBlue; gridline.Pattern = LinePattern.Dashed; saveOptions.Gridlines.Add(gridline); // Save the whole project layout to one file project.Save(dataDir + "PrintProjectPagesToSeparateFiles1_out.png", saveOptions); // Save project layout to separate files saveOptions.SaveToSeparateFiles = true; project.Save(dataDir + "PrintProjectPagesToSeparateFiles2_out.png", saveOptions); // ExEnd:PrintProjectPagesToSeparateFiles }
public void FloydSteinbergDithering() { //ExStart //ExFor:ImageBinarizationMethod //ExFor:ImageSaveOptions.ThresholdForFloydSteinbergDithering //ExFor:ImageSaveOptions.TiffBinarizationMethod //ExSummary: Shows how to control the threshold for TIFF binarization in the Floyd-Steinberg method Document doc = new Document(MyDir + "Rendering.docx"); ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff) { TiffCompression = TiffCompression.Ccitt3, ImageColorMode = ImageColorMode.Grayscale, TiffBinarizationMethod = ImageBinarizationMethod.FloydSteinbergDithering, // The default value of this property is 128. The higher value, the darker image ThresholdForFloydSteinbergDithering = 254 }; doc.Save(ArtifactsDir + "ImageSaveOptions.FloydSteinbergDithering.tiff", options); //ExEnd #if NET462 || JAVA TestUtil.VerifyImage(794, 1123, ArtifactsDir + "ImageSaveOptions.FloydSteinbergDithering.tiff"); #endif }
public void EditImage() { //ExStart //ExFor:ImageSaveOptions.HorizontalResolution //ExFor:ImageSaveOptions.ImageBrightness //ExFor:ImageSaveOptions.ImageContrast //ExFor:ImageSaveOptions.SaveFormat //ExFor:ImageSaveOptions.Scale //ExFor:ImageSaveOptions.VerticalResolution //ExSummary:Shows how to edit image. Document doc = new Document(MyDir + "Rendering.docx"); // When saving the document as an image, we can use an ImageSaveOptions object to edit various aspects of it ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png) { ImageBrightness = 0.3f, // 0 - 1 scale, default at 0.5 ImageContrast = 0.7f, // 0 - 1 scale, default at 0.5 HorizontalResolution = 72f, // Default at 96.0 meaning 96dpi, image dimensions will be affected if we change resolution VerticalResolution = 72f, // Default at 96.0 meaning 96dpi Scale = 96f / 72f // Default at 1.0 for normal scale, can be used to negate resolution impact in image size }; doc.Save(ArtifactsDir + "ImageSaveOptions.EditImage.png", options); //ExEnd TestUtil.VerifyImage(794, 1123, ArtifactsDir + "ImageSaveOptions.EditImage.png"); }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); // Open the document. Document doc = new Document(dataDir + "TestFile.doc"); //ExStart //ExId:SaveAsMultipageTiff_save //ExSummary:Convert document to TIFF. // Save the document as multipage TIFF. doc.Save(dataDir + "TestFile Out.tiff"); //ExEnd //ExStart //ExId:SaveAsMultipageTiff_SaveWithOptions //ExSummary:Convert to TIFF using customized options //Create an ImageSaveOptions object to pass to the Save method ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff); options.PageIndex = 0; options.PageCount = 2; options.TiffCompression = TiffCompression.Ccitt4; options.Resolution = 160; doc.Save(dataDir + "TestFileWithOptions Out.tiff", options); //ExEnd }
public void GraphicsQuality() { //ExStart //ExFor:GraphicsQualityOptions //ExFor:GraphicsQualityOptions.CompositingMode //ExFor:GraphicsQualityOptions.CompositingQuality //ExFor:GraphicsQualityOptions.InterpolationMode //ExFor:GraphicsQualityOptions.StringFormat //ExFor:GraphicsQualityOptions.SmoothingMode //ExFor:GraphicsQualityOptions.TextRenderingHint //ExFor:ImageSaveOptions.GraphicsQualityOptions //ExSummary:Shows how to set render quality options when converting documents to image formats. Document doc = new Document(MyDir + "Rendering.docx"); GraphicsQualityOptions qualityOptions = new GraphicsQualityOptions { SmoothingMode = SmoothingMode.AntiAlias, TextRenderingHint = TextRenderingHint.ClearTypeGridFit, CompositingMode = CompositingMode.SourceOver, CompositingQuality = CompositingQuality.HighQuality, InterpolationMode = InterpolationMode.High, StringFormat = StringFormat.GenericTypographic }; ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Jpeg); saveOptions.GraphicsQualityOptions = qualityOptions; doc.Save(ArtifactsDir + "ImageSaveOptions.GraphicsQuality.jpg", saveOptions); //ExEnd TestUtil.VerifyImage(794, 1122, ArtifactsDir + "ImageSaveOptions.GraphicsQuality.jpg"); }
public static void Run() { try { // ExStart:ExportOfHiddenVisioPagesToImage // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Intro(); // Load an existing Visio Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx"); // Get a particular page Page page = diagram.Pages.GetPage("Flow 2"); // Set Visio page visiblity page.PageSheet.PageProps.UIVisibility.Value = BOOL.True; // Initialize PDF save options ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.JPEG); // Set export option of hidden Visio pages options.ExportHiddenPage = false; // Save the Visio diagram diagram.Save(dataDir + "ExportOfHiddenVisioPagesToImage_out.jpeg", options); // ExEnd:ExportOfHiddenVisioPagesToImage } catch (System.Exception ex) { System.Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx."); } }
public void CheckThatAllMethodsArePresent() { HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions(); htmlFixedSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); ImageSaveOptions imageSaveOptions = new ImageSaveOptions(SaveFormat.Png); imageSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); pdfSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); PsSaveOptions psSaveOptions = new PsSaveOptions(); psSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); SvgSaveOptions svgSaveOptions = new SvgSaveOptions(); svgSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); XamlFixedSaveOptions xamlFixedSaveOptions = new XamlFixedSaveOptions(); xamlFixedSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); XpsSaveOptions xpsSaveOptions = new XpsSaveOptions(); xpsSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); }
/// <summary> /// 另存为Xps文档 /// </summary> /// <param name="data">数据</param> /// <param name="fileName">文件名称</param> public void SaveAsJpeg(object data, string fileName) { if (doc == null) { throw new Exception(TEMPLATEFILE_NOT_OPEN); } fileName = WordOperator.InitalizeValideFileName(fileName); string extension = System.IO.Path.GetExtension(fileName); if (string.IsNullOrEmpty(extension)) { fileName += ".jpg"; } else { fileName = extension == ".jpg" ? fileName : fileName.Replace(extension, ".jpg"); } bool success = OnSetParamValue(data); if (success) { WordOperator.InitalzieDirectory(fileName); ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Jpeg); options.Resolution = 300; doc.Save(fileName, options); Close(); } }
private void GeneratePreviewImages() { var previewFile = Path.Combine((string)asm.GetType("Workshare.Utilities.LocalCopyOfFileManager").GetProperty("ManagedFolder").GetValue(_lcfm), "0.jpg"); var license = new License(); license.SetLicense(GetLicence()); var document = new Document(FileName); var saveOptions = new ImageSaveOptions(SaveFormat.Jpeg) { UseHighQualityRendering = true, JpegQuality = 100 }; for (var i = 0; i < document.PageCount; i++) { saveOptions.PageIndex = i; var pageImageFileName = string.Format("{0}{1}.jpg", (string)asm.GetType("Workshare.Utilities.LocalCopyOfFileManager").GetProperty("ManagedFolder").GetValue(_lcfm) + "\\", i); document.Save(pageImageFileName, saveOptions); if (PreviewImage == null) { PreviewImage = new Bitmap(previewFile); Events.RaiseEvent(this, ThumbnailGenerated); } PreviewImages.Add(new Bitmap(pageImageFileName)); } }
static void Example3() { // Load a Word file. var document = DocumentModel.Load("Input.docx"); var imageOptions = new ImageSaveOptions(ImageSaveFormat.Png); // Get Word pages. var pages = document.GetPaginator().Pages; // Create a ZIP file for storing PNG files. using (var archiveStream = File.OpenWrite("Output.zip")) using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create)) { // Iterate through the Word pages. for (int pageIndex = 0; pageIndex < pages.Count; pageIndex++) { DocumentModelPage page = pages[pageIndex]; // Create a ZIP entry for each document page. var entry = archive.CreateEntry($"Page {pageIndex + 1}.png"); // Save each document page as a PNG image to the ZIP entry. using (var imageStream = new MemoryStream()) using (var entryStream = entry.Open()) { page.Save(imageStream, imageOptions); imageStream.CopyTo(entryStream); } } } }
public void ConvertMDtoJPGWithImageSaveOptionsTest() { // Prepare a path to a source Markdown file string sourcePath = Path.Combine(DataDir, "nature.md"); // Prepare a path for converted file saving string savePath = Path.Combine(OutputDir, "nature-options.jpg"); // Convert Markdown to HTML using var document = Converter.ConvertMarkdown(sourcePath); // Initialize ImageSaveOptions var options = new ImageSaveOptions(ImageFormat.Jpeg) { SmoothingMode = SmoothingMode.HighQuality, HorizontalResolution = 200, VerticalResolution = 200, BackgroundColor = Color.AliceBlue }; options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(600, 950), new Margin(30, 20, 10, 10)); // Convert HTML document to JPG image file format Converter.ConvertHTML(document, options, savePath); Assert.True(File.Exists(Path.Combine(OutputDir, "nature-options_1.jpg"))); }
/// <summary> /// Word转为图片 /// </summary> /// <param name="source">word文件路径</param> /// <param name="target">图片保存的文件夹路径</param> /// <param name="resolution">分辨率</param> /// <param name="format">图片格式</param> public static bool ConverToImage(string source, string target, int resolution = 300, AsposeConvertDelegate d = null) { double percent = 0.0; int page = 0; int total = 0; double second = 0; string path = ""; string message = ""; DateTime startTime = DateTime.Now; if (!FileUtil.CreateDirectory(target)) { throw new DirectoryNotFoundException(); } if (!File.Exists(source)) { throw new FileNotFoundException(); } if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.1; message = "正在解析文件!"; d.Invoke(percent, page, total, second, path, message); } Diagram diagram = new Diagram(source); total = diagram.Pages.Count; if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.2; message = "开始转换文件,共" + total + "页!"; d.Invoke(percent, page, total, second, path, message); } logger.Info("ConverToImage - source=" + source + ", target=" + target + ", resolution=" + resolution + ", pageCount=" + total); ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.PNG); options.Resolution = resolution; for (page = 0; page < total; page++) { options.PageIndex = page; using (MemoryStream stream = new MemoryStream()) { diagram.Save(stream, options); Bitmap bitmap = new Bitmap(stream); path = target + "\\" + (page + 1) + "_.png"; bitmap.Save(path, ImageFormat.Png); } if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.2 + (page + 1) * 0.8 / total; message = "正在转换第" + (page + 1) + "/" + total + "页!"; d.Invoke(percent, (page + 1), total, second, path, message); } } return(true); }
public void ConvertHTMLtoPNGWithImageSavaOptionsTest() { // Prepare a path to a source HTML file string documentPath = Path.Combine(DataDir, "nature.html"); // Prepare a path for converted file saving string savePath = Path.Combine(OutputDir, "nature-output-options.png"); // Initialize an HTML document from the file using var document = new HTMLDocument(documentPath); // Initialize ImageSaveOptions var options = new ImageSaveOptions() { SmoothingMode = SmoothingMode.Default, HorizontalResolution = 100, VerticalResolution = 100, BackgroundColor = Color.Beige }; // Convert HTML to PNG Converter.ConvertHTML(document, options, savePath); Assert.True(File.Exists(Path.Combine(OutputDir, "nature-output-options_1.png"))); }
static void Main(string[] args) { // Sample infrastructure. string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar; string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath; // Open the document. Document doc = new Document(dataDir + "SaveAsMutiPageTiff.doc"); //ExStart //ExId:SaveAsMultipageTiff_save //ExSummary:Convert document to TIFF. // Save the document as multipage TIFF. doc.Save(dataDir + "SaveAsMutiPageTiff Out.tiff"); //ExEnd //ExStart //ExId:SaveAsMultipageTiff_SaveWithOptions //ExSummary:Convert to TIFF using customized options //Create an ImageSaveOptions object to pass to the Save method ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff); options.PageIndex = 0; options.PageCount = doc.PageCount; options.TiffCompression = TiffCompression.Ccitt4; options.Resolution = 160; doc.Save(dataDir + "TiffFileWithOptions Out.tiff", options); //ExEnd }
private static void SaveBlackWhiteTIFFwithLZW(Document doc, string dataDir, bool highSensitivity) { // Select the TIFF format with 100 dpi. ImageSaveOptions imgOpttiff = new ImageSaveOptions(SaveFormat.Tiff); imgOpttiff.Resolution = 100; // Apply black & white filter. Set very high sensitivity to gray color. imgOpttiff.TiffCompression = TiffCompression.Lzw; imgOpttiff.ImageColorMode = ImageColorMode.BlackAndWhite; // Set brightness and contrast according to sensitivity. if (highSensitivity) { imgOpttiff.ImageBrightness = 0.4f; imgOpttiff.ImageContrast = 0.3f; } else { imgOpttiff.ImageBrightness = 0.9f; imgOpttiff.ImageContrast = 0.9f; } // Save multipage TIFF. doc.Save(string.Format("{0}{1}", dataDir, "result black and white.tiff"), imgOpttiff); Console.WriteLine("\nDocument converted to TIFF successfully with black and white.\nFile saved at " + dataDir + "Result black and white.tiff"); }
public void CheckThatAllMethodsArePresent() { HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions(); htmlFixedSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); ImageSaveOptions imageSaveOptions = new ImageSaveOptions(SaveFormat.Png); imageSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); pdfSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); PsSaveOptions psSaveOptions = new PsSaveOptions(); psSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); SvgSaveOptions svgSaveOptions = new SvgSaveOptions(); svgSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); SwfSaveOptions swfSaveOptions = new SwfSaveOptions(); swfSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); XamlFixedSaveOptions xamlFixedSaveOptions = new XamlFixedSaveOptions(); xamlFixedSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); XpsSaveOptions xpsSaveOptions = new XpsSaveOptions(); xpsSaveOptions.PageSavingCallback = new CustomPageFileNamePageSavingCallback(); }
public static void Run() { try { //ExStart:ExportOfHiddenVisioPagesToImage // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Intro(); // load an existing Visio Diagram diagram = new Diagram(dataDir + "Drawing1.vsdx"); // get a particular page Page page = diagram.Pages.GetPage("Flow 2"); // set Visio page visiblity page.PageSheet.PageProps.UIVisibility.Value = BOOL.False; // initialize PDF save options ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.JPEG); // set export option of hidden Visio pages options.ExportHiddenPage = false; //Save the Visio diagram diagram.Save(dataDir + "ExportOfHiddenVisioPagesToImage_Out.jpeg", options); //ExEnd:ExportOfHiddenVisioPagesToImage } catch (System.Exception ex) { System.Console.WriteLine("This example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http://www.aspose.com/purchase/default.aspx."); } }
public static void Run() { // ExStart:PrintProjectPagesToSeparateFiles // The path to the documents directory. string dataDir = RunExamples.GetDataDir_PrintingAndExporting(); Project project = new Project(dataDir + "Project5.mpp"); ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFileFormat.PNG); saveOptions.StartDate = project.Get(Prj.StartDate).AddDays(-3); saveOptions.EndDate = project.Get(Prj.FinishDate); saveOptions.MarkCriticalTasks = true; saveOptions.LegendOnEachPage = false; saveOptions.Gridlines = new List <Gridline>(); Gridline gridline = new Gridline(); gridline.GridlineType = GridlineType.GanttRow; gridline.Color = Color.CornflowerBlue; gridline.Pattern = LinePattern.Dashed; saveOptions.Gridlines.Add(gridline); // Save the whole project layout to one file project.Save(dataDir + "CustomerFeedback1_out.png", saveOptions); // Save project layout to separate files saveOptions.SaveToSeparateFiles = true; project.Save(dataDir + "CustomerFeedback2_out.png", saveOptions); // ExEnd:PrintProjectPagesToSeparateFiles }
public static void Run() { // ExStart:SaveAsMultipageTiff // The path to the documents directory. string dataDir = RunExamples.GetDataDir_RenderingAndPrinting(); // Open the document. Document doc = new Document(dataDir + "TestFile Multipage TIFF.doc"); // ExStart:SaveAsTIFF // Save the document as multipage TIFF. doc.Save(dataDir + "TestFile Multipage TIFF_out.tiff"); // ExEnd:SaveAsTIFF // ExStart:SaveAsTIFFUsingImageSaveOptions // Create an ImageSaveOptions object to pass to the Save method ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff); options.PageIndex = 0; options.PageCount = 2; options.TiffCompression = TiffCompression.Ccitt4; options.Resolution = 160; dataDir = dataDir + "TestFileWithOptions_out.tiff"; doc.Save(dataDir, options); // ExEnd:SaveAsTIFFUsingImageSaveOptions // ExEnd:SaveAsMultipageTiff Console.WriteLine("\nDocument saved as multi-page TIFF successfully.\nFile saved at " + dataDir); }
public void PrintProjectPagesToSeparateFiles() { // ExStart:PrintProjectPagesToSeparateFiles // ExFor: SaveOptions.Gridlines // ExFor: SaveOptions.StartDate // ExFor: SaveOptions.EndDate // ExFor: ImageSaveOptions.DefaultFontName // ExFor: ImageSaveOptions.UseProjectDefaultFont // ExSummary: Shows how to save layout to separate files. var project = new Project(DataDir + "CreateProject2.mpp"); var options = new ImageSaveOptions(SaveFileFormat.PNG); options.StartDate = project.Get(Prj.StartDate).AddDays(-3); options.EndDate = project.Get(Prj.FinishDate); options.MarkCriticalTasks = true; options.LegendOnEachPage = false; options.DefaultFontName = "Segoe UI Black"; options.UseProjectDefaultFont = false; options.Gridlines = new List <Gridline>(); var gridline = new Gridline { GridlineType = GridlineType.GanttRow, Color = Color.CornflowerBlue, Pattern = LinePattern.Dashed }; options.Gridlines.Add(gridline); project.Save(OutDir + "PrintProjectPagesToSeparateFiles1_out.png", options); // Save project layout to separate files options.SaveToSeparateFiles = true; project.Save(OutDir + "PrintProjectPagesToSeparateFiles2_out.png", options); // ExEnd:PrintProjectPagesToSeparateFiles }
//ExEnd //ExStart //ExId:ImageColorFilters_tiff_lzw_blackandwhite_sens //ExSummary: Applies LZW compression, saves to black & white TIFF image with specified sensitivity to gray color. private static void SaveBlackWhiteTIFFwithLZW(Document doc, string dataDir, bool highSensitivity) { // Select the TIFF format with 100 dpi. ImageSaveOptions imgOpttiff = new ImageSaveOptions(SaveFormat.Tiff); imgOpttiff.Resolution = 100; // Apply black & white filter. Set very high sensitivity to gray color. imgOpttiff.TiffCompression = TiffCompression.Lzw; imgOpttiff.ImageColorMode = ImageColorMode.BlackAndWhite; // Set brightness and contrast according to sensitivity. if (highSensitivity) { imgOpttiff.ImageBrightness = 0.4f; imgOpttiff.ImageContrast = 0.3f; } else { imgOpttiff.ImageBrightness = 0.9f; imgOpttiff.ImageContrast = 0.9f; } // Save multipage TIFF. doc.Save(string.Format("{0}{1}", dataDir, "result.tiff"), imgOpttiff); }
/// <summary> /// 将Word文档转换为图片的方法(该方法基于第三方DLL),你可以像这样调用该方法: /// ConvertPDF2Image("F:\\PdfFile.doc", "F:\\", "ImageFile", 1, 20, ImageFormat.Png, 256); /// </summary> /// <param name="pdfInputPath">Word文件路径</param> /// <param name="imageOutputPath">图片输出路径,如果为空,默认值为Word所在路径</param> /// <param name="imageName">图片的名字,不需要带扩展名,如果为空,默认值为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 static void ConvertWordToImage(string wordInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, float resolution) { try { // 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; } ImageSaveOptions imageSaveOptions = new ImageSaveOptions(GetSaveFormat(imageFormat)); imageSaveOptions.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) { throw ex; } }
public List <PageInfo> Convert(String inputFile, ImageConversionOptions options) { Diagram diagram = new Diagram(inputFile); if (options.BinarisationAlgorithm == BinarisationAlgorithm.Default) { options.BinarisationAlgorithm = BinarisationAlgorithm.OtsuThreshold; } var pages = new List <PageInfo>(); var saveOptions = new ImageSaveOptions(SaveFileFormat.PNG); saveOptions.Resolution = options.Resolution; saveOptions.PageCount = 1; for (int i = 0; i < diagram.Pages.Count; i++) { saveOptions.PageIndex = i; using (MemoryStream ms = new MemoryStream()) { // Save the page to the memory stream diagram.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); }
public static void Run() { // ExStart:SaveAsMultipageTiff // The path to the documents directory. string dataDir = RunExamples.GetDataDir_RenderingAndPrinting(); // Open the document. Document doc = new Document(dataDir + "TestFile Multipage TIFF.doc"); //ExStart:SaveAsTIFF // Save the document as multipage TIFF. doc.Save(dataDir + "TestFile Multipage TIFF_out_.tiff"); //ExEnd:SaveAsTIFF //ExStart:SaveAsTIFFUsingImageSaveOptions //Create an ImageSaveOptions object to pass to the Save method ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff); options.PageIndex = 0; options.PageCount = 2; options.TiffCompression = TiffCompression.Ccitt4; options.Resolution = 160; dataDir = dataDir + "TestFileWithOptions_out_.tiff"; doc.Save(dataDir, options); //ExEnd:SaveAsTIFFUsingImageSaveOptions // ExEnd:SaveAsMultipageTiff Console.WriteLine("\nDocument saved as multi-page TIFF successfully.\nFile saved at " + dataDir); }
public void SVGtoTIFFWithImageSaveOptionsTest() { // Prepare a path to a source SVG file string documentPath = Path.Combine(DataDir, "gradient.svg"); // Prepare a path for converted file saving string savePath = Path.Combine(OutputDir, "gradient-options.tiff"); // Initialize an SVG document from the file using var document = new SVGDocument(documentPath); // Initialize ImageSaveOptions. Set up the compression, resolutions, and change the background color to AliceBlue var options = new ImageSaveOptions(ImageFormat.Tiff) { Compression = Compression.None, HorizontalResolution = 200, VerticalResolution = 200, BackgroundColor = Color.AliceBlue }; // Convert SVG to TIFF Converter.ConvertSVG(document, options, savePath); Assert.True(File.Exists(savePath)); }
public static void Run() { // ExStart:SaveDocumentToJPEG // The path to the documents directory. string dataDir = RunExamples.GetDataDir_RenderingAndPrinting(); // Open the document Document doc = new Document(dataDir + "Rendering.doc"); // Save as a JPEG image file with default options doc.Save(dataDir + "Rendering.JpegDefaultOptions.jpg"); // Save document to stream as a JPEG with default options MemoryStream docStream = new MemoryStream(); doc.Save(docStream, SaveFormat.Jpeg); // Rewind the stream position back to the beginning, ready for use docStream.Seek(0, SeekOrigin.Begin); // Save document to a JPEG image with specified options. // Render the third page only and set the JPEG quality to 80% // In this case we need to pass the desired SaveFormat to the ImageSaveOptions constructor // to signal what type of image to save as. ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg); imageOptions.PageIndex = 2; imageOptions.PageCount = 1; imageOptions.JpegQuality = 80; doc.Save(dataDir + "Rendering.JpegCustomOptions.jpg", imageOptions); // ExEnd:SaveDocumentToJPEG }
public void ResolutionDefaultValues() { ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg); Assert.AreEqual(96, imageOptions.HorizontalResolution); Assert.AreEqual(96, imageOptions.VerticalResolution); }
/// <summary> /// Sign image and save it to different output type /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Advanced Usage] # SaveSignedImageWithDifferentOutputFileType : Sign image and save it to different output type\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_IMAGE; string fileName = Path.GetFileName(filePath); string outputFilePath = Path.Combine(Constants.OutputPath, "SaveSignedOutputType", "Sample_PngToJpg.jpg"); using (Signature signature = new Signature(filePath)) { // create QRCode option with predefined QRCode text QrCodeSignOptions signOptions = new QrCodeSignOptions("JohnSmith") { // setup QRCode encoding type EncodeType = QrCodeTypes.QR, // set signature position Left = 100, Top = 100 }; ImageSaveOptions saveOptions = new ImageSaveOptions() { FileFormat = ImageSaveFileFormat.Jpg, OverwriteExistingFiles = true }; // sign document to file SignResult result = signature.Sign(outputFilePath, signOptions, saveOptions); Console.WriteLine($"\nSource document signed successfully with {result.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
public void GetOpaqueBoundsInPixels() { Document doc = new Document(MyDir + "Shape.TextBox.doc"); Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg); MemoryStream stream = new MemoryStream(); ShapeRenderer renderer = shape.GetShapeRenderer(); renderer.Save(stream, imageOptions); shape.Remove(); // Check that the opaque bounds and bounds have default values Assert.AreEqual(250, renderer.GetOpaqueBoundsInPixels(imageOptions.Scale, imageOptions.VerticalResolution).Width); Assert.AreEqual(52, renderer.GetOpaqueBoundsInPixels(imageOptions.Scale, imageOptions.HorizontalResolution).Height); Assert.AreEqual(250, renderer.GetBoundsInPixels(imageOptions.Scale, imageOptions.VerticalResolution).Width); Assert.AreEqual(52, renderer.GetBoundsInPixels(imageOptions.Scale, imageOptions.HorizontalResolution).Height); Assert.AreEqual(250, renderer.GetOpaqueBoundsInPixels(imageOptions.Scale, imageOptions.HorizontalResolution).Width); Assert.AreEqual(52, renderer.GetOpaqueBoundsInPixels(imageOptions.Scale, imageOptions.HorizontalResolution).Height); Assert.AreEqual(250, renderer.GetBoundsInPixels(imageOptions.Scale, imageOptions.VerticalResolution).Width); Assert.AreEqual(52, renderer.GetBoundsInPixels(imageOptions.Scale, imageOptions.VerticalResolution).Height); Assert.AreEqual((float)187.850006, renderer.OpaqueBoundsInPoints.Width); Assert.AreEqual((float)39.25, renderer.OpaqueBoundsInPoints.Height); }
public void Renderer(bool useGdiEmfRenderer) { //ExStart //ExFor:ImageSaveOptions.UseGdiEmfRenderer //ExSummary:Shows how to choose a renderer when converting a document to .emf. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.ParagraphFormat.Style = doc.Styles["Heading 1"]; builder.Writeln("Hello world!"); builder.InsertImage(ImageDir + "Logo.jpg"); // When we save the document as an EMF image, we can pass a SaveOptions object to select a renderer for the image. // If we set the "UseGdiEmfRenderer" flag to "true", Aspose.Words will use the GDI+ renderer. // If we set the "UseGdiEmfRenderer" flag to "false", Aspose.Words will use its own metafile renderer. ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Emf); saveOptions.UseGdiEmfRenderer = useGdiEmfRenderer; doc.Save(ArtifactsDir + "ImageSaveOptions.Renderer.emf", saveOptions); // The GDI+ renderer usually creates larger files. if (useGdiEmfRenderer) #if NET48 || JAVA { Assert.That(300000, Is.LessThan(new FileInfo(ArtifactsDir + "ImageSaveOptions.Renderer.emf").Length)); } #elif NET5_0 { Assert.That(30000, Is.AtLeast(new FileInfo(ArtifactsDir + "ImageSaveOptions.Renderer.emf").Length)); }
public void MHTMLtoJPGWithImageSaveOptionsTest() { // Open an existing MHTML file for reading using var stream = File.OpenRead(DataDir + "sample.mht"); // Prepare a path to save the converted file string savePath = Path.Combine(OutputDir, "sample-options.jpg"); // Initailize the ImageSaveOptions with a custom page-size and a background color var options = new ImageSaveOptions(ImageFormat.Jpeg) { PageSetup = { AnyPage = new Page() { Size = new Aspose.Html.Drawing.Size(Length.FromPixels(1000), Length.FromPixels(500)) } }, BackgroundColor = Color.Beige }; // Call the ConvertMHTML method to convert MHTML to JPG Converter.ConvertMHTML(stream, options, savePath); Assert.True(File.Exists(Path.Combine(OutputDir, "sample-options_1.jpg"))); }
public void OnePage() { //ExStart //ExFor:Document.Save(String, SaveOptions) //ExFor:FixedPageSaveOptions //ExFor:ImageSaveOptions.PageSet //ExSummary:Shows how to render one page from a document to a JPEG image. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Page 1."); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Page 2."); builder.InsertImage(ImageDir + "Logo.jpg"); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Page 3."); // Create an "ImageSaveOptions" object which we can pass to the document's "Save" method // to modify the way in which that method renders the document into an image. ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Jpeg); // Set the "PageSet" to "1" to select the second page via // the zero-based index to start rendering the document from. options.PageSet = new PageSet(1); // When we save the document to the JPEG format, Aspose.Words only renders one page. // This image will contain one page starting from page two, // which will just be the second page of the original document. doc.Save(ArtifactsDir + "ImageSaveOptions.OnePage.jpg", options); //ExEnd TestUtil.VerifyImage(816, 1056, ArtifactsDir + "ImageSaveOptions.OnePage.jpg"); }
public void SaveAsImage() { //ExStart //ExFor:ImageSaveOptions.#ctor //ExFor:Document.Save(String) //ExFor:Document.Save(Stream, SaveFormat) //ExFor:Document.Save(String, SaveOptions) //ExId:SaveToImage_NewAPI //ExSummary:Shows how to save a document to the Jpeg format using the Save method and the ImageSaveOptions class. // Open the document Document doc = new Document(MyDir + "Rendering.doc"); // Save as a Jpeg image file with default options doc.Save(MyDir + @"\Artifacts\Rendering.JpegDefaultOptions.jpg"); // Save document to stream as a Jpeg with default options MemoryStream docStream = new MemoryStream(); doc.Save(docStream, SaveFormat.Jpeg); // Rewind the stream position back to the beginning, ready for use docStream.Seek(0, SeekOrigin.Begin); // Save document to a Jpeg image with specified options. // Render the third page only and set the jpeg quality to 80% // In this case we need to pass the desired SaveFormat to the ImageSaveOptions constructor // to signal what type of image to save as. ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg); imageOptions.PageIndex = 2; imageOptions.PageCount = 1; imageOptions.JpegQuality = 80; doc.Save(MyDir + @"\Artifacts\Rendering.JpegCustomOptions.jpg", imageOptions); //ExEnd }
private static void SaveBlackWhiteTIFFwithCITT4(Document doc, string dataDir, bool highSensitivity) { // Select the TIFF format with 100 dpi. ImageSaveOptions imgOpttiff = new ImageSaveOptions(SaveFormat.Tiff); imgOpttiff.Resolution = 100; // Set CCITT4 compression. imgOpttiff.TiffCompression = TiffCompression.Ccitt4; // Apply grayscale filter. imgOpttiff.ImageColorMode = ImageColorMode.Grayscale; // Set brightness and contrast according to sensitivity. if (highSensitivity) { imgOpttiff.ImageBrightness = 0.4f; imgOpttiff.ImageContrast = 0.3f; } else { imgOpttiff.ImageBrightness = 0.9f; imgOpttiff.ImageContrast = 0.9f; } // Save multipage TIFF. doc.Save(string.Format("{0}{1}", dataDir, "result Ccitt4.tiff"), imgOpttiff); Console.WriteLine("\nDocument converted to TIFF successfully with black and white and Ccitt4 compression.\nFile saved at " + dataDir + "Result Ccitt4.tiff"); }
/// <summary> /// Word转为图片 /// </summary> /// <param name="source">word文件路径</param> /// <param name="target">图片保存的文件夹路径</param> /// <param name="resolution">分辨率</param> /// <param name="format">图片格式</param> public static bool ConverToImage(string source, string target, int resolution = 300, AsposeConvertDelegate d = null) { double percent = 0.0; int page = 0; int total = 0; double second = 0; string path = ""; string message = ""; DateTime startTime = DateTime.Now; if (!FileUtil.CreateDirectory(target)) { throw new DirectoryNotFoundException(); } if (!File.Exists(source)) { throw new FileNotFoundException(); } if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.1; message = "正在解析文件!"; d.Invoke(percent, page, total, second, path, message); } Diagram diagram = new Diagram(source); total = diagram.Pages.Count; if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.2; message = "开始转换文件,共" + total + "页!"; d.Invoke(percent, page, total, second, path, message); } logger.Info("ConverToImage - source=" + source + ", target=" + target + ", resolution=" + resolution + ", pageCount=" + total); ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.PNG); options.Resolution = resolution; for (page = 0; page < total; page++) { options.PageIndex = page; using (MemoryStream stream = new MemoryStream()) { diagram.Save(stream, options); Bitmap bitmap = new Bitmap(stream); path = target + "\\" + (page + 1) + "_.png"; bitmap.Save(path, ImageFormat.Png); } if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.2 + (page + 1) * 0.8 / total; message = "正在转换第" + (page + 1) + "/" + total + "页!"; d.Invoke(percent, (page + 1), total, second, path, message); } } return true; }
/// <summary> /// Word转为图片 /// </summary> /// <param name="source">word文件路径</param> /// <param name="target">图片保存的文件夹路径</param> /// <param name="resolution">分辨率</param> /// <param name="format">图片格式</param> public static bool ConverToImage(string source, string target, int resolution = 300, AsposeConvertDelegate d=null) { double percent = 0.0; int page = 0; int total = 0; double second = 0; string path = ""; string message = ""; DateTime startTime = DateTime.Now; if (!FileUtil.CreateDirectory(target)) { throw new DirectoryNotFoundException(); } if (!File.Exists(source)) { throw new FileNotFoundException(); } if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.1; message = "正在解析文件!"; d.Invoke(percent, page, total, second, path, message); } LoadOptions loadOptions = new LoadOptions(); loadOptions.LoadFormat = LoadFormat.Auto; Document doc = new Document(source, loadOptions); total = doc.PageCount; if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.2; message = "开始转换文件,共" + total + "页!"; d.Invoke(percent, page, total, second, path, message); } logger.Info("ConverToImage - source=" + source + ", target=" + target + ", resolution=" + resolution + ", pageCount=" + total); for (page = 0; page < total; page++) { ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png); options.PrettyFormat = false; options.Resolution = resolution; options.PageIndex = page; options.PageCount = 1; path = target + "\\" + (page + 1) + ".png"; doc.Save(path, options); if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.2 + (page + 1) * 0.8 / total; message = "正在转换第" + (page + 1) + "/" + total + "页!"; d.Invoke(percent, (page + 1), total, second, path, message); } } return true; }
public void UseGdiEmfRenderer() { //ExStart //ExFor:ImageSaveOptions.UseGdiEmfRenderer //ExSummary:Shows how to save metafiles directly without using GDI+ to EMF. Document doc = new Document(MyDir + "SaveOptions.MyraidPro.docx"); ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.Emf); saveOptions.UseGdiEmfRenderer = false; //ExEnd }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName); // ExStart:RenderProjectDataToFormat24bppRgb Project project = new Project(dataDir + "TestProject1.mpp"); ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.TIFF); options.HorizontalResolution = 72; options.VerticalResolution = 72; options.PixelFormat = PixelFormat.Format24bppRgb; project.Save(dataDir + "RenderProjectDataToFormat24bppRgb_out.tif", options); // ExEnd:RenderProjectDataToFormat24bppRgb }
/// <summary> /// OneNote转为图片 - 未开发完 /// </summary> /// <param name="source">源文件路径</param> /// <param name="target">图片保存的文件夹路径</param> /// <param name="dpi">dpi</param> /// <param name="format">图片格式</param> public static bool ConverToImage(string source, string target, float scale, AsposeConvertDelegate d = null) { double percent = 0.0; int page = 0; int total = 0; double second = 0; string path = ""; string message = ""; DateTime startTime = DateTime.Now; if (!FileUtil.CreateDirectory(target)) { throw new DirectoryNotFoundException(); } if (!File.Exists(source)) { throw new FileNotFoundException(); } if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.1; message = "正在解析文件!"; d.Invoke(percent, page, total, second, path, message); } Document doc = new Document(source); if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.2; message = "开始转换文件,共" + total + "页!"; d.Invoke(percent, (page + 1), total, second, path, message); } logger.Info("ConverToImage - source=" + source + ", target=" + target + ", scale=" + scale + ", pageCount=" + total); ImageSaveOptions opts = new ImageSaveOptions(SaveFormat.Png); opts.PageIndex = 1; doc.Save(target + "\\" + (page + 1) + "_.png", opts); //for (page = 0; page < total; page++) //{ // if (d != null) // { // second = (DateTime.Now - startTime).TotalSeconds; // percent = 0.2 + page * 0.8 / total; // message = "正在转换第" + (page + 1) + "/" + total + "页!"; // d.Invoke(percent, page, total, second, message); // } //} return true; }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Diagrams(); Diagram diagram = new Diagram(dataDir + "ExportPageToImage.vsd"); //Save diagram as PNG ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.PNG); // Save one page only, by page index options.PageIndex = 0; //Save resultant Image file diagram.Save(dataDir + "output.png", options); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); Diagram diagram = new Diagram(dataDir + "Drawing1.vsd"); //Save diagram as PNG ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.PNG); // Save one page only, by page index options.PageIndex = 0; //Save resultant Image file diagram.Save(dataDir + "output.png", options); }
public static void RenderShapeToDisk(string dataDir, Shape shape) { ShapeRenderer r = shape.GetShapeRenderer(); // Define custom options which control how the image is rendered. Render the shape to the JPEG raster format. ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Emf) { Scale = 1.5f }; dataDir = dataDir + "TestFile.RenderToDisk_out_.emf"; // Save the rendered image to disk. r.Save(dataDir, imageOptions); Console.WriteLine("\nShape rendered to disk successfully.\nFile saved at " + dataDir); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Note.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Load the document into Aspose.Note. Document oneFile = new Document(dataDir + "Aspose.one"); // Initialize ImageSaveOptions object ImageSaveOptions opts = new ImageSaveOptions(SaveFormat.Png); // set page index opts.PageIndex = 1; // Save the document as PNG. oneFile.Save(dataDir + "output.png", opts); }
private static void SaveColorTIFFwithLZW(Document doc, string dataDir, float brightness, float contrast) { // Select the TIFF format with 100 dpi. ImageSaveOptions imgOpttiff = new ImageSaveOptions(SaveFormat.Tiff); imgOpttiff.Resolution = 100; // Select fullcolor LZW compression. imgOpttiff.TiffCompression = TiffCompression.Lzw; // Set brightness and contrast. imgOpttiff.ImageBrightness = brightness; imgOpttiff.ImageContrast = contrast; // Save multipage color TIFF. doc.Save(string.Format("{0}{1}", dataDir, "Result Colors.tiff"), imgOpttiff); Console.WriteLine("\nDocument converted to TIFF successfully with Colors.\nFile saved at " + dataDir + "Result Colors.tiff"); }
static void Main(string[] args) { // Sample infrastructure. string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar; string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath; // Open the document. Document doc = new Document(dataDir + "SaveAsPNG.doc"); //Create an ImageSaveOptions object to pass to the Save method ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png); options.Resolution = 160; // Save each page of the document as Png. for (int i = 0; i < doc.PageCount; i++) { options.PageIndex = i; doc.Save(string.Format(dataDir + i + "SaveAsPNG out.Png", i), options); } }
public static void RenderShapeToStream(string dataDir, Shape shape) { ShapeRenderer r = new ShapeRenderer(shape); // Define custom options which control how the image is rendered. Render the shape to the vector format EMF. ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg) { // Output the image in gray scale ImageColorMode = ImageColorMode.Grayscale, // Reduce the brightness a bit (default is 0.5f). ImageBrightness = 0.45f }; dataDir = dataDir + "TestFile.RenderToStream_out_.jpg"; FileStream stream = new FileStream(dataDir, FileMode.Create); // Save the rendered image to the stream using different options. r.Save(stream, imageOptions); Console.WriteLine("\nShape rendered to stream successfully.\nFile saved at " + dataDir); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName); // ExStart:RenderMultipageTIFF // Source file to be converted to TIFF string file = "Project2.mpp"; Project project = new Project(dataDir + file); // Save the project to TIFF project.Save(dataDir + "RenderMultipageTIFF_out.tif", SaveFileFormat.TIFF); // Save the project with CCITT4 compression ImageSaveOptions options = new ImageSaveOptions(SaveFileFormat.TIFF); options.TiffCompression = TiffCompression.Ccitt4; project.Save(dataDir + "RenderMultipageTIFF_options_out.tif", options); // Remove the compression options.TiffCompression = TiffCompression.None; project.Save(dataDir + "RenderMultipageTIFF_comp_none_out.tif", options); // ExEnd:RenderMultipageTIFF }
public static void RenderShapeToDisk(string dataDir, Shape shape) { //ExStart //ExFor:ShapeRenderer //ExFor:ShapeBase.GetShapeRenderer //ExFor:ImageSaveOptions //ExFor:ImageSaveOptions.Scale //ExFor:ShapeRenderer.Save(String, ImageSaveOptions) //ExId:RenderShapeToDisk //ExSummary:Shows how to render a shape independent of the document to an EMF image and save it to disk. // The shape render is retrieved using this method. This is made into a separate object from the shape as it internally // caches the rendered shape. ShapeRenderer r = shape.GetShapeRenderer(); // Define custom options which control how the image is rendered. Render the shape to the JPEG raster format. ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Emf) { Scale = 1.5f }; // Save the rendered image to disk. r.Save(dataDir + "TestFile.RenderToDisk Out.emf", imageOptions); //ExEnd }
public static void RenderShapeToStream(string dataDir, Shape shape) { //ExStart //ExFor:ShapeRenderer //ExFor:ShapeRenderer.#ctor(ShapeBase) //ExFor:ImageSaveOptions.ImageColorMode //ExFor:ImageSaveOptions.ImageBrightness //ExFor:ShapeRenderer.Save(Stream, ImageSaveOptions) //ExId:RenderShapeToStream //ExSummary:Shows how to render a shape independent of the document to a JPEG image and save it to a stream. // We can also retrieve the renderer for a shape by using the ShapeRenderer constructor. ShapeRenderer r = new ShapeRenderer(shape); // Define custom options which control how the image is rendered. Render the shape to the vector format EMF. ImageSaveOptions imageOptions = new ImageSaveOptions(SaveFormat.Jpeg) { // Output the image in gray scale ImageColorMode = ImageColorMode.Grayscale, // Reduce the brightness a bit (default is 0.5f). ImageBrightness = 0.45f }; FileStream stream = new FileStream(dataDir + "TestFile.RenderToStream Out.jpg", FileMode.CreateNew); // Save the rendered image to the stream using different options. r.Save(stream, imageOptions); //ExEnd }
//ExStart //ExId:RenderNode //ExSummary:Shows how to render a node independent of the document by building on the functionality provided by ShapeRenderer class. /// <summary> /// Renders any node in a document to the path specified using the image save options. /// </summary> /// <param name="node">The node to render.</param> /// <param name="path">The path to save the rendered image to.</param> /// <param name="imageOptions">The image options to use during rendering. This can be null.</param> public static void RenderNode(Node node, string filePath, ImageSaveOptions imageOptions) { // Run some argument checks. if (node == null) throw new ArgumentException("Node cannot be null"); // If no image options are supplied, create default options. if (imageOptions == null) imageOptions = new ImageSaveOptions(FileFormatUtil.ExtensionToSaveFormat(Path.GetExtension(filePath))); // Store the paper color to be used on the final image and change to transparent. // This will cause any content around the rendered node to be removed later on. Color savePaperColor = imageOptions.PaperColor; imageOptions.PaperColor = Color.Transparent; // There a bug which affects the cache of a cloned node. To avoid this we instead clone the entire document including all nodes, // find the matching node in the cloned document and render that instead. Document doc = (Document)node.Document.Clone(true); node = doc.GetChild(NodeType.Any, node.Document.GetChildNodes(NodeType.Any, true).IndexOf(node), true); // Create a temporary shape to store the target node in. This shape will be rendered to retrieve // the rendered content of the node. Shape shape = new Shape(doc, ShapeType.TextBox); Section parentSection = (Section)node.GetAncestor(NodeType.Section); // Assume that the node cannot be larger than the page in size. shape.Width = parentSection.PageSetup.PageWidth; shape.Height = parentSection.PageSetup.PageHeight; shape.FillColor = Color.Transparent; // We must make the shape and paper color transparent. // Don't draw a surronding line on the shape. shape.Stroked = false; // Move up through the DOM until we find node which is suitable to insert into a Shape (a node with a parent can contain paragraph, tables the same as a shape). // Each parent node is cloned on the way up so even a descendant node passed to this method can be rendered. // Since we are working with the actual nodes of the document we need to clone the target node into the temporary shape. Node currentNode = node; while (!(currentNode.ParentNode is InlineStory || currentNode.ParentNode is Story || currentNode.ParentNode is ShapeBase)) { CompositeNode parent = (CompositeNode)currentNode.ParentNode.Clone(false); currentNode = currentNode.ParentNode; parent.AppendChild(node.Clone(true)); node = parent; // Store this new node to be inserted into the shape. } // We must add the shape to the document tree to have it rendered. shape.AppendChild(node.Clone(true)); parentSection.Body.FirstParagraph.AppendChild(shape); // Render the shape to stream so we can take advantage of the effects of the ImageSaveOptions class. // Retrieve the rendered image and remove the shape from the document. MemoryStream stream = new MemoryStream(); shape.GetShapeRenderer().Save(stream, imageOptions); shape.Remove(); // Load the image into a new bitmap. using (Bitmap renderedImage = new Bitmap(stream)) { // Extract the actual content of the image by cropping transparent space around // the rendered shape. Rectangle cropRectangle = FindBoundingBoxAroundNode(renderedImage); Bitmap croppedImage = new Bitmap(cropRectangle.Width, cropRectangle.Height); croppedImage.SetResolution(imageOptions.Resolution, imageOptions.Resolution); // Create the final image with the proper background color. using (Graphics g = Graphics.FromImage(croppedImage)) { g.Clear(savePaperColor); g.DrawImage(renderedImage, new Rectangle(0, 0, croppedImage.Width, croppedImage.Height), cropRectangle.X, cropRectangle.Y, cropRectangle.Width, cropRectangle.Height, GraphicsUnit.Pixel); croppedImage.Save(filePath); } } }
//ExEnd //ExStart //ExFor:ImageColorMode //ExId:ImageColorFilters_tiff_lzw_grayscale //ExSummary: Applies LZW compression, saves to grayscale TIFF image with specified brightness and contrast. private static void SaveGrayscaleTIFFwithLZW(Document doc, string dataDir, float brightness, float contrast) { // Select the TIFF format with 100 dpi. ImageSaveOptions imgOpttiff = new ImageSaveOptions(SaveFormat.Tiff); imgOpttiff.Resolution = 100; // Select LZW compression. imgOpttiff.TiffCompression = TiffCompression.Lzw; // Apply grayscale filter. imgOpttiff.ImageColorMode = ImageColorMode.Grayscale; // Set brightness and contrast. imgOpttiff.ImageBrightness = brightness; imgOpttiff.ImageContrast = contrast; // Save multipage grayscale TIFF. doc.Save(string.Format("{0}{1}", dataDir, "result.tiff"), imgOpttiff); }
//ExEnd //ExStart //ExId:ImageColorFilters_tiff_rle_graysvale_sens //ExSummary: Applies RLE compression with specified sensitivity to gray color, saves to black & white TIFF image. private static void SaveBlackWhiteTIFFwithRLE(Document doc, string dataDir, bool highSensitivity) { // Select the TIFF format with 100 dpi. ImageSaveOptions imgOpttiff = new ImageSaveOptions(SaveFormat.Tiff); imgOpttiff.Resolution = 100; // Set RLE compression. imgOpttiff.TiffCompression = TiffCompression.Rle; // Aply grayscale filter. imgOpttiff.ImageColorMode = ImageColorMode.Grayscale; // Set brightness and contrast according to sensitivity. if (highSensitivity) { imgOpttiff.ImageBrightness = 0.4f; imgOpttiff.ImageContrast = 0.3f; } else { imgOpttiff.ImageBrightness = 0.9f; imgOpttiff.ImageContrast = 0.9f; } // Save multipage TIFF grayscale with low bright and contrast doc.Save(string.Format("{0}{1}", dataDir, "result.tiff"), imgOpttiff); }
public static ArrayList GetDocumentData(string filePath, string sessionID) { Common.SetLicense(); ArrayList result = new ArrayList(); try { // Create a temporary folder string documentFolder = CreateTempFolders(filePath, sessionID); // Load the document in Aspose.Words Document doc = new Document(filePath); // Convert the document to images ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Jpeg); options.PageCount = 1; // Save each page of the document as image. for (int i = 0; i < doc.PageCount; i++) { options.PageIndex = i; doc.Save(string.Format(@"{0}\{1}.png", documentFolder, i), options); } result.Add(Common.Success); // 0. Result result.Add(doc.PageCount.ToString()); // 1. Page count result.Add(MapPathReverse(documentFolder)); // 2. Images Folder path } catch (Exception ex) { result.Clear(); result.Add(Common.Error + ": " + ex.Message); // 0. Result } return result; }