private void button2_Click(object sender, EventArgs e) { string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar; string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath; Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(dataDir + "//InputFile.pdf"); for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++) { using (FileStream imageStream = new FileStream("image" + pageCount + ".png", FileMode.Create)) { Resolution resolution = new Resolution(300); PngDevice pngDevice = new PngDevice(resolution); pngDevice.Process(pdfDocument.Pages[pageCount], imageStream); imageStream.Close(); MessageBox.Show("png file created in \\bin\\Debug"); } } }
public static void Run() { // ExStart:ConvertAllPagesToPNG // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Images(); // Open document Document pdfDocument = new Document(dataDir + "ConvertAllPagesToPNG.pdf"); for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++) { using (FileStream imageStream = new FileStream(dataDir + "image" + pageCount + "_out" + ".png", FileMode.Create)) { // Create PNG device with specified attributes // Width, Height, Resolution, Quality // Quality [0-100], 100 is Maximum // Create Resolution object Resolution resolution = new Resolution(300); PngDevice pngDevice = new PngDevice(resolution); // Convert a particular page and save the image to stream pngDevice.Process(pdfDocument.Pages[pageCount], imageStream); // Close stream imageStream.Close(); } } // ExEnd:ConvertAllPagesToPNG System.Console.WriteLine("PDF pages are converted to PNG successfully!"); }
public static void Run() { // ExStart:ConvertPageRegionToDOM // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Images(); // Open document Document document = new Document( dataDir + "AddImage.pdf"); // Get rectangle of particular page region Aspose.Pdf.Rectangle pageRect = new Aspose.Pdf.Rectangle(20, 671, 693, 1125); // Set CropBox value as per rectangle of desired page region document.Pages[1].CropBox = pageRect; // Save cropped document into stream MemoryStream ms = new MemoryStream(); document.Save(ms); // Open cropped PDF document and convert to image document = new Document(ms); // Create Resolution object Resolution resolution = new Resolution(300); // Create PNG device with specified attributes PngDevice pngDevice = new PngDevice(resolution); dataDir = dataDir + "ConvertPageRegionToDOM_out.png"; // Convert a particular page and save the image to stream pngDevice.Process(document.Pages[1], dataDir); ms.Close(); // ExEnd:ConvertPageRegionToDOM Console.WriteLine("\nPage region converted to DOM successfully.\nFile saved at " + dataDir); }
public static void Run() { // ExStart:ConvertPageRegionToDOM // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Images(); // Open document Document document = new Document(dataDir + "AddImage.pdf"); // Get rectangle of particular page region Aspose.Pdf.Rectangle pageRect = new Aspose.Pdf.Rectangle(20, 671, 693, 1125); // Set CropBox value as per rectangle of desired page region document.Pages[1].CropBox = pageRect; // Save cropped document into stream MemoryStream ms = new MemoryStream(); document.Save(ms); // Open cropped PDF document and convert to image document = new Document(ms); // Create Resolution object Resolution resolution = new Resolution(300); // Create PNG device with specified attributes PngDevice pngDevice = new PngDevice(resolution); dataDir = dataDir + "ConvertPageRegionToDOM_out_.png"; // Convert a particular page and save the image to stream pngDevice.Process(document.Pages[1], dataDir); ms.Close(); // ExEnd:ConvertPageRegionToDOM Console.WriteLine("\nPage region converted to DOM successfully.\nFile saved at " + dataDir); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Open document Document pdfDocument = new Document(dataDir + "input.pdf"); for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++) { using (FileStream imageStream = new FileStream(dataDir + "image" + pageCount + ".png", FileMode.Create)) { //create PNG device with specified attributes //Width, Height, Resolution, Quality //Quality [0-100], 100 is Maximum //Create Resolution object Resolution resolution = new Resolution(300); PngDevice pngDevice = new PngDevice(resolution); //Convert a particular page and save the image to stream pngDevice.Process(pdfDocument.Pages[pageCount], imageStream); //Close stream imageStream.Close(); } } }
public static void Run() { // ExStart:PageToPNG // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Images(); // Open document Document pdfDocument = new Document(dataDir + "PageToPNG.pdf"); using (FileStream imageStream = new FileStream(dataDir + "aspose-logo.png", FileMode.Create)) { // Create Resolution object Resolution resolution = new Resolution(300); // Create PNG device with specified attributes (Width, Height, Resolution) PngDevice pngDevice = new PngDevice(resolution); // Convert a particular page and save the image to stream pngDevice.Process(pdfDocument.Pages[1], imageStream); // Close stream imageStream.Close(); } // ExEnd:PageToPNG }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Open document Document pdfDocument = new Document(dataDir+ "input.pdf"); for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++) { using (FileStream imageStream = new FileStream(dataDir + "image" + pageCount + ".png", FileMode.Create)) { //create PNG device with specified attributes //Width, Height, Resolution, Quality //Quality [0-100], 100 is Maximum //Create Resolution object Resolution resolution = new Resolution(300); PngDevice pngDevice = new PngDevice(resolution); //Convert a particular page and save the image to stream pngDevice.Process(pdfDocument.Pages[pageCount], imageStream); //Close stream imageStream.Close(); } } }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Images(); //open document Document pdfDocument = new Document(dataDir + "PageToPNG.pdf"); using (FileStream imageStream = new FileStream(dataDir + "aspose-logo.png", FileMode.Create)) { //create Resolution object Resolution resolution = new Resolution(300); //create PNG device with specified attributes (Width, Height, Resolution) PngDevice pngDevice = new PngDevice(resolution); //convert a particular page and save the image to stream pngDevice.Process(pdfDocument.Pages[1], imageStream); //close stream imageStream.Close(); } }
private OutputDevice GetCorrectOutputDevice(Job job) { OutputDevice device; switch (job.Profile.OutputFormat) { case OutputFormat.PdfA1B: case OutputFormat.PdfA2B: case OutputFormat.PdfA3B: case OutputFormat.PdfX: case OutputFormat.Pdf: device = new PdfDevice(job); break; case OutputFormat.Png: device = new PngDevice(job); break; case OutputFormat.Jpeg: device = new JpegDevice(job); break; case OutputFormat.Tif: device = new TiffDevice(job); break; case OutputFormat.Txt: device = new TextDevice(job); break; default: throw new Exception("Illegal OutputFormat specified"); } return(device); }
///<Summary> /// ConvertPdfToPng method to convert PDF to PNG ///</Summary> public Response ConvertPdfToPng(string fileName, string folderName) { return(ProcessTask(fileName, folderName, ".png", true, "", true, delegate(string inFilePath, string outPath, string zipOutFolder) { Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(inFilePath); string outfileName = Path.GetFileNameWithoutExtension(fileName) + "_{0}"; int totalPages = pdfDocument.Pages.Count; for (int pageCount = 1; pageCount <= totalPages; pageCount++) { if (totalPages > 1) { outPath = zipOutFolder + "/" + outfileName; outPath = string.Format(outPath, pageCount); } else { outPath = zipOutFolder + "/" + Path.GetFileNameWithoutExtension(fileName); } Resolution resolution = new Resolution(300); PngDevice pngDevice = new PngDevice(resolution); pngDevice.Process(pdfDocument.Pages[pageCount], outPath + ".png"); } })); }
public void Init(string file, int clientWidth) { Logger.Info("**** Начинается обработка файла {0} ****", file); string directory = Path.GetDirectoryName(file); var newFile = Path.Combine(directory, string.Concat(Path.GetFileNameWithoutExtension(file), ".png")); Logger.Info("Будет создан файл {0}", newFile); try { //исходную пдфку перегоняем в картинку и потом уже картинку масштабируем Document pdfDocument = new Document(file); using (FileStream imageStream = new FileStream(newFile, FileMode.OpenOrCreate)) { Resolution resolution = new Resolution(100); PngDevice pngDevice = new PngDevice(resolution); pngDevice.Process(pdfDocument.Pages[1], imageStream); imageStream.Close(); } _imageProcessor.Init(newFile, clientWidth); } catch (Exception e) { Logger.Error(e); } Logger.Info("**** Обработка файла {0} завершена****", file); }
/// <summary> /// Excel转为图片 /// </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, 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); } Document document = new Document(source); total = document.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); for (page = 0; page < total; page++) { path = target + "\\" + (page + 1) + ".png"; using (FileStream imageStream = new FileStream(path, FileMode.Create)) { PngDevice pngDevice = new PngDevice(new Resolution(resolution)); pngDevice.Process(document.Pages[page + 1], imageStream); imageStream.Close(); } 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); }
private void InitDevice() { //Width, Height, Resolution, Quality //Quality [0-100], 100 is Maximum //create Resolution object Resolution resolution = new Resolution(170); //JpegDevice jpegDevice = new JpegDevice(500, 700, resolution,100); _device = new PngDevice(resolution); }
public static string AppendConverter(string appPages, string appRatios, string appHeights) { Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); int totalCount = doc.Pages.Count; //open second document Document pdfDocument2 = new Document(HttpContext.Current.Server.MapPath("Convert/append.pdf")); //add pages of second document to the first doc.Pages.Add(pdfDocument2.Pages); //save concatenated output file doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf")); string Aratio = ""; string pages = ""; string height = ""; string Allheights = ""; for (int pageCount = 1; pageCount <= doc.Pages.Count; pageCount++) { if (pageCount > totalCount) { using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png"), FileMode.Create)) { //Create Resolution object //Resolution resolution = new Resolution(300); //create PNG device with specified attributes PngDevice pngDevice = new PngDevice(); //Convert a particular page and save the image to stream pngDevice.Process(doc.Pages[pageCount], imageStream); //Close stream imageStream.Close(); System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png")); ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath("Input/image" + pageCount + ".png"), out height, out Aratio); image.Dispose(); appPages = appPages + "," + "image" + pageCount + ".png"; appRatios = appRatios + "," + Aratio; appHeights = appHeights + "," + height; } } } return(appPages + "%#" + appRatios + "%#" + appHeights); }
public void ToJpeg(string absoluteFilePath, string outputPath) { using (var pdfDocument = new Document(absoluteFilePath)) { for (var i = 1; i < pdfDocument.Pages.Count + 1; i++) { //convert a particular page and save the image to stream var page = pdfDocument.Pages[i]; var ph = page.PageInfo.Height - page.Rect.Height; var pw = page.PageInfo.Width - page.Rect.Width; var pngDevice = new PngDevice((int)page.Rect.Width, (int)page.Rect.Height); pngDevice.Process(page, Path.Combine(outputPath, i.ToString() + ".PNG")); lblInfo.Content = $"{i}/{pdfDocument.Pages.Count}"; } } }
public override async Task GeneratePreviewAsync(Stream docStream, IPreviewGenerationContext context, CancellationToken cancellationToken) { var document = new Document(docStream); if (context.StartIndex == 0) { await context.SetPageCountAsync(document.Pages.Count, cancellationToken).ConfigureAwait(false); } var loggedPageError = false; context.SetIndexes(document.Pages.Count, out var firstIndex, out var lastIndex); for (var i = firstIndex; i <= lastIndex; i++) { cancellationToken.ThrowIfCancellationRequested(); using (var imgStream = new MemoryStream()) { try { var pngDevice = new PngDevice(new Resolution(context.PreviewResolution, context.PreviewResolution)); pngDevice.Process(document.Pages[i + 1], imgStream); if (imgStream.Length == 0) { continue; } await context.SavePreviewAndThumbnailAsync(imgStream, i + 1, cancellationToken) .ConfigureAwait(false); } catch (Exception ex) { if (await Tools.HandlePageErrorAsync(ex, i + 1, context, !loggedPageError, cancellationToken).ConfigureAwait(false)) { return; } loggedPageError = true; } } } }
private static string ImageConverter(string fullName) { Document doc = new Document(fullName); string Aratio = ""; string pages = ""; string Ratios = ""; string height = ""; string Allheights = ""; string fields = ""; int TotalPages = doc.Pages.Count; var fullPath = System.IO.Path.GetDirectoryName(fullName); for (int pageCount = 1; pageCount <= TotalPages; pageCount++) { using (FileStream imageStream = new FileStream(fullPath + "\\image" + pageCount + ".png", FileMode.Create)) { PngDevice pngDevice = new PngDevice(new Resolution(150)); pngDevice.Process(doc.Pages[pageCount], imageStream); imageStream.Close(); //System.Drawing.Image image = System.Drawing.Image.FromFile(fullPath + "\\image" + pageCount + ".png"); ScaleImage(fullPath + "\\image" + pageCount + ".png", 1138, 760, out height, out Aratio); //image.Dispose(); if (pageCount == 1) { fields = CheckFields(doc, pageCount, "image" + pageCount + ".png", fields, Convert.ToDouble(Aratio)); } pages = pages + "," + "image" + pageCount + ".png"; Ratios = Ratios + "," + Aratio; Allheights = Allheights + "," + height; } } Ratios = Ratios.Substring(1, Ratios.Length - 1); pages = pages.Substring(1, pages.Length - 1); Allheights = Allheights.Substring(1, Allheights.Length - 1); if (fields != "") { fields = fields.Substring(3, fields.Length - 3); } return(pages + "%#" + Ratios + "%#" + Allheights + "%#" + fields); }
public IHttpActionResult AddPage(string folder) { var fullPath = string.Format("{0}Editor\\{1}", Config.Configuration.WorkingDirectory.Replace("/", "\\"), folder); var pdfDocumentPath = string.Format("{0}\\document.pdf", fullPath); try { Document doc = new Document(pdfDocumentPath); doc.Pages.Add(); doc.Save(pdfDocumentPath); string height = ""; string Aratio = ""; //int counter = GetHighestPage(); using (FileStream imageStream = new FileStream(fullPath + "\\image" + doc.Pages.Count + ".png", FileMode.Create)) { //create PNG device with specified attributes PngDevice pngDevice = new PngDevice(new Resolution(150)); //Convert a particular page and save the image to stream pngDevice.Process(doc.Pages[doc.Pages.Count], imageStream); //Close stream imageStream.Close(); //System.Drawing.Image image = System.Drawing.Image.FromFile(fullPath + "\\image" + doc.Pages.Count + ".png"); ScaleImage(fullPath + "\\image" + doc.Pages.Count + ".png", 1138, 760, out height, out Aratio); //image.Dispose(); } return(Ok(new DocStatusModel { d = "image" + doc.Pages.Count + ".png#" + height, Path = folder })); } catch (Exception ex) { return(InternalServerError(ex)); } }
public override void GeneratePreview(Stream docStream, IPreviewGenerationContext context) { var document = new Document(docStream); if (context.StartIndex == 0) { context.SetPageCount(document.Pages.Count); } int firstIndex; int lastIndex; var loggedPageError = false; context.SetIndexes(document.Pages.Count, out firstIndex, out lastIndex); for (var i = firstIndex; i <= lastIndex; i++) { using (var imgStream = new MemoryStream()) { try { var pngDevice = new PngDevice(new Resolution(context.PreviewResolution, context.PreviewResolution)); pngDevice.Process(document.Pages[i + 1], imgStream); if (imgStream.Length == 0) { continue; } context.SavePreviewAndThumbnail(imgStream, i + 1); } catch (Exception ex) { if (Tools.HandlePageError(ex, i + 1, context, !loggedPageError)) { return; } loggedPageError = true; } } } }
public static OutputDevice GenerateDevice(OutputFormat outputFormat, IFile fileWrap = null) { var jobStub = GenerateJobStub(outputFormat); var fileStub = fileWrap ?? Substitute.For <IFile>(); var osHelperStub = Substitute.For <IOsHelper>(); osHelperStub.WindowsFontsFolder.Returns(WindowsFontsFolderDummie); var commandLineUtilStub = Substitute.For <ICommandLineUtil>(); OutputDevice device = null; switch (outputFormat) { case OutputFormat.Jpeg: device = new JpegDevice(jobStub, fileStub, osHelperStub, commandLineUtilStub); break; case OutputFormat.Pdf: case OutputFormat.PdfA1B: case OutputFormat.PdfA2B: case OutputFormat.PdfX: device = new PdfDevice(jobStub, fileStub, osHelperStub, commandLineUtilStub); break; case OutputFormat.Png: device = new PngDevice(jobStub, fileStub, osHelperStub, commandLineUtilStub); break; case OutputFormat.Tif: device = new TiffDevice(jobStub, fileStub, osHelperStub, commandLineUtilStub); break; case OutputFormat.Txt: device = new TextDevice(jobStub, fileStub, osHelperStub, commandLineUtilStub); break; } return(device); }
public static OutputDevice GenerateDevice(OutputFormat outputFormat) { var jobStub = GenerateJobStub(outputFormat); var fileStub = MockRepository.GenerateStub <IFile>(); var osHelperStub = MockRepository.GenerateStub <IOsHelper>(); osHelperStub.Stub(x => x.WindowsFontsFolder).Return(WindowsFontsFolderDummie); var commandLineUtilStub = MockRepository.GenerateStub <ICommandLineUtil>(); OutputDevice device = null; switch (outputFormat) { case OutputFormat.Jpeg: device = new JpegDevice(jobStub, fileStub, osHelperStub, commandLineUtilStub); break; case OutputFormat.Pdf: case OutputFormat.PdfA1B: case OutputFormat.PdfA2B: case OutputFormat.PdfX: device = new PdfDevice(jobStub, fileStub, osHelperStub, commandLineUtilStub); break; case OutputFormat.Png: device = new PngDevice(jobStub, fileStub, osHelperStub, commandLineUtilStub); break; case OutputFormat.Tif: device = new TiffDevice(jobStub, fileStub, osHelperStub, commandLineUtilStub); break; case OutputFormat.Txt: device = new TextDevice(jobStub, fileStub, osHelperStub, commandLineUtilStub); break; } return(device); }
/// <summary> /// This feature is supported by version 19.6 or greater /// </summary> public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); using (Document pdfDocument = new Document(dataDir + "input.pdf")) { using (FileStream imageStream = new FileStream(dataDir + "SetDefaultFontName.png", FileMode.Create)) { Resolution resolution = new Resolution(300); PngDevice pngDevice = new PngDevice(resolution); RenderingOptions ro = new RenderingOptions(); ro.DefaultFontName = "Arial"; pngDevice.RenderingOptions = ro; pngDevice.Process(pdfDocument.Pages[1], imageStream); } } // ExEnd:1 }
private OutputDevice GetOutputDevice(Job job, ConversionMode conversionMode) { OutputDevice device; if (conversionMode == ConversionMode.IntermediateConversion) { return(new PdfIntermediateDevice(job)); } switch (job.Profile.OutputFormat) { case OutputFormat.PdfA1B: case OutputFormat.PdfA2B: case OutputFormat.PdfA3B: case OutputFormat.PdfX: case OutputFormat.Pdf: device = new PdfDevice(job, conversionMode); break; case OutputFormat.Png: device = new PngDevice(job, conversionMode); break; case OutputFormat.Jpeg: device = new JpegDevice(job, conversionMode); break; case OutputFormat.Tif: device = new TiffDevice(job, conversionMode); break; case OutputFormat.Txt: device = new TextDevice(job, conversionMode); break; default: throw new Exception("Illegal OutputFormat specified"); } return(device); }
public static void Run() { try { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); // Open document Document pdfDocument = new Document(dataDir + "input.pdf"); // Create Aspose.Pdf.RenderingOptions to enable font hinting RenderingOptions opts = new RenderingOptions(); opts.UseFontHinting = true; for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++) { using (FileStream imageStream = new FileStream(dataDir + "image" + pageCount + "_out" + ".png", FileMode.Create)) { // Create PNG device with specified attributes // Width, Height, Resolution, Quality // Quality [0-100], 100 is Maximum // Create Resolution object Resolution resolution = new Resolution(300); PngDevice pngDevice = new PngDevice(resolution); // Set predefined rendering options pngDevice.RenderingOptions = opts; // Convert a particular page and save the image to stream pngDevice.Process(pdfDocument.Pages[pageCount], imageStream); // Close stream imageStream.Close(); } } // ExEnd:1 } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private static void GeneratePdfPreview(int previewsFolderId, Stream docStream) { var document = new Aspose.Pdf.Document(docStream); if (StartIndex == 0) { SetPageCount(document.Pages.Count); } var firstIndex = 0; var lastIndex = 0; SetIndexes(StartIndex, document.Pages.Count, out firstIndex, out lastIndex, MaxPreviewCount); for (var i = firstIndex; i <= lastIndex; i++) { //if (!CheckActuality(file)) // break; using (var imgStream = new MemoryStream()) { try { var pngDevice = new PngDevice(); pngDevice.Process(document.Pages[i + 1], imgStream); 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); } } } }
private static string AppendConverter(string fullPath, string appPages, string appRatios, string appHeights) { var originalDocumentFileName = Path.Combine(fullPath, "document.pdf"); var appendedDocumentFileName = Path.Combine(fullPath, "append.pdf"); Document doc = new Document(originalDocumentFileName); int initialPageCount = doc.Pages.Count; //open second document Document pdfDocument2 = new Document(appendedDocumentFileName); //add pages of second document to the first doc.Pages.Add(pdfDocument2.Pages); //save concatenated output file doc.Save(originalDocumentFileName); string Aratio = ""; //string pages = ""; string height = ""; //string Allheights = ""; for (int pageIndex = initialPageCount + 1; pageIndex <= doc.Pages.Count; pageIndex++) { var imageFileName = Path.Combine(fullPath, "image" + pageIndex + ".png"); using (FileStream imageStream = new FileStream(imageFileName, FileMode.Create)) { PngDevice pngDevice = new PngDevice(new Resolution(150)); pngDevice.Process(doc.Pages[pageIndex], imageStream); imageStream.Close(); ScaleImage(imageFileName, 1138, 760, out height, out Aratio); appPages = appPages + "," + "image" + pageIndex + ".png"; appRatios = appRatios + "," + Aratio; appHeights = appHeights + "," + height; } } return(appPages + "%#" + appRatios + "%#" + appHeights); }
public void ConvertToImage(string filepath, string imageFolderName, string imageFolderRootPath) { if (!Directory.Exists(imageFolderRootPath)) { ///若路径不存在,创建路径 Directory.CreateDirectory(imageFolderRootPath); } if (!Directory.Exists(imageFolderRootPath + "\\" + imageFolderName)) { ///若路径不存在,创建路径 Directory.CreateDirectory(imageFolderRootPath + "\\" + imageFolderName); } Document pdfDocument = new Document(filepath); for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++) { string imageFilePath = string.Format(@"{0}\{1}\{2}.png", imageFolderRootPath, imageFolderName, pageCount); using (FileStream imageStream = new FileStream(imageFilePath, FileMode.Create)) { // Create Resolution object Resolution resolution = new Resolution(300); // Create PNG device with specified attributes PngDevice pngDevice = new PngDevice(resolution); // Convert a particular page and save the image to stream pngDevice.Process(pdfDocument.Pages[pageCount], imageStream); // Close stream imageStream.Close(); } } string jsFileName = string.Format(@"{0}\{1}\{2}.js", imageFolderRootPath, imageFolderName, "info"); var fileType = (filepath.EndsWith(".docx")) ? "docx" : "doc"; File.WriteAllText(jsFileName, "var imageInfo={PageCount:" + pdfDocument.Pages.Count + ",FileType:'" + fileType + "'}"); }
public static string AddPage_Click(string lastpage) { try { Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); //insert an empty page at the end of a PDF file doc.Pages.Add(); doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf")); string height = ""; int counter = GetHighestPage(); counter = counter + 1; using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image-1" + counter + ".png"), FileMode.Create)) { //Create Resolution object Resolution resolution = new Resolution(300); //create PNG device with specified attributes PngDevice pngDevice = new PngDevice(); //Convert a particular page and save the image to stream pngDevice.Process(doc.Pages[doc.Pages.Count], imageStream); //Close stream imageStream.Close(); } string Aratio = ""; System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("Input/image-1" + counter + ".png")); ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath("Input/image" + counter + ".png"), out height, out Aratio); image.Dispose(); return("image" + counter + ".png"); } catch (Exception Exp) { return(Exp.Message); } }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //open document Document pdfDocument = new Document(dataDir + "input.pdf"); using (FileStream imageStream = new FileStream(dataDir + "aspose-logo.png", FileMode.Create)) { //create Resolution object Resolution resolution = new Resolution(300); //create PNG device with specified attributes (Width, Height, Resolution) PngDevice pngDevice = new PngDevice(resolution); //convert a particular page and save the image to stream pngDevice.Process(pdfDocument.Pages[1], imageStream); //close stream imageStream.Close(); } }
public static string AddPage_Click(string lastpage) { try { Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); //insert an empty page at the end of a PDF file doc.Pages.Add(); doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf")); string height = ""; int counter = GetHighestPage(); counter = counter + 1; using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image-1" + counter + ".png"), FileMode.Create)) { //Create Resolution object Resolution resolution = new Resolution(300); //create PNG device with specified attributes PngDevice pngDevice = new PngDevice(); //Convert a particular page and save the image to stream pngDevice.Process(doc.Pages[doc.Pages.Count], imageStream); //Close stream imageStream.Close(); } string Aratio = ""; System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("Input/image-1" + counter + ".png")); ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath("Input/image" + counter + ".png"), out height, out Aratio); image.Dispose(); return "image" + counter + ".png"; } catch (Exception Exp) { return Exp.Message; } }
public static void Run() { // ExStart:TrimWhiteSpace // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments(); // Load an existing PDF files Document doc = new Document(dataDir + "input.pdf"); // Render the page to image with 72 DPI PngDevice device = new PngDevice(new Resolution(72)); using (MemoryStream imageStr = new MemoryStream()) { device.Process(doc.Pages[1], imageStr); Bitmap bmp = (Bitmap)Bitmap.FromStream(imageStr); System.Drawing.Imaging.BitmapData imageBitmapData = null; // Determine white areas try { imageBitmapData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); Aspose.Pdf.Rectangle prevCropBox = doc.Pages[1].CropBox; int toHeight = bmp.Height; int toWidth = bmp.Width; int?leftNonWhite = null; int?rightNonWhite = null; int?topNonWhite = null; int?bottomNonWhite = null; for (int y = 0; y < toHeight; y++) { byte[] imageRowBytes = new byte[imageBitmapData.Stride]; // Copy the row data to byte array if (IntPtr.Size == 4) { System.Runtime.InteropServices.Marshal.Copy(new IntPtr(imageBitmapData.Scan0.ToInt32() + y * imageBitmapData.Stride), imageRowBytes, 0, imageBitmapData.Stride); } else { System.Runtime.InteropServices.Marshal.Copy(new IntPtr(imageBitmapData.Scan0.ToInt64() + y * imageBitmapData.Stride), imageRowBytes, 0, imageBitmapData.Stride); } int?leftNonWhite_row = null; int?rightNonWhite_row = null; for (int x = 0; x < toWidth; x++) { if (imageRowBytes[x * 4] != 255 || imageRowBytes[x * 4 + 1] != 255 || imageRowBytes[x * 4 + 2] != 255) { if (leftNonWhite_row == null) { leftNonWhite_row = x; } rightNonWhite_row = x; } } if (leftNonWhite_row != null || rightNonWhite_row != null) { if (topNonWhite == null) { topNonWhite = y; } bottomNonWhite = y; } if (leftNonWhite_row != null && (leftNonWhite == null || leftNonWhite > leftNonWhite_row)) { leftNonWhite = leftNonWhite_row; } if (rightNonWhite_row != null && (rightNonWhite == null || rightNonWhite < rightNonWhite_row)) { rightNonWhite = rightNonWhite_row; } } leftNonWhite = leftNonWhite ?? 0; rightNonWhite = rightNonWhite ?? toWidth; topNonWhite = topNonWhite ?? 0; bottomNonWhite = bottomNonWhite ?? toHeight; // Set crop box with correction to previous crop box doc.Pages[1].CropBox = new Aspose.Pdf.Rectangle( leftNonWhite.Value + prevCropBox.LLX, (toHeight + prevCropBox.LLY) - bottomNonWhite.Value, rightNonWhite.Value + doc.Pages[1].CropBox.LLX, (toHeight + prevCropBox.LLY) - topNonWhite.Value ); } finally { if (imageBitmapData != null) { bmp.UnlockBits(imageBitmapData); } } } dataDir = dataDir + "TrimWhiteSpace_out_.pdf"; // Save the updated document doc.Save(dataDir); // ExEnd:TrimWhiteSpace Console.WriteLine("\nWhite-space trimmed successfully around a page.\nFile saved at " + dataDir); }
public static string AppendConverter(string appPages, string appRatios, string appHeights) { Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); int totalCount = doc.Pages.Count; //open second document Document pdfDocument2 = new Document(HttpContext.Current.Server.MapPath("Convert/append.pdf")); //add pages of second document to the first doc.Pages.Add(pdfDocument2.Pages); //save concatenated output file doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf")); string Aratio = ""; string pages = ""; string height = ""; string Allheights = ""; for (int pageCount = 1; pageCount <= doc.Pages.Count; pageCount++) { if (pageCount > totalCount) { using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png"), FileMode.Create)) { //Create Resolution object //Resolution resolution = new Resolution(300); //create PNG device with specified attributes PngDevice pngDevice = new PngDevice(); //Convert a particular page and save the image to stream pngDevice.Process(doc.Pages[pageCount], imageStream); //Close stream imageStream.Close(); System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png")); ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath("Input/image" + pageCount + ".png"), out height, out Aratio); image.Dispose(); appPages = appPages + "," + "image" + pageCount + ".png"; appRatios = appRatios + "," + Aratio; appHeights = appHeights + "," + height; } } } return appPages + "%#" + appRatios + "%#" + appHeights; }
public static string ReplaceText(string txtFind, string txtReplace, string[] pageList) { try { Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); //create TextAbsorber object to find all instances of the input search phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("(?i)" + txtFind, new Aspose.Pdf.Text.TextOptions.TextSearchOptions(true)); textFragmentAbsorber.TextReplaceOptions.ReplaceAdjustmentAction = TextReplaceOptions.ReplaceAdjustment.WholeWordsHyphenation; //accept the absorber for all the pages doc.Pages.Accept(textFragmentAbsorber); //get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; //loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { //update text and other properties textFragment.Text = txtReplace; } doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf")); doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("Input/")); foreach (FileInfo file in downloadedMessageInfo.GetFiles()) { file.Delete(); } for (int pageCount = 1; pageCount <= doc.Pages.Count; pageCount++) { string filename = "Input/" + pageList[pageCount - 1]; filename = filename.Replace("image", "image-1"); using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath(filename), FileMode.Create)) { //Create Resolution object Resolution resolution = new Resolution(300); //create PNG device with specified attributes PngDevice pngDevice = new PngDevice(); //Convert a particular page and save the image to stream pngDevice.Process(doc.Pages[pageCount], imageStream); //Close stream imageStream.Close(); System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(filename)); string height = ""; string Aratio = ""; ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath(filename.Replace("image-1", "image")), out height, out Aratio); image.Dispose(); } } } catch (Exception exp) { } return "success"; }
public static string ReplaceText(string txtFind, string txtReplace, string[] pageList) { try { Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); //create TextAbsorber object to find all instances of the input search phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("(?i)" + txtFind, new Aspose.Pdf.Text.TextOptions.TextSearchOptions(true)); textFragmentAbsorber.TextReplaceOptions.ReplaceAdjustmentAction = TextReplaceOptions.ReplaceAdjustment.WholeWordsHyphenation; //accept the absorber for all the pages doc.Pages.Accept(textFragmentAbsorber); //get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; //loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { //update text and other properties textFragment.Text = txtReplace; } doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf")); doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("Input/")); foreach (FileInfo file in downloadedMessageInfo.GetFiles()) { file.Delete(); } for (int pageCount = 1; pageCount <= doc.Pages.Count; pageCount++) { string filename = "Input/" + pageList[pageCount - 1]; filename = filename.Replace("image", "image-1"); using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath(filename), FileMode.Create)) { //Create Resolution object Resolution resolution = new Resolution(300); //create PNG device with specified attributes PngDevice pngDevice = new PngDevice(); //Convert a particular page and save the image to stream pngDevice.Process(doc.Pages[pageCount], imageStream); //Close stream imageStream.Close(); System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(filename)); string height = ""; string Aratio = ""; ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath(filename.Replace("image-1", "image")), out height, out Aratio); image.Dispose(); } } } catch (Exception exp) { } return("success"); }
/// <summary> /// Run the Job /// </summary> protected override JobState RunJobWork() { try { if (string.IsNullOrEmpty(Thread.CurrentThread.Name)) { Thread.CurrentThread.Name = "JobWorker"; } } catch (InvalidOperationException) { } try { _ghostScript.Output += Ghostscript_Output; OnJobCompleted += (sender, args) => _ghostScript.Output -= Ghostscript_Output; OutputFiles.Clear(); Logger.Trace("Setting up actions"); SetUpActions(); Logger.Debug("Starting Ghostscript Job"); OutputDevice device; switch (Profile.OutputFormat) { case OutputFormat.PdfA1B: case OutputFormat.PdfA2B: case OutputFormat.PdfX: case OutputFormat.Pdf: device = new PdfDevice(this); break; case OutputFormat.Png: device = new PngDevice(this); break; case OutputFormat.Jpeg: device = new JpegDevice(this); break; case OutputFormat.Tif: device = new TiffDevice(this); break; case OutputFormat.Txt: device = new TextDevice(this); break; default: throw new Exception("Illegal OutputFormat specified"); } Logger.Trace("Output format is: {0}", Profile.OutputFormat.ToString()); _ghostScript.Output += Ghostscript_Logging; var success = _ghostScript.Run(device, JobTempFolder); _ghostScript.Output -= Ghostscript_Logging; Logger.Trace("Finished Ghostscript execution"); if (!success) { var errorMessage = ExtractGhostscriptErrors(GhostscriptOutput); Logger.Error("Ghostscript execution failed: " + errorMessage); ErrorMessage = errorMessage; JobState = JobState.Failed; return(JobState); } ProcessOutput(); Logger.Trace("Moving output files to final location"); MoveOutputFiles(); Logger.Trace("Finished Ghostscript Job"); JobState = JobState.Succeeded; return(JobState); } catch (ProcessingException) { JobState = JobState.Failed; throw; } catch (DeviceException) { JobState = JobState.Failed; throw; } catch (Exception ex) { JobState = JobState.Failed; Logger.Error("There was an error while converting the Job {0}: {1}", JobInfo.InfFile, ex); throw; } }
public static string ImageConverter() { Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); string Aratio = ""; string pages = ""; string Ratios = ""; string height = ""; string Allheights = ""; string fields = ""; int TotalPages = 0; bool licensed = CheckLicense(); if (licensed || (!licensed && doc.Pages.Count <= 4)) { TotalPages = doc.Pages.Count; } else { TotalPages = 4; } for (int pageCount = 1; pageCount <= TotalPages; pageCount++) { using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png"), FileMode.Create)) { //Create Resolution object // Resolution resolution = new Resolution(150); //create PNG device with specified attributes PngDevice pngDevice = new PngDevice(); //Convert a particular page and save the image to stream pngDevice.Process(doc.Pages[pageCount], imageStream); //Close stream imageStream.Close(); System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png")); ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath("Input/image" + pageCount + ".png"), out height, out Aratio); image.Dispose(); if (pageCount == 1) { fields = CheckFields(doc, pageCount, "image" + pageCount + ".png", fields, Convert.ToDouble(Aratio), licensed); } pages = pages + "," + "image" + pageCount + ".png"; Ratios = Ratios + "," + Aratio; Allheights = Allheights + "," + height; } } Ratios = Ratios.Substring(1, Ratios.Length - 1); pages = pages.Substring(1, pages.Length - 1); Allheights = Allheights.Substring(1, Allheights.Length - 1); if (fields != "") { fields = fields.Substring(3, fields.Length - 3); } return(pages + "%#" + Ratios + "%#" + Allheights + "%#" + fields); }
public static void Run() { // ExStart:TrimWhiteSpace // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments(); // Load an existing PDF files Document doc = new Document(dataDir + "input.pdf"); // Render the page to image with 72 DPI PngDevice device = new PngDevice(new Resolution(72)); using (MemoryStream imageStr = new MemoryStream()) { device.Process(doc.Pages[1], imageStr); Bitmap bmp = (Bitmap)Bitmap.FromStream(imageStr); System.Drawing.Imaging.BitmapData imageBitmapData = null; // Determine white areas try { imageBitmapData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); Aspose.Pdf.Rectangle prevCropBox = doc.Pages[1].CropBox; int toHeight = bmp.Height; int toWidth = bmp.Width; int? leftNonWhite = null; int? rightNonWhite = null; int? topNonWhite = null; int? bottomNonWhite = null; for (int y = 0; y < toHeight; y++) { byte[] imageRowBytes = new byte[imageBitmapData.Stride]; // Copy the row data to byte array if (IntPtr.Size == 4) System.Runtime.InteropServices.Marshal.Copy(new IntPtr(imageBitmapData.Scan0.ToInt32() + y * imageBitmapData.Stride), imageRowBytes, 0, imageBitmapData.Stride); else System.Runtime.InteropServices.Marshal.Copy(new IntPtr(imageBitmapData.Scan0.ToInt64() + y * imageBitmapData.Stride), imageRowBytes, 0, imageBitmapData.Stride); int? leftNonWhite_row = null; int? rightNonWhite_row = null; for (int x = 0; x < toWidth; x++) { if (imageRowBytes[x * 4] != 255 || imageRowBytes[x * 4 + 1] != 255 || imageRowBytes[x * 4 + 2] != 255) { if (leftNonWhite_row == null) leftNonWhite_row = x; rightNonWhite_row = x; } } if (leftNonWhite_row != null || rightNonWhite_row != null) { if (topNonWhite == null) topNonWhite = y; bottomNonWhite = y; } if (leftNonWhite_row != null && (leftNonWhite == null || leftNonWhite > leftNonWhite_row)) { leftNonWhite = leftNonWhite_row; } if (rightNonWhite_row != null && (rightNonWhite == null || rightNonWhite < rightNonWhite_row)) { rightNonWhite = rightNonWhite_row; } } leftNonWhite = leftNonWhite ?? 0; rightNonWhite = rightNonWhite ?? toWidth; topNonWhite = topNonWhite ?? 0; bottomNonWhite = bottomNonWhite ?? toHeight; // Set crop box with correction to previous crop box doc.Pages[1].CropBox = new Aspose.Pdf.Rectangle( leftNonWhite.Value + prevCropBox.LLX, (toHeight + prevCropBox.LLY) - bottomNonWhite.Value, rightNonWhite.Value + doc.Pages[1].CropBox.LLX, (toHeight + prevCropBox.LLY) - topNonWhite.Value ); } finally { if (imageBitmapData != null) bmp.UnlockBits(imageBitmapData); } } dataDir = dataDir + "TrimWhiteSpace_out.pdf"; // Save the updated document doc.Save(dataDir); // ExEnd:TrimWhiteSpace Console.WriteLine("\nWhite-space trimmed successfully around a page.\nFile saved at " + dataDir); }
public static string ImageConverter() { Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); string Aratio = ""; string pages = ""; string Ratios = ""; string height = ""; string Allheights = ""; string fields = ""; int TotalPages = 0; bool licensed = CheckLicense(); if (licensed || (!licensed && doc.Pages.Count <= 4)) TotalPages = doc.Pages.Count; else TotalPages = 4; for (int pageCount = 1; pageCount <= TotalPages; pageCount++) { using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png"), FileMode.Create)) { //Create Resolution object // Resolution resolution = new Resolution(150); //create PNG device with specified attributes PngDevice pngDevice = new PngDevice(); //Convert a particular page and save the image to stream pngDevice.Process(doc.Pages[pageCount], imageStream); //Close stream imageStream.Close(); System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("Input/image-1" + pageCount + ".png")); ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath("Input/image" + pageCount + ".png"), out height, out Aratio); image.Dispose(); if(pageCount == 1) fields = CheckFields(doc, pageCount, "image" + pageCount + ".png", fields, Convert.ToDouble(Aratio), licensed); pages = pages + "," + "image" + pageCount + ".png"; Ratios = Ratios + "," + Aratio; Allheights = Allheights + "," + height; } } Ratios = Ratios.Substring(1, Ratios.Length - 1); pages = pages.Substring(1, pages.Length -1); Allheights = Allheights.Substring(1, Allheights.Length -1); if (fields != "") { fields = fields.Substring(3, fields.Length - 3); } return pages + "%#" + Ratios + "%#" + Allheights + "%#" + fields; }
public void TrimSpace(Document doc, int i) { // Render the page to image with 72 DPI PngDevice device = new PngDevice(new Resolution(72)); using (MemoryStream imageStr = new MemoryStream()) { device.Process(doc.Pages[i], imageStr); Bitmap bmp = (Bitmap)Bitmap.FromStream(imageStr); System.Drawing.Imaging.BitmapData imageBitmapData = null; // Determine white areas try { imageBitmapData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); Aspose.Pdf.Rectangle prevCropBox = doc.Pages[i].CropBox; int toHeight = bmp.Height; int toWidth = bmp.Width; int?leftNonWhite = null; int?rightNonWhite = null; int?topNonWhite = null; int?bottomNonWhite = null; for (int y = 0; y < toHeight; y++) { byte[] imageRowBytes = new byte[imageBitmapData.Stride]; // Copy the row data to byte array if (IntPtr.Size == 4) { System.Runtime.InteropServices.Marshal.Copy(new IntPtr(imageBitmapData.Scan0.ToInt32() + y * imageBitmapData.Stride), imageRowBytes, 0, imageBitmapData.Stride); } else { System.Runtime.InteropServices.Marshal.Copy(new IntPtr(imageBitmapData.Scan0.ToInt64() + y * imageBitmapData.Stride), imageRowBytes, 0, imageBitmapData.Stride); } int?leftNonWhite_row = null; int?rightNonWhite_row = null; for (int x = 0; x < toWidth; x++) { if (imageRowBytes[x * 4] != 255 || imageRowBytes[x * 4 + 1] != 255 || imageRowBytes[x * 4 + 2] != 255) { if (leftNonWhite_row == null) { leftNonWhite_row = x; } rightNonWhite_row = x; } } if (leftNonWhite_row != null || rightNonWhite_row != null) { if (topNonWhite == null) { topNonWhite = y; } bottomNonWhite = y; } if (leftNonWhite_row != null && (leftNonWhite == null || leftNonWhite > leftNonWhite_row)) { leftNonWhite = leftNonWhite_row; } if (rightNonWhite_row != null && (rightNonWhite == null || rightNonWhite < rightNonWhite_row)) { rightNonWhite = rightNonWhite_row; } } leftNonWhite = leftNonWhite ?? 0; rightNonWhite = rightNonWhite ?? toWidth; topNonWhite = topNonWhite ?? 0; bottomNonWhite = bottomNonWhite ?? toHeight; // Set crop box with correction to previous crop box doc.Pages[i].CropBox = new Aspose.Pdf.Rectangle( leftNonWhite.Value + prevCropBox.LLX, (toHeight + prevCropBox.LLY) - bottomNonWhite.Value, rightNonWhite.Value + doc.Pages[i].CropBox.LLX, (toHeight + prevCropBox.LLY) - topNonWhite.Value ); } finally { if (imageBitmapData != null) { bmp.UnlockBits(imageBitmapData); } } } // Save the document doc.Save(@"D:\hoctap\webasp\CongVan\CongVan\Areas\Admin\Files\Tmp\spacePdf" + i + ".pdf"); }