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:GetFieldsFromRegion // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Forms(); // Open pdf file Aspose.Pdf.Document doc = new Aspose.Pdf.Document(dataDir + "GetFieldsFromRegion.pdf"); // Create rectangle object to get fields in that area Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(35, 30, 500, 500); // Get the PDF form Aspose.Pdf.Forms.Form form = doc.Form; // Get fields in the rectangular area Aspose.Pdf.Forms.Field[] fields = form.GetFieldsInRect(rectangle); // Display Field names and values foreach (Field field in fields) { // Display image placement properties for all placements Console.Out.WriteLine("Field Name: " + field.FullName + "-" + "Field Value: " + field.Value); } // ExEnd:GetFieldsFromRegion }
static void Main(string[] args) { var doc = new Document(); var page = doc.Pages.Add(); page.Paragraphs.Add(new Aspose.Pdf.Text.TextFragment("Hello World!")); int lowerLeftX = 40; int lowerLeftY = 830; int upperRightX = 120; int upperRightY = 790; var logoFile = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "logo.jpg"); FileStream imageStream = new FileStream(logoFile, FileMode.Open, FileAccess.Read); page.Resources.Images.Add(imageStream); page.Contents.Add(new Aspose.Pdf.Operators.GSave()); Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY); Aspose.Pdf.Matrix matrix = new Aspose.Pdf.Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY }); page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix)); XImage ximage = page.Resources.Images[page.Resources.Images.Count]; page.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name)); page.Contents.Add(new Aspose.Pdf.Operators.GRestore()); var pdfFile = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "new.pdf"); doc.Save(pdfFile); Console.WriteLine("all done.."); }
private void RemoveFooter(Aspose.Pdf.Document pdfDoc) { try { for (int i = 1; i <= pdfDoc.Pages.Count; i++) { Page page = pdfDoc.Pages[i]; Aspose.Pdf.Rectangle rect = new Aspose.Pdf.Rectangle(0, 75, page.Rect.Width, 1); RedactionAnnotation annot = new RedactionAnnotation(page, rect); annot.FillColor = Aspose.Pdf.Color.White; annot.BorderColor = Aspose.Pdf.Color.Yellow; annot.Color = Aspose.Pdf.Color.White; annot.TextAlignment = Aspose.Pdf.HorizontalAlignment.Center; page.Annotations.Add(annot); annot.Redact(); TextAbsorber textAbsorber = new TextAbsorber(); pdfDoc.Pages[i].Accept(textAbsorber); } } catch (Exception ex) { throw ex; } }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Images(); //open document Document pdfDocument = new Document(dataDir+ "AddImage.pdf"); //set coordinates int lowerLeftX = 100; int lowerLeftY = 100; int upperRightX = 200; int upperRightY = 200; //get the page where image needs to be added Page page = pdfDocument.Pages[1]; //load image into stream FileStream imageStream = new FileStream(dataDir + "aspose-logo.jpg", FileMode.Open); //add image to Images collection of Page Resources page.Resources.Images.Add(imageStream); //using GSave operator: this operator saves current graphics state page.Contents.Add(new Operator.GSave()); //create Rectangle and Matrix objects Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY); Aspose.Pdf.DOM.Matrix matrix = new Aspose.Pdf.DOM.Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY }); //using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed page.Contents.Add(new Operator.ConcatenateMatrix(matrix)); XImage ximage = page.Resources.Images[page.Resources.Images.Count]; //using Do operator: this operator draws image page.Contents.Add(new Operator.Do(ximage.Name)); //using GRestore operator: this operator restores graphics state page.Contents.Add(new Operator.GRestore()); //save updated document pdfDocument.Save(dataDir + "AddImage_out.pdf"); }
private void AddPage(Document pdfDocument, string filePath) { var imageInfo = GetImageInfoEx(filePath); var page = pdfDocument.Pages.Add(); // Resize page, or we have default A4 Size page.SetPageSize(imageInfo.PageSize.Width, imageInfo.PageSize.Height); // add image to Images collection of Page Resources page.Resources.Images.Add(imageInfo.Stream); // using GSave operator: this operator saves current graphics state page.Contents.Add(new Operator.GSave()); // create Rectangle and Matrix objects var rectangle = new Rectangle(0, 0, imageInfo.PageSize.Width, imageInfo.PageSize.Height); var matrix = new Matrix(new[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY }); // using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed page.Contents.Add(new Operator.ConcatenateMatrix(matrix)); var ximage = page.Resources.Images[page.Resources.Images.Count]; // using Do operator: this operator draws image page.Contents.Add(new Operator.Do(ximage.Name)); // using GRestore operator: this operator restores graphics state page.Contents.Add(new Operator.GRestore()); page.FreeMemory(); Log.Verbose("Added page to pdf document {documentName}", pdfDocument.FileName); }
public static void Run() { // ExStart:ZoomToPageContents // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Pages(); // Load source PDF file Document doc = new Document(dataDir + "input.pdf"); // Get rectangular region of first page of PDF Aspose.Pdf.Rectangle rect = doc.Pages[1].Rect; // Instantiate PdfPageEditor instance PdfPageEditor ppe = new PdfPageEditor(); // Bind source PDF ppe.BindPdf(dataDir + "input.pdf"); // Set zoom coefficient ppe.Zoom = (float)(rect.Width / rect.Height); // Update page size ppe.PageSize = new Aspose.Pdf.PageSize((float)rect.Height, (float)rect.Width); dataDir = dataDir + "ZoomToPageContents_out_.pdf"; // Save output file doc.Save(dataDir); // ExEnd:ZoomToPageContents System.Console.WriteLine("\nZoom to page contents applied 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 pdf file Aspose.Pdf.Document doc = new Aspose.Pdf.Document(dataDir + "input.pdf"); //Create rectangle object to get fields in that area Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(35, 30, 500, 500); //Get the PDF form Aspose.Pdf.InteractiveFeatures.Forms.Form form = doc.Form; //get fields in the rectangular area Aspose.Pdf.InteractiveFeatures.Forms.Field[] fields = form.GetFieldsInRect(rectangle); //Display Field names and values foreach (Field field in fields) { //Display image placement properties for all placements Console.Out.WriteLine("Field Name: " + field.FullName + "-" + "Field Value: " + field.Value); } }
public static void Run() { // ExStart:ChangeOrientation // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Pages(); Document doc = new Document(dataDir + "input.pdf"); foreach (Page page in doc.Pages) { Aspose.Pdf.Rectangle r = page.MediaBox; double newHeight = r.Width; double newWidth = r.Height; double newLLX = r.LLX; // We must to move page upper in order to compensate changing page size // (lower edge of the page is 0,0 and information is usually placed from the // Top of the page. That's why we move lover edge upper on difference between // Old and new height. double newLLY = r.LLY + (r.Height - newHeight); page.MediaBox = new Aspose.Pdf.Rectangle(newLLX, newLLY, newLLX + newWidth, newLLY + newHeight); // Sometimes we also need to set CropBox (if it was set in original file) page.CropBox = new Aspose.Pdf.Rectangle(newLLX, newLLY, newLLX + newWidth, newLLY + newHeight); // Setting Rotation angle of page page.Rotate = Rotation.on90; } dataDir = dataDir + "ChangeOrientation_out.pdf"; // Save output file doc.Save(dataDir); // ExEnd:ChangeOrientation System.Console.WriteLine("\nPage orientation changed successfully.\nFile saved at " + dataDir); }
public static void Run() { // ExStart:StrikeOutWords // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations(); // Open document Document document = new Document(dataDir + "input.pdf"); // Create TextFragment Absorber instance to search particular text fragment Aspose.Pdf.Text.TextFragmentAbsorber textFragmentAbsorber = new Aspose.Pdf.Text.TextFragmentAbsorber("Estoque"); // Iterate through pages of PDF document for (int i = 1; i <= document.Pages.Count; i++) { // Get first page of PDF document Page page = document.Pages[1]; page.Accept(textFragmentAbsorber); } // Create a collection of Absorbed text Aspose.Pdf.Text.TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; // Iterate on above collection for (int j = 1; j <= textFragmentCollection.Count; j++) { Aspose.Pdf.Text.TextFragment textFragment = textFragmentCollection[j]; // Get rectangular dimensions of TextFragment object Aspose.Pdf.Rectangle rect = new Aspose.Pdf.Rectangle( (float)textFragment.Position.XIndent, (float)textFragment.Position.YIndent, (float)textFragment.Position.XIndent + (float)textFragment.Rectangle.Width, (float)textFragment.Position.YIndent + (float)textFragment.Rectangle.Height); // Instantiate StrikeOut Annotation instance StrikeOutAnnotation strikeOut = new StrikeOutAnnotation(textFragment.Page, rect); // Set opacity for annotation strikeOut.Opacity = .80f; // Set the border for annotation instance strikeOut.Border = new Border(strikeOut); // Set the color of annotation strikeOut.Color = Aspose.Pdf.Color.Red; // Add annotation to annotations collection of TextFragment textFragment.Page.Annotations.Add(strikeOut); } dataDir = dataDir + "StrikeOutWords_out.pdf"; document.Save(dataDir); // ExEnd:StrikeOutWords Console.WriteLine("\nWords strikeout successfully.\nFile saved at " + dataDir); }
public static string TestReadGAC_BAK(string path) { List <string> l = new List <string>(); Document pdfDocument = new Aspose.Pdf.Document(path); Aspose.Pdf.Text.TextFragmentAbsorber textFragmentAbsorberAddress = new Aspose.Pdf.Text.TextFragmentAbsorber(); double width = 50d; double height = 30d; double x = 20d; double y = 585d; for (int i = 0; i < 3; i++) { // textFragmentAbsorberAddress.TextSearchOptions.LimitToPageBounds = true; textFragmentAbsorberAddress.TextSearchOptions.LimitToPageBounds = false; var rectangle = new Aspose.Pdf.Rectangle ( //llx: x, //lly: y - i * height, //urx: width, //ury: height llx: width, lly: height, urx: x, ury: y - i * height ); textFragmentAbsorberAddress.TextSearchOptions.Rectangle = rectangle; pdfDocument.Pages[1].Accept(textFragmentAbsorberAddress); foreach (Aspose.Pdf.Text.TextFragment tf in textFragmentAbsorberAddress.TextFragments) { l.Add(tf.Text); } } l = l.Distinct().ToList(); if (l.Count > 0) { return(l[0]); } else { return(string.Empty); } }
public static bool ConverToPdf(List <String> files, string target, AsposeConvertDelegate d = null) { logger.Info("ConverToPdf - files=" + files.Count + " , target=" + target); double percent = 0.0; int page = 0; int total = 0; double second = 0; string path = ""; string message = ""; DateTime startTime = DateTime.Now; if (File.Exists(target)) { FileInfo fi = new FileInfo(target); fi.Delete(); logger.Debug("ConverToPdf - delete - fileName=" + fi.FullName); } Document document = new Document(); total = files.Count; if (d != null) { second = (DateTime.Now - startTime).TotalSeconds; percent = 0.2; message = "开始添加文件,共" + total + "页!"; d.Invoke(percent, page, total, second, path, message); } for (page = 0; page < total; page++) { path = files[page]; Page pdfPage = document.Pages.Insert(page + 1); BitmapImage bitemap = new BitmapImage(); bitemap.BeginInit(); bitemap.StreamSource = new FileStream(path, FileMode.Open); bitemap.EndInit(); logger.Debug("ConverToPdf - PixelWidth=" + bitemap.PixelWidth + ", PixelHeight=" + bitemap.PixelHeight + ", path=" + path); Aspose.Pdf.Rectangle rec = new Aspose.Pdf.Rectangle(0, 0, bitemap.PixelWidth, bitemap.PixelHeight); pdfPage.SetPageSize(bitemap.PixelWidth, bitemap.PixelHeight); pdfPage.AddImage(bitemap.StreamSource, rec, bitemap.PixelWidth, bitemap.PixelHeight, true); 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); } } document.Save(target); return(true); }
static void Main(string[] args) { // Instantiate License class and call its SetLicense method to use the license //Aspose.Pdf.License license = new Aspose.Pdf.License(); //license.SetLicense("Aspose.Pdf.lic"); #region Чушня // Set coordinates int lowerLeftX = 100; int lowerLeftY = 100; int upperRightX = 200; int upperRightY = 200; #endregion var document = new Document(new FileStream(_cleanPath, FileMode.Open, FileAccess.Read, FileShare.None)); //var imageStream = new FileStream($"{_testPath}\\1.jpeg", FileMode.Open, FileAccess.Read, FileShare.None); var imageStream = new FileStream(Path.Combine(_testPath, _svgHerb), FileMode.Open, FileAccess.Read, FileShare.None); document.Pages.Add(); // последняя страница var page = document.Pages[document.Pages.Count - 1]; page.Resources.Images.Add(imageStream); page.Contents.Add(new Aspose.Pdf.Operators.GSave()); #region Чушня // Create Rectangle and Matrix objects Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY); Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY }); // Using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix)); XImage ximage = page.Resources.Images[page.Resources.Images.Count]; // Using Do operator: this operator draws image page.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name)); // Using GRestore operator: this operator restores graphics state page.Contents.Add(new Aspose.Pdf.Operators.GRestore()); #endregion document.Save(_output); }
/// <summary> /// Generate a non- PDF/UA compliant PDF for use in demo /// </summary> /// <param name="outputFilePath">Full output path including filename with extension</param> public static void CreateDemoNonCompliantPdfFile(string outputFilePath) { var pdfDoc = new Document(); pdfDoc.Pages.Add(); var pageOne = pdfDoc.Pages[1]; #region Add image int lowerLeftX = 100; int lowerLeftY = 680; int upperRightX = 200; int upperRightY = 780; FileStream imageStream = new FileStream("aspose.png", FileMode.Open); pageOne.Resources.Images.Add(imageStream); pageOne.Contents.Add(new Aspose.Pdf.Operators.GSave()); Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY); Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY }); pageOne.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix)); XImage ximage = pageOne.Resources.Images[pageOne.Resources.Images.Count]; pageOne.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name)); pageOne.Contents.Add(new Aspose.Pdf.Operators.GRestore()); #endregion #region Add text fragments var textFragmentOne = new TextFragment("Some large indigo text for our header."); textFragmentOne.Position = new Position(100, 800); textFragmentOne.TextState.FontSize = 24; textFragmentOne.TextState.Font = FontRepository.FindFont("TimesNewRoman"); textFragmentOne.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Indigo); var textFragmentTwo = new TextFragment("Some smaller blue text in a non-tagged document."); textFragmentTwo.Position = new Position(100, 660); textFragmentTwo.TextState.FontSize = 12; textFragmentTwo.TextState.Font = FontRepository.FindFont("TimesNewRoman"); textFragmentTwo.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue); var textBuilder = new TextBuilder(pageOne); textBuilder.AppendText(textFragmentOne); textBuilder.AppendText(textFragmentTwo); #endregion pdfDoc.Save(outputFilePath); }
public static void Run() { // ExStart:AddImage // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Images(); // Open document Document pdfDocument = new Document(dataDir + "AddImage.pdf"); // Set coordinates int lowerLeftX = 100; int lowerLeftY = 100; int upperRightX = 200; int upperRightY = 200; // Get the page where image needs to be added Page page = pdfDocument.Pages[1]; // Load image into stream FileStream imageStream = new FileStream(dataDir + "aspose-logo.jpg", FileMode.Open); // Add image to Images collection of Page Resources page.Resources.Images.Add(imageStream); // Using GSave operator: this operator saves current graphics state page.Contents.Add(new Operator.GSave()); // Create Rectangle and Matrix objects Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY); Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY }); // Using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed page.Contents.Add(new Operator.ConcatenateMatrix(matrix)); XImage ximage = page.Resources.Images[page.Resources.Images.Count]; // Using Do operator: this operator draws image page.Contents.Add(new Operator.Do(ximage.Name)); // Using GRestore operator: this operator restores graphics state page.Contents.Add(new Operator.GRestore()); dataDir = dataDir + "AddImage_out_.pdf"; // Save updated document pdfDocument.Save(dataDir); // ExEnd:AddImage Console.WriteLine("\nImage added successfully.\nFile saved at " + dataDir); }
public static void Run() { // ExStart:AddlnkAnnotation // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations(); Document doc = new Document(); Page pdfPage = doc.Pages.Add(); System.Drawing.Rectangle drect = new System.Drawing.Rectangle(); drect.Height = (int)pdfPage.Rect.Height; drect.Width = (int)pdfPage.Rect.Width; drect.X = 0; drect.Y = 0; Aspose.Pdf.Rectangle arect = Aspose.Pdf.Rectangle.FromRect(drect); IList <Point[]> inkList = new List <Point[]>(); Aspose.Pdf.Point[] arrpt = new Aspose.Pdf.Point[3]; inkList.Add(arrpt); arrpt[0] = new Aspose.Pdf.Point(100, 800); arrpt[1] = new Aspose.Pdf.Point(200, 800); arrpt[2] = new Aspose.Pdf.Point(200, 700); InkAnnotation ia = new InkAnnotation(pdfPage, arect, inkList); ia.Title = "XXX"; ia.Color = Aspose.Pdf.Color.LightBlue; // (GetColorFromString(stroke.InkColor)); ia.CapStyle = CapStyle.Rounded; Border border = new Border(ia); border.Width = 25; ia.Opacity = 0.5; pdfPage.Annotations.Add(ia); dataDir = dataDir + "AddlnkAnnotation_out.pdf"; // Save output file doc.Save(dataDir); // ExEnd:AddlnkAnnotation Console.WriteLine("\nlnk annotation added successfully.\nFile saved at " + dataDir); }
private MemoryStream AddWatermarkToFile(Document pdfDocument, ref PdfFileStamp pdfStamp, string sUserName, DateTime dtCurrentDate, string sCompany) { string sTextDate = dtCurrentDate.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture); FormattedText wtext = new FormattedText("Confidential", new FontColor(220, 20, 60), new FontColor(255, 255, 255), Aspose.Pdf.Facades.FontStyle.HelveticaBold, EncodingType.Winansi, true, 35); wtext.AddNewLineText(sUserName, 5); wtext.AddNewLineText(sTextDate, 5); int nPageCount = 1; foreach (Aspose.Pdf.Page pg in pdfDocument.Pages) { //get the page size position for each page Aspose.Pdf.Rectangle rtPage = pg.TrimBox; AddWatermarkToPage(rtPage.Width, rtPage.Height, pg, sUserName, sTextDate); nPageCount++; } MemoryStream outStream = new MemoryStream(); //save updated PDF file DocumentPrivilege pv = null; pv = DocumentPrivilege.AllowAll; pv.ChangeAllowLevel = 0; pv.CopyAllowLevel = 1; pv.PrintAllowLevel = 2; pdfStamp.Document.Encrypt("", new Guid().ToString(), pv, CryptoAlgorithm.RC4x128, false); pdfStamp.Save(outStream); return(outStream); }
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"); //set coordinates int lowerLeftX = 100; int lowerLeftY = 100; int upperRightX = 200; int upperRightY = 200; //get the page where image needs to be added Page page = pdfDocument.Pages[1]; //load image into stream FileStream imageStream = new FileStream(dataDir + "aspose-logo.jpg", FileMode.Open); //add image to Images collection of Page Resources page.Resources.Images.Add(imageStream); //using GSave operator: this operator saves current graphics state page.Contents.Add(new Operator.GSave()); //create Rectangle and Matrix objects Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY); Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY }); //using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed page.Contents.Add(new Operator.ConcatenateMatrix(matrix)); XImage ximage = page.Resources.Images[page.Resources.Images.Count]; //using Do operator: this operator draws image page.Contents.Add(new Operator.Do(ximage.Name)); //using GRestore operator: this operator restores graphics state page.Contents.Add(new Operator.GRestore()); //save updated document pdfDocument.Save(dataDir + "output.pdf"); }
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); }
private void debug_createImage(string fileFullName) { Document pdfDocument = new Document(); Page page = pdfDocument.Pages.Add(); // Load image into stream //FileStream imageStream = new FileStream("https://www.shareicon.net/data/48x48/2016/08/05/806939_document_512x512.png", FileMode.Open); string imageUrl = "https://www.shareicon.net/data/48x48/2016/08/05/806939_document_512x512.png"; /* * // Creates an HttpWebRequest with the specified URL. * HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(imageUrl); * // Sends the HttpWebRequest and waits for the response. * HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); * // Gets the stream associated with the response. * Stream imageStream = myHttpWebResponse.GetResponseStream(); */ using (WebClient webClient = new WebClient()) { //var watch = System.Diagnostics.Stopwatch.StartNew(); byte[] data = webClient.DownloadData(imageUrl); using (MemoryStream imageStream = new MemoryStream(data)) { // Add image to Images collection of Page Resources page.Resources.Images.Add(imageStream); //Console.WriteLine(imageData.Length + " bytes received"); } //watch.Stop(); //Console.WriteLine("Total Execution Time :{0}", watch.ElapsedMilliseconds); } int lowerLeftX = 100; int lowerLeftY = 600; int upperRightX = 148; int upperRightY = 648; // Using GSave operator: this operator saves current graphics state page.Contents.Add(new Operator.GSave()); // Create Rectangle and Matrix objects Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY); Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY }); // Using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed page.Contents.Add(new Operator.ConcatenateMatrix(matrix)); XImage ximage = page.Resources.Images[page.Resources.Images.Count]; // Using Do operator: this operator draws image page.Contents.Add(new Operator.Do(ximage.Name)); // Using GRestore operator: this operator restores graphics state page.Contents.Add(new Operator.GRestore()); // Save updated document pdfDocument.Save(fileFullName); }
public static void Run() { try { // ExStart:HighlightCharacterInPDF // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); int resolution = 150; Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(dataDir + "input.pdf"); using (MemoryStream ms = new MemoryStream()) { PdfConverter conv = new PdfConverter(pdfDocument); conv.Resolution = new Resolution(resolution, resolution); conv.GetNextImage(ms, System.Drawing.Imaging.ImageFormat.Png); Bitmap bmp = (Bitmap)Bitmap.FromStream(ms); using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp)) { float scale = resolution / 72f; gr.Transform = new System.Drawing.Drawing2D.Matrix(scale, 0, 0, -scale, 0, bmp.Height); for (int i = 0; i < pdfDocument.Pages.Count; i++) { Page page = pdfDocument.Pages[1]; // Create TextAbsorber object to find all words TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(@"[\S]+"); textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true; page.Accept(textFragmentAbsorber); // Get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; // Loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { if (i == 0) { gr.DrawRectangle( Pens.Yellow, (float)textFragment.Position.XIndent, (float)textFragment.Position.YIndent, (float)textFragment.Rectangle.Width, (float)textFragment.Rectangle.Height); for (int segNum = 1; segNum <= textFragment.Segments.Count; segNum++) { TextSegment segment = textFragment.Segments[segNum]; for (int charNum = 1; charNum <= segment.Characters.Count; charNum++) { CharInfo characterInfo = segment.Characters[charNum]; Aspose.Pdf.Rectangle rect = page.GetPageRect(true); Console.WriteLine("TextFragment = " + textFragment.Text + " Page URY = " + rect.URY + " TextFragment URY = " + textFragment.Rectangle.URY); gr.DrawRectangle( Pens.Black, (float)characterInfo.Rectangle.LLX, (float)characterInfo.Rectangle.LLY, (float)characterInfo.Rectangle.Width, (float)characterInfo.Rectangle.Height); } gr.DrawRectangle( Pens.Green, (float)segment.Rectangle.LLX, (float)segment.Rectangle.LLY, (float)segment.Rectangle.Width, (float)segment.Rectangle.Height); } } } } } dataDir = dataDir + "HighlightCharacterInPDF_out.png"; bmp.Save(dataDir, System.Drawing.Imaging.ImageFormat.Png); } // ExEnd:HighlightCharacterInPDF Console.WriteLine("\nCharacters highlighted successfully in pdf document.\nFile saved at " + dataDir); } catch (Exception ex) { 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 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"); }