diff --git a/working-with-images/add-background-image-multiply-blend-mode.cs b/working-with-images/add-background-image-multiply-blend-mode.cs new file mode 100644 index 00000000..0ae141da --- /dev/null +++ b/working-with-images/add-background-image-multiply-blend-mode.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Drawing; // for BlendMode enum (if available) + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + const string outputPdf = "output.pdf"; + const string imagePath = "background.png"; + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + + if (!File.Exists(imagePath)) + { + Console.Error.WriteLine($"Background image not found: {imagePath}"); + return; + } + + // Load the existing PDF document + using (Document doc = new Document(inputPdf)) + { + // Create a background artifact for the first page + BackgroundArtifact bgArtifact = new BackgroundArtifact(); + + // Set the image for the background artifact + bgArtifact.SetImage(imagePath); + + // Mark the artifact as a background (placed behind page contents) + bgArtifact.IsBackground = true; + + // OPTIONAL: Set blend mode to Multiply for subtle shading. + // The BlendMode property exists on Artifact (or its derived types) in newer versions. + // If the property is not available in your version, you may need to adjust opacity instead. + // Uncomment the following line if BlendMode is supported: + // bgArtifact.BlendMode = BlendMode.Multiply; + + // Add the artifact to the page's artifact collection + // (Page indices are 1‑based in Aspose.Pdf) + doc.Pages[1].Artifacts.Add(bgArtifact); + + // Save the modified PDF + doc.Save(outputPdf); + } + + Console.WriteLine($"Background image added and saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/add-background-image-to-pdf-pages.cs b/working-with-images/add-background-image-to-pdf-pages.cs new file mode 100644 index 00000000..0a356b7a --- /dev/null +++ b/working-with-images/add-background-image-to-pdf-pages.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; +using Aspose.Pdf; // Core Aspose.Pdf namespace + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_with_background.pdf"; + const string imagePath = "background.png"; // Path to the background image + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPath}"); + return; + } + + if (!File.Exists(imagePath)) + { + Console.Error.WriteLine($"Background image not found: {imagePath}"); + return; + } + + // Load the existing PDF document + using (Document doc = new Document(inputPath)) + { + // Iterate over all pages (Aspose.Pdf uses 1‑based indexing) + for (int i = 1; i <= doc.Pages.Count; i++) + { + Page page = doc.Pages[i]; + + // Create a background artifact, set the image and opacity (30%) + BackgroundArtifact bgArtifact = new BackgroundArtifact(); + bgArtifact.SetImage(imagePath); // Load image from file + bgArtifact.Opacity = 0.3; // 30 percent opacity + + // Add the artifact to the page's artifact collection + page.Artifacts.Add(bgArtifact); + } + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"PDF saved with background image: {outputPath}"); + } +} \ No newline at end of file diff --git a/working-with-images/add-background-pattern-image-to-pdf-pages.cs b/working-with-images/add-background-pattern-image-to-pdf-pages.cs new file mode 100644 index 00000000..77fc528a --- /dev/null +++ b/working-with-images/add-background-pattern-image-to-pdf-pages.cs @@ -0,0 +1,53 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const string imagePath = "pattern.png"; + + // Verify input files exist + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPath}"); + return; + } + if (!File.Exists(imagePath)) + { + Console.Error.WriteLine($"Background image not found: {imagePath}"); + return; + } + + // Load the PDF document (lifecycle rule: use using) + using (Document doc = new Document(inputPath)) + { + // Iterate over all pages (1‑based indexing) + foreach (Page page in doc.Pages) + { + // Create a background artifact for the page + BackgroundArtifact bg = new BackgroundArtifact(); + + // Place the artifact behind page contents + bg.IsBackground = true; + + // Set opacity to 10 percent (0.1) + bg.Opacity = 0.1; + + // Assign the pattern image to the artifact + bg.SetImage(imagePath); + + // Add the artifact to the page + page.Artifacts.Add(bg); + } + + // Save the modified PDF (lifecycle rule: use Save inside using) + doc.Save(outputPath); + } + + Console.WriteLine($"Background pattern applied and saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/add-background-pattern-to-pdf-pages.cs b/working-with-images/add-background-pattern-to-pdf-pages.cs new file mode 100644 index 00000000..a351afa9 --- /dev/null +++ b/working-with-images/add-background-pattern-to-pdf-pages.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; // source PDF + const string outputPath = "output_with_bg.pdf"; // result PDF + const string patternPath = "pattern.png"; // background pattern image + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPath}"); + return; + } + + if (!File.Exists(patternPath)) + { + Console.Error.WriteLine($"Pattern image not found: {patternPath}"); + return; + } + + // Load the PDF document (using block ensures proper disposal) + using (Document doc = new Document(inputPath)) + { + // Iterate over all pages (Aspose.Pdf uses 1‑based indexing) + for (int i = 1; i <= doc.Pages.Count; i++) + { + Page page = doc.Pages[i]; + + // Create a background artifact for the page + BackgroundArtifact bgArtifact = new BackgroundArtifact(); + + // Set the image that will be used as the background pattern + bgArtifact.SetImage(patternPath); + + // Place the artifact behind page contents + bgArtifact.IsBackground = true; + + // Set a subtle opacity (5 percent) + bgArtifact.Opacity = 0.05; + + // Add the artifact to the page's artifact collection + page.Artifacts.Add(bgArtifact); + } + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"PDF saved with background pattern: {outputPath}"); + } +} \ No newline at end of file diff --git a/working-with-images/add-background-texture-to-pdf-pages.cs b/working-with-images/add-background-texture-to-pdf-pages.cs new file mode 100644 index 00000000..4d706a40 --- /dev/null +++ b/working-with-images/add-background-texture-to-pdf-pages.cs @@ -0,0 +1,68 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Annotations; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + const string outputPdf = "output_with_background.pdf"; + const string bgImagePath = "texture.png"; // subtle texture image + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input file not found: {inputPdf}"); + return; + } + + if (!File.Exists(bgImagePath)) + { + Console.Error.WriteLine($"Background image not found: {bgImagePath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPdf)) + { + // Iterate over all pages (1‑based indexing) + for (int i = 1; i <= doc.Pages.Count; i++) + { + Page page = doc.Pages[i]; + + // ----- Approach 1: use Page.BackgroundImage (generator only) ----- + // This sets the background image for the page. It is not read when loading an existing PDF, + // but it will be written to the output PDF. + Aspose.Pdf.Image bgImg = new Aspose.Pdf.Image(); + bgImg.File = bgImagePath; + page.BackgroundImage = bgImg; + + // ----- Approach 2: use a BackgroundArtifact ----- + // Adding a BackgroundArtifact gives more control (e.g., opacity, alignment). + // The artifact is placed behind page contents (IsBackground = true). + // Blend mode "Overlay" is not directly exposed in Aspose.Pdf; using opacity can simulate a subtle effect. + BackgroundArtifact artifact = new BackgroundArtifact(); + artifact.IsBackground = true; // place behind page contents + artifact.Opacity = 0.5; // semi‑transparent for subtle overlay effect + artifact.ArtifactHorizontalAlignment = HorizontalAlignment.Center; + artifact.ArtifactVerticalAlignment = VerticalAlignment.Center; + + // Set the image for the artifact + using (FileStream imgStream = File.OpenRead(bgImagePath)) + { + artifact.SetImage(imgStream); + } + + // Add the artifact to the page + page.Artifacts.Add(artifact); + } + + // Save the modified PDF + doc.Save(outputPdf); + } + + Console.WriteLine($"PDF saved with background texture: {outputPdf}"); + } +} \ No newline at end of file diff --git a/working-with-images/add-company-logo-to-first-page.cs b/working-with-images/add-company-logo-to-first-page.cs new file mode 100644 index 00000000..56211b66 --- /dev/null +++ b/working-with-images/add-company-logo-to-first-page.cs @@ -0,0 +1,50 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; + const string outputPdfPath = "output.pdf"; + const string logoImagePath = "logo.png"; + + // Verify that the required files exist + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + if (!File.Exists(logoImagePath)) + { + Console.Error.WriteLine($"Logo image not found: {logoImagePath}"); + return; + } + + // Load the PDF document (create‑load‑save lifecycle) + using (Document pdfDoc = new Document(inputPdfPath)) + { + // Aspose.Pdf uses 1‑based page indexing; get the first page + Page firstPage = pdfDoc.Pages[1]; + + // Create an ImageStamp for the logo image + ImageStamp logoStamp = new ImageStamp(logoImagePath); + + // Center the stamp horizontally and vertically on the page + logoStamp.HorizontalAlignment = HorizontalAlignment.Center; + logoStamp.VerticalAlignment = VerticalAlignment.Center; + + // Ensure the stamp appears in front of page content + logoStamp.Background = false; + + // Add the stamp to the first page only + firstPage.AddStamp(logoStamp); + + // Save the modified PDF (save‑rule) + pdfDoc.Save(outputPdfPath); + } + + Console.WriteLine($"Company logo added to first page and saved as '{outputPdfPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/add-diagonal-image-watermark-to-pdf.cs b/working-with-images/add-diagonal-image-watermark-to-pdf.cs new file mode 100644 index 00000000..95184a7c --- /dev/null +++ b/working-with-images/add-diagonal-image-watermark-to-pdf.cs @@ -0,0 +1,51 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; // source PDF + const string outputPdf = "watermarked.pdf"; // result PDF + const string watermarkImage = "logo.png"; // image to use as watermark + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input file not found: {inputPdf}"); + return; + } + + if (!File.Exists(watermarkImage)) + { + Console.Error.WriteLine($"Watermark image not found: {watermarkImage}"); + return; + } + + // Load the PDF document (using the recommended load pattern) + using (Document doc = new Document(inputPdf)) + { + // Iterate over all pages (Aspose.Pdf uses 1‑based indexing) + foreach (Page page in doc.Pages) + { + // Create an ImageStamp with the watermark image + ImageStamp stamp = new ImageStamp(watermarkImage); + + // Set the arbitrary rotation angle (45 degrees) for diagonal placement + stamp.RotateAngle = 45; + + // Optional: center the stamp on the page + stamp.HorizontalAlignment = HorizontalAlignment.Center; + stamp.VerticalAlignment = VerticalAlignment.Center; + + // Add the stamp to the current page + page.AddStamp(stamp); + } + + // Save the modified PDF (using the standard Save method) + doc.Save(outputPdf); + } + + Console.WriteLine($"Watermarked PDF saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/add-dicom-image-to-pdf-using-filestream.cs b/working-with-images/add-dicom-image-to-pdf-using-filestream.cs new file mode 100644 index 00000000..18aefad1 --- /dev/null +++ b/working-with-images/add-dicom-image-to-pdf-using-filestream.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string dicomPath = "medical.dcm"; // Path to the DICOM image file + const string outputPdf = "output.pdf"; // Desired PDF output path + + if (!File.Exists(dicomPath)) + { + Console.Error.WriteLine($"File not found: {dicomPath}"); + return; + } + + // Keep the DICOM stream open until the PDF is saved + using (FileStream dicomStream = new FileStream(dicomPath, FileMode.Open, FileAccess.Read)) + { + // Create a new PDF document + using (Document pdfDoc = new Document()) + { + // Add a blank page to the document + pdfDoc.Pages.Add(); + + // Create an Image object and assign the DICOM stream + Image dicomImage = new Image(); + dicomImage.ImageStream = dicomStream; // Use the stream as the image source + + // Optionally set size or scaling (commented out) + // dicomImage.FixWidth = 500; + // dicomImage.FixHeight = 500; + + // Add the image to the first page + pdfDoc.Pages[1].Paragraphs.Add(dicomImage); + + // Save the PDF document + pdfDoc.Save(outputPdf); + } + } + + Console.WriteLine($"PDF with DICOM image saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/add-header-image-to-pdf-pages.cs b/working-with-images/add-header-image-to-pdf-pages.cs new file mode 100644 index 00000000..6bcc3551 --- /dev/null +++ b/working-with-images/add-header-image-to-pdf-pages.cs @@ -0,0 +1,62 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; // source PDF + const string outputPdf = "output.pdf"; // result PDF + const string headerImg = "header.png"; // decorative header image + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input file not found: {inputPdf}"); + return; + } + + if (!File.Exists(headerImg)) + { + Console.Error.WriteLine($"Header image not found: {headerImg}"); + return; + } + + // Load the existing PDF document (lifecycle rule: load) + using (Document doc = new Document(inputPdf)) + { + // Iterate over all pages (1‑based indexing) + for (int i = 1; i <= doc.Pages.Count; i++) + { + Page page = doc.Pages[i]; + + // Page dimensions (points) + double pageWidth = page.PageInfo.Width; + double pageHeight = page.PageInfo.Height; + + // Desired header image height (adjust as needed) + double imgHeight = 50; // points + double marginTop = 10; // space from top edge + + // Compute rectangle for the header image. + // Origin is bottom‑left, so bottom = pageHeight - imgHeight - marginTop + double left = 0; + double right = pageWidth; + double bottom = pageHeight - imgHeight - marginTop; + double top = pageHeight - marginTop; + + // Fully qualified rectangle to avoid ambiguity + Aspose.Pdf.Rectangle rect = new Aspose.Pdf.Rectangle(left, bottom, right, top); + + // Add the image to the page within the rectangle. + // The image will be centered and scaled proportionally. + page.AddImage(headerImg, rect); + } + + // Save the modified PDF (lifecycle rule: save) + doc.Save(outputPdf); + } + + Console.WriteLine($"Header image added to each page. Saved as '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/add-image-with-alt-text-to-pdf.cs b/working-with-images/add-image-with-alt-text-to-pdf.cs new file mode 100644 index 00000000..9681d073 --- /dev/null +++ b/working-with-images/add-image-with-alt-text-to-pdf.cs @@ -0,0 +1,53 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; + const string outputPdfPath = "output.pdf"; + const string imagePath = "newImage.png"; + const string altText = "Description of the newly added image for assistive technologies"; + + // Verify required files exist + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + if (!File.Exists(imagePath)) + { + Console.Error.WriteLine($"Image file not found: {imagePath}"); + return; + } + + // Load the existing PDF + using (Document doc = new Document(inputPdfPath)) + { + // Add the image to the first page + Page page = doc.Pages[1]; + Aspose.Pdf.Image img = new Aspose.Pdf.Image + { + File = imagePath, + // Optional: set explicit size (width/height in points) + FixWidth = 200, + FixHeight = 150 + }; + page.Paragraphs.Add(img); + + // Set alternative text for the newly added image + foreach (XImage xImg in page.Resources.Images) + { + // TrySetAlternativeText returns true if the alt text was applied + xImg.TrySetAlternativeText(altText, page); + } + + // Save the modified PDF + doc.Save(outputPdfPath); + } + + Console.WriteLine($"PDF saved with image and alt text: {outputPdfPath}"); + } +} \ No newline at end of file diff --git a/working-with-images/add-png-logo-to-first-page.cs b/working-with-images/add-png-logo-to-first-page.cs new file mode 100644 index 00000000..07c0cc56 --- /dev/null +++ b/working-with-images/add-png-logo-to-first-page.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + const string logoPng = "logo.png"; + const string outputPdf = "output.pdf"; + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + + if (!File.Exists(logoPng)) + { + Console.Error.WriteLine($"Logo image not found: {logoPng}"); + return; + } + + // Load the PDF document (wrapped in using for deterministic disposal) + using (Document doc = new Document(inputPdf)) + { + // Get the first page (Aspose.Pdf uses 1‑based indexing) + Page firstPage = doc.Pages[1]; + + // Define the rectangle where the logo will be placed: + // lower‑left (llx, lly) = (50, 750), upper‑right (urx, ury) = (150, 800) + // Adjust these values to position the logo as needed. + Aspose.Pdf.Rectangle logoRect = new Aspose.Pdf.Rectangle(50, 750, 150, 800); + + // Add the PNG logo to the specified rectangle on the first page. + firstPage.AddImage(logoPng, logoRect); + + // Save the modified PDF. + doc.Save(outputPdf); + } + + Console.WriteLine($"Logo added and saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/add-raster-image-to-pdf-page.cs b/working-with-images/add-raster-image-to-pdf-page.cs new file mode 100644 index 00000000..dac305b8 --- /dev/null +++ b/working-with-images/add-raster-image-to-pdf-page.cs @@ -0,0 +1,41 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + // Path to the raster image file (PNG, JPEG, etc.) + const string imagePath = "image.png"; + + // Path where the resulting PDF will be saved + const string outputPdf = "output.pdf"; + + // Verify that the image file exists + if (!File.Exists(imagePath)) + { + Console.Error.WriteLine($"Image file not found: {imagePath}"); + return; + } + + // Create a new PDF document and ensure it is disposed properly + using (Document pdfDoc = new Document()) + { + // Add a blank page to the document (pages are 1‑based) + pdfDoc.Pages.Add(); + + // Create an Image object and assign the image file + Image img = new Image(); + img.File = imagePath; + + // Add the image to the first page's Paragraphs collection + pdfDoc.Pages[1].Paragraphs.Add(img); + + // Save the PDF document to the specified output path + pdfDoc.Save(outputPdf); + } + + Console.WriteLine($"PDF with image saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/add-scalable-footer-image-to-pdf-pages.cs b/working-with-images/add-scalable-footer-image-to-pdf-pages.cs new file mode 100644 index 00000000..9da0110d --- /dev/null +++ b/working-with-images/add-scalable-footer-image-to-pdf-pages.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; // source PDF + const string outputPdfPath = "output.pdf"; // result PDF + const string footerImgPath = "footer.png"; // decorative footer image + + // Ensure source files exist + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + if (!File.Exists(footerImgPath)) + { + Console.Error.WriteLine($"Footer image not found: {footerImgPath}"); + return; + } + + // Load the PDF document (lifecycle rule: use using for disposal) + using (Document doc = new Document(inputPdfPath)) + { + // Load the image once to obtain its original dimensions + Image sampleImg = new Image(); + sampleImg.File = footerImgPath; + double originalImgWidth = sampleImg.BitmapSize.Width; + double originalImgHeight = sampleImg.BitmapSize.Height; + + // Iterate over all pages (Aspose.Pdf uses 1‑based indexing) + foreach (Page page in doc.Pages) + { + // Current page width (points) + double pageWidth = page.PageInfo.Width; + + // Compute height that preserves the image aspect ratio + double scaledHeight = pageWidth * originalImgHeight / originalImgWidth; + + // Define a rectangle that spans the full page width and the computed height, + // positioned at the bottom of the page (y = 0). + Aspose.Pdf.Rectangle rect = new Aspose.Pdf.Rectangle( + 0, // left + 0, // bottom + pageWidth, // right (full width) + scaledHeight); // top + + // Add the image to the page. The overload with (Stream, Rectangle) + // centers the image within the rectangle while keeping its proportions. + using (FileStream imgStream = File.OpenRead(footerImgPath)) + { + page.AddImage(imgStream, rect); + } + } + + // Save the modified PDF (lifecycle rule: save inside using block) + doc.Save(outputPdfPath); + } + + Console.WriteLine($"Footer image added to each page. Saved as '{outputPdfPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/add-semi-transparent-image-watermark-to-pdf-pages.cs b/working-with-images/add-semi-transparent-image-watermark-to-pdf-pages.cs new file mode 100644 index 00000000..400d1855 --- /dev/null +++ b/working-with-images/add-semi-transparent-image-watermark-to-pdf-pages.cs @@ -0,0 +1,51 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + // Paths to the source PDF, watermark image, and output PDF + const string inputPdfPath = "input.pdf"; + const string watermarkImagePath = "watermark.png"; + const string outputPdfPath = "output.pdf"; + + // Opacity can be read from a configuration source; here we set it directly + double watermarkOpacity = 0.3; // Range: 0.0 (transparent) to 1.0 (opaque) + + // Validate required files + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + if (!File.Exists(watermarkImagePath)) + { + Console.Error.WriteLine($"Watermark image not found: {watermarkImagePath}"); + return; + } + + // Load the PDF document + using (Document pdfDoc = new Document(inputPdfPath)) + { + // Create an ImageStamp from the watermark image + ImageStamp stamp = new ImageStamp(watermarkImagePath); + stamp.Opacity = watermarkOpacity; // Set semi‑transparent opacity + stamp.Background = false; // Place on top of page content + stamp.HorizontalAlignment = HorizontalAlignment.Center; + stamp.VerticalAlignment = VerticalAlignment.Center; + + // Apply the stamp to every page + foreach (Page page in pdfDoc.Pages) + { + page.AddStamp(stamp); + } + + // Save the watermarked PDF + pdfDoc.Save(outputPdfPath); + } + + Console.WriteLine($"Watermarked PDF saved to '{outputPdfPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/add-semi-transparent-overlay-image-to-pdf.cs b/working-with-images/add-semi-transparent-overlay-image-to-pdf.cs new file mode 100644 index 00000000..1a425da9 --- /dev/null +++ b/working-with-images/add-semi-transparent-overlay-image-to-pdf.cs @@ -0,0 +1,61 @@ +using System; +using System.IO; +using Aspose.Pdf; // Core API (Document, Page, ImageStamp) + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; // source PDF + const string overlayImg = "overlay.png"; // semi‑transparent image to overlay + const string outputPdf = "output.pdf"; // result PDF + + // Verify files exist + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + if (!File.Exists(overlayImg)) + { + Console.Error.WriteLine($"Overlay image not found: {overlayImg}"); + return; + } + + // Load the PDF inside a using block for deterministic disposal + using (Document doc = new Document(inputPdf)) + { + // Create an ImageStamp from the overlay image + ImageStamp stamp = new ImageStamp(overlayImg) + { + // Place the stamp over the page content (false = top layer) + Background = false, + + // Semi‑transparent (0.0 = fully transparent, 1.0 = opaque) + Opacity = 0.5f, + + // Center the image on each page + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + + // Scale the image to fit the page while preserving aspect ratio + // (Zoom = 1.0 means original size; adjust if needed) + Zoom = 1.0f + }; + + // Apply the stamp to every page (pages are 1‑based) + foreach (Page page in doc.Pages) + { + page.AddStamp(stamp); + } + + // Optional: replace any remaining transparency with opaque graphics + // doc.FlattenTransparency(); + + // Save the modified PDF + doc.Save(outputPdf); + } + + Console.WriteLine($"Overlay applied and saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/add-semi-transparent-overlay-to-pdf-pages.cs b/working-with-images/add-semi-transparent-overlay-to-pdf-pages.cs new file mode 100644 index 00000000..25e37b2c --- /dev/null +++ b/working-with-images/add-semi-transparent-overlay-to-pdf-pages.cs @@ -0,0 +1,99 @@ +using System; +using System.IO; +using System.Text.Json; +using Aspose.Pdf; +using Aspose.Pdf.Drawing; + +class ThemeConfig +{ + public required string Color { get; set; } // Hex string, e.g. "#FFAA00" + public required double Opacity { get; set; } // 0.0 to 1.0 +} + +class Program +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; + const string outputPdfPath = "output.pdf"; + const string themeConfigPath = "theme.json"; + + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + if (!File.Exists(themeConfigPath)) + { + Console.Error.WriteLine($"Theme config not found: {themeConfigPath}"); + return; + } + + // Load theme configuration + ThemeConfig theme = JsonSerializer.Deserialize(File.ReadAllText(themeConfigPath))!; + if (theme == null || string.IsNullOrWhiteSpace(theme.Color)) + { + Console.Error.WriteLine("Invalid theme configuration."); + return; + } + + // Parse hex color to Aspose.Pdf.Color (RGB) and also retrieve the raw R,G,B bytes + var (baseColor, r, g, b) = ParseHexColor(theme.Color); + + // Ensure opacity is within 0..1 and compute alpha byte + double opacity = Math.Max(0.0, Math.Min(1.0, theme.Opacity)); + int alpha = (int)Math.Round(opacity * 255); + // Create a color that includes the alpha channel for transparency + Aspose.Pdf.Color overlayColor = Aspose.Pdf.Color.FromArgb(alpha, r, g, b); + + // Load the source PDF + using (Document srcDoc = new Document(inputPdfPath)) + { + // Apply the overlay to each page of the source document + foreach (Page page in srcDoc.Pages) + { + // Create a Graph that covers the whole page + Graph graph = new Graph(page.MediaBox.Width, page.MediaBox.Height); + + // Create a rectangle shape that fills the page + var rect = new Aspose.Pdf.Drawing.Rectangle( + 0f, + 0f, + (float)page.MediaBox.Width, + (float)page.MediaBox.Height); + + rect.GraphInfo = new GraphInfo + { + FillColor = overlayColor, + Color = overlayColor // outline (optional) + }; + + graph.Shapes.Add(rect); + + // Insert the graph as the first paragraph so it appears behind existing content + page.Paragraphs.Insert(0, graph); + } + + // Save the modified PDF + srcDoc.Save(outputPdfPath); + } + + Console.WriteLine($"Overlay applied and saved to '{outputPdfPath}'."); + } + + // Helper: converts "#RRGGBB" or "RRGGBB" to Aspose.Pdf.Color (RGB, no alpha) + // Returns the Aspose.Pdf.Color together with the integer R,G,B components (0‑255) + static (Aspose.Pdf.Color color, int r, int g, int b) ParseHexColor(string hex) + { + string clean = hex.TrimStart('#'); + if (clean.Length != 6) + throw new ArgumentException("Color must be in RRGGBB format."); + + int r = Convert.ToInt32(clean.Substring(0, 2), 16); + int g = Convert.ToInt32(clean.Substring(2, 2), 16); + int b = Convert.ToInt32(clean.Substring(4, 2), 16); + // Aspose.Pdf.Color.FromRgb expects values in the range 0‑1 + Aspose.Pdf.Color aspColor = Aspose.Pdf.Color.FromRgb(r / 255.0, g / 255.0, b / 255.0); + return (aspColor, r, g, b); + } +} diff --git a/working-with-images/add-transparent-png-overlay-to-pdf-pages.cs b/working-with-images/add-transparent-png-overlay-to-pdf-pages.cs new file mode 100644 index 00000000..d436daf0 --- /dev/null +++ b/working-with-images/add-transparent-png-overlay-to-pdf-pages.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Pdf; // Core Aspose.Pdf namespace (no Facades) + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; // source PDF + const string overlayPng = "overlay.png"; // transparent PNG to overlay + const string outputPdf = "output.pdf"; // result PDF + + // Validate input files + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + if (!File.Exists(overlayPng)) + { + Console.Error.WriteLine($"Overlay image not found: {overlayPng}"); + return; + } + + // Load the PDF (lifecycle rule: use Document constructor inside using) + using (Document doc = new Document(inputPdf)) + { + // Create an ImageStamp for the PNG overlay. + // Background = false ensures the stamp is placed on top of existing content. + ImageStamp overlayStamp = new ImageStamp(overlayPng); + overlayStamp.Background = false; // foreground (over content) + + // Apply the stamp to every page. + foreach (Page page in doc.Pages) + { + // Resize the stamp to cover the whole page. + overlayStamp.Width = page.MediaBox.Width; + overlayStamp.Height = page.MediaBox.Height; + + // Position the stamp at the lower‑left corner of the page. + overlayStamp.XIndent = 0; // horizontal offset from the left edge + overlayStamp.YIndent = 0; // vertical offset from the bottom edge + + // AddStamp adds the stamp at the current Z‑order (top of the page). + page.AddStamp(overlayStamp); + } + + // Save the modified PDF (lifecycle rule: use Document.Save) + doc.Save(outputPdf); + } + + Console.WriteLine($"Transparent overlay applied and saved to '{outputPdf}'."); + } +} diff --git a/working-with-images/agents.md b/working-with-images/agents.md new file mode 100644 index 00000000..5bc3cc13 --- /dev/null +++ b/working-with-images/agents.md @@ -0,0 +1,136 @@ +--- +name: working-with-images +description: C# examples for working-with-images using Aspose.PDF for .NET +language: csharp +framework: net10.0 +parent: ../agents.md +--- + +# AGENTS - working-with-images + +## Persona + +You are a C# developer specializing in PDF processing using Aspose.PDF for .NET, +working within the **working-with-images** category. +This folder contains standalone C# examples for working-with-images operations. +See the root [agents.md](../agents.md) for repository-wide conventions and boundaries. + +## Scope +- This folder contains examples for **working-with-images**. +- Files are standalone `.cs` examples stored directly in this folder. + +## Required Namespaces + +- `using Aspose.Pdf;` (70/70 files) ← category-specific +- `using Aspose.Pdf.Devices;` (11/70 files) +- `using Aspose.Pdf.Vector;` (6/70 files) +- `using Aspose.Pdf.Annotations;` (4/70 files) +- `using Aspose.Pdf.Text;` (4/70 files) +- `using Aspose.Pdf.Drawing;` (3/70 files) +- `using Aspose.Pdf.Facades;` (2/70 files) +- `using Aspose.Pdf.Optimization;` (2/70 files) +- `using Aspose.Pdf.Tagged;` (2/70 files) +- `using Aspose.Pdf.LogicalStructure;` (1/70 files) +- `using System;` (70/70 files) +- `using System.IO;` (70/70 files) +- `using System.Drawing;` (4/70 files) +- `using System.Drawing.Imaging;` (4/70 files) +- `using System.Collections.Generic;` (3/70 files) +- `using System.Text.Json;` (3/70 files) +- `using System.Runtime.InteropServices;` (1/70 files) + +## Common Code Pattern + +Most files follow this pattern: + +```csharp +using (Document doc = new Document("input.pdf")) +{ + // ... operations ... + doc.Save("output.pdf"); +} +``` + +## Files in this folder + +| File | Title | Key APIs | Description | +|------|-------|----------|-------------| +| [add-background-image-multiply-blend-mode](./add-background-image-multiply-blend-mode.cs) | Add Background Image with Multiply Blend Mode to PDF | `Document`, `Save`, `BackgroundArtifact` | Shows how to load an existing PDF, attach a background image artifact to a page, optionally set i... | +| [add-background-image-to-pdf-pages](./add-background-image-to-pdf-pages.cs) | Add Background Image to PDF Pages with Opacity | `Document`, `Page`, `BackgroundArtifact` | Shows how to place a background image on every page of a PDF and set its opacity to 30 % using As... | +| [add-background-pattern-image-to-pdf-pages](./add-background-pattern-image-to-pdf-pages.cs) | Add Background Pattern Image to PDF Pages | `Document`, `Page`, `BackgroundArtifact` | Shows how to place a semi‑transparent pattern image as a background on every page of a PDF using ... | +| [add-background-pattern-to-pdf-pages](./add-background-pattern-to-pdf-pages.cs) | Add Background Pattern Image to PDF Pages | `Document`, `Page`, `BackgroundArtifact` | Shows how to place a semi‑transparent background pattern image on every page of a PDF using Aspos... | +| [add-background-texture-to-pdf-pages](./add-background-texture-to-pdf-pages.cs) | Add Background Texture Image to PDF Pages | `Document`, `Page`, `Image` | Shows how to place a subtle texture image as a background on every page of an existing PDF and si... | +| [add-company-logo-to-first-page](./add-company-logo-to-first-page.cs) | Add Company Logo to First Page of PDF | `Document`, `Page`, `ImageStamp` | Shows how to load a PDF with Aspose.Pdf, create an ImageStamp for a logo, center it on the first ... | +| [add-diagonal-image-watermark-to-pdf](./add-diagonal-image-watermark-to-pdf.cs) | Add Diagonal Image Watermark to PDF Pages | `Document`, `Page`, `ImageStamp` | Demonstrates how to load a PDF with Aspose.Pdf, add an image stamp as a watermark on each page, r... | +| [add-dicom-image-to-pdf-using-filestream](./add-dicom-image-to-pdf-using-filestream.cs) | Add DICOM Image to PDF Using FileStream | `Document`, `Image`, `Add` | Shows how to embed a DICOM medical image into a PDF page by reading the image from a FileStream a... | +| [add-header-image-to-pdf-pages](./add-header-image-to-pdf-pages.cs) | Add Header Image to Each PDF Page | `Document`, `Page`, `PageInfo` | Shows how to load a PDF with Aspose.Pdf, calculate a top‑margin rectangle for each page, insert a... | +| [add-image-with-alt-text-to-pdf](./add-image-with-alt-text-to-pdf.cs) | Add Image with Alternative Text to PDF | `Document`, `Page`, `Image` | Demonstrates inserting an image into a PDF and assigning alternative text for accessibility using... | +| [add-png-logo-to-first-page](./add-png-logo-to-first-page.cs) | Add PNG Logo to First Page of PDF | `Document`, `Page`, `Rectangle` | Shows how to load a PDF with Aspose.Pdf, place a PNG logo at specific coordinates on the first pa... | +| [add-raster-image-to-pdf-page](./add-raster-image-to-pdf-page.cs) | Add Raster Image to PDF Page | `Document`, `Image`, `Add` | Demonstrates how to insert a PNG/JPEG raster image onto a new PDF page using Aspose.Pdf's Image c... | +| [add-scalable-footer-image-to-pdf-pages](./add-scalable-footer-image-to-pdf-pages.cs) | Add Scalable Footer Image to PDF Pages | `Document`, `Page`, `Image` | Shows how to insert a decorative footer image on every page of a PDF and scale it proportionally ... | +| [add-semi-transparent-image-watermark-to-pdf-pages](./add-semi-transparent-image-watermark-to-pdf-pages.cs) | Add Semi-Transparent Image Watermark to PDF Pages | `Document`, `ImageStamp`, `AddStamp` | Demonstrates loading a PDF with Aspose.Pdf, creating an ImageStamp, setting its opacity for a sem... | +| [add-semi-transparent-overlay-image-to-pdf](./add-semi-transparent-overlay-image-to-pdf.cs) | Add Semi-Transparent Overlay Image to PDF | `Document`, `ImageStamp`, `AddStamp` | Shows how to place a semi‑transparent PNG overlay on every page of a PDF using Aspose.Pdf's Image... | +| [add-semi-transparent-overlay-to-pdf-pages](./add-semi-transparent-overlay-to-pdf-pages.cs) | Add Semi-Transparent Color Overlay to PDF Pages | `Document`, `Page`, `Graph` | The example reads a theme configuration (hex color and opacity) from a JSON file and applies a se... | +| [add-transparent-png-overlay-to-pdf-pages](./add-transparent-png-overlay-to-pdf-pages.cs) | Add Transparent PNG Overlay to PDF Pages | `Document`, `Page`, `ImageStamp` | Shows how to place a transparent PNG image over every page of a PDF as a foreground stamp using A... | +| [batch-extract-images-from-pdfs](./batch-extract-images-from-pdfs.cs) | Batch Extract Images from PDFs | `Document`, `Page`, `XImage` | Demonstrates how to iterate over PDF files in a folder, access each page's image resources with A... | +| [batch-extract-vector-graphics-from-pdfs](./batch-extract-vector-graphics-from-pdfs.cs) | Batch Extract Vector Graphics from PDFs | `Document`, `Page`, `SvgExtractor` | Shows how to process multiple PDF files, detect pages containing vector graphics, and extract eac... | +| [collect-image-resolution-metadata](./collect-image-resolution-metadata.cs) | Collect Image Resolution Metadata from PDF Pages | `Document`, `Page`, `ImagePlacementAbsorber` | Loads a PDF, iterates through each page, extracts image placements with ImagePlacementAbsorber, a... | +| [compress-large-images-in-pdf](./compress-large-images-in-pdf.cs) | Compress Large Images in PDF to Reduce File Size | `Document`, `OptimizationOptions`, `ImageCompressionOptions` | Shows how to replace images larger than 1 MB with compressed JPEG versions using Aspose.Pdf optim... | +| [compress-large-images-in-pdf__v2](./compress-large-images-in-pdf__v2.cs) | Compress Large Images in PDF to Reduce File Size | `Document`, `OptimizationOptions`, `ImageCompressionOptions` | Demonstrates loading a PDF, configuring image compression options to downsize images, optimizing ... | +| [convert-even-pages-to-grayscale](./convert-even-pages-to-grayscale.cs) | Convert Even Pages to Grayscale in PDF | `Document`, `Page`, `MakeGrayscale` | Shows how to load a PDF with Aspose.Pdf, iterate through its pages, apply a grayscale conversion ... | +| [convert-pdf-pages-to-jpeg-with-default-font](./convert-pdf-pages-to-jpeg-with-default-font.cs) | Convert PDF Pages to JPEG with Default Font Override | `Document`, `JpegDevice`, `Resolution` | Demonstrates loading a PDF, setting the default font to Arial for rendering, and converting each ... | +| [convert-pdf-to-multi-page-tiff-default-font](./convert-pdf-to-multi-page-tiff-default-font.cs) | Convert PDF to Multi-Page TIFF with Default Font | `Document`, `Resolution`, `TiffSettings` | Loads a PDF document and converts it into a multi‑page TIFF image using Aspose.Pdf, applying a sp... | +| [convert-pdf-to-png-with-default-font](./convert-pdf-to-png-with-default-font.cs) | Convert PDF Pages to PNG Images with Default Font Substituti... | `Document`, `Resolution`, `PngDevice` | Loads a PDF document, sets the rendering default font to Times New Roman to handle missing fonts,... | +| [correct-pdf-image-orientation](./correct-pdf-image-orientation.cs) | Correct PDF Image Orientation Using EXIF Data | `Document`, `Page`, `XImageCollection` | Loads a PDF, reads EXIF orientation from each embedded image, rotates the image when needed, and ... | +| [delete-raster-image-from-pdf-page](./delete-raster-image-from-pdf-page.cs) | Delete Raster Image from PDF Page | `Document`, `Page`, `ImageDeleteAction` | Demonstrates how to remove a specific raster image from a PDF page by deleting its reference from... | +| [export-pdf-pages-to-bmp-300-dpi](./export-pdf-pages-to-bmp-300-dpi.cs) | Export PDF Pages as BMP Images (300 DPI) | `Document`, `Resolution`, `BmpDevice` | Loads a PDF document, sets a 300 DPI resolution, and renders each page to a separate BMP file usi... | +| [extract-raster-images-from-pdf-preserve-format](./extract-raster-images-from-pdf-preserve-format.cs) | Extract Raster Images from PDF Preserving Original Format | `Document`, `Page`, `XImage` | The example loads a PDF with Aspose.Pdf, iterates through each page's image resources, determines... | +| ... | | | *and 40 more files* | + +## Category Statistics +- Total examples: 70 + +## Category-Specific Tips + +### Key API Surface +- `Aspose.Pdf.Devices.BmpDevice` +- `Aspose.Pdf.Devices.ColorDepth` +- `Aspose.Pdf.Devices.CompressionType` +- `Aspose.Pdf.Devices.EmfDevice` +- `Aspose.Pdf.Devices.PngDevice` +- `Aspose.Pdf.Devices.Resolution` +- `Aspose.Pdf.Devices.ShapeType` +- `Aspose.Pdf.Devices.TiffDevice` +- `Aspose.Pdf.Devices.TiffSettings` +- `Aspose.Pdf.Document` +- `Aspose.Pdf.Facades.PdfExtractor` +- `Aspose.Pdf.Facades.PdfProducer` +- `Aspose.Pdf.Image` +- `Aspose.Pdf.ImportFormat` +- `Aspose.Pdf.Optimization.ImageCompressionOptions` + +### Rules +- Load a PDF document: Document {doc} = new Document("{input_pdf}"); +- Iterate over pages using 1‑based index: for (int {page}=1; {page} <= {doc}.Pages.Count; {page}++) { ... } +- Create a Resolution object for desired DPI: Resolution {resolution} = new Resolution({int}); +- Instantiate a PngDevice with the resolution: PngDevice pngDevice = new PngDevice({resolution}); +- Render a page to an output stream: pngDevice.Process({doc}.Pages[{page}], {output_stream}); + +### Warnings +- PdfProducer resides in the Aspose.Pdf.Facades namespace and may be deprecated in newer library versions; ensure the correct version is referenced. +- A valid Aspose.PDF license is required for production use. +- Assumes Aspose.Pdf.Devices.EmfDevice and Resolution are the correct fully qualified types; if the library version changes the namespace may differ. +- The example manually closes the MemoryStream; using a 'using' statement is recommended to ensure proper disposal. +- The code reads the entire file into a byte array before creating the MemoryStream; for large images a direct stream copy may be more efficient. + +## General Tips +- See parent [agents.md](../agents.md) for: + - **Boundaries** — Always / Ask First / Never rules for all examples + - **Common Mistakes** — verified anti-patterns that cause build failures + - **Domain Knowledge** — cross-cutting API-specific gotchas + - **Testing Guide** — build and run verification steps +- Review code examples in this folder for working-with-images patterns + + +Updated: 2026-05-08 | Run: `20260508_145008_6ada82` + diff --git a/working-with-images/batch-extract-images-from-pdfs.cs b/working-with-images/batch-extract-images-from-pdfs.cs new file mode 100644 index 00000000..58f32af3 --- /dev/null +++ b/working-with-images/batch-extract-images-from-pdfs.cs @@ -0,0 +1,117 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + // Folder containing the PDFs to process + const string inputFolder = "InputPdfs"; + // Folder where extracted images will be saved + const string outputFolder = "ExtractedImages"; + + if (!Directory.Exists(inputFolder)) + { + Console.Error.WriteLine($"Input folder not found: {inputFolder}"); + return; + } + + // Ensure the output directory exists + Directory.CreateDirectory(outputFolder); + + // Get all PDF files in the input folder + string[] pdfFiles = Directory.GetFiles(inputFolder, "*.pdf"); + if (pdfFiles.Length == 0) + { + Console.WriteLine("No PDF files found in the input folder."); + return; + } + + foreach (string pdfPath in pdfFiles) + { + try + { + // Load each PDF inside a using block for deterministic disposal + using (Document doc = new Document(pdfPath)) + { + // Pages are 1‑based in Aspose.Pdf + for (int pageIndex = 1; pageIndex <= doc.Pages.Count; pageIndex++) + { + Page page = doc.Pages[pageIndex]; + int imageIndex = 1; + + // Iterate over the image collection; it yields XImage objects directly + foreach (XImage img in page.Resources.Images) + { + // Save the image to a memory stream first + using (var ms = new MemoryStream()) + { + img.Save(ms); // XImage.Save accepts a Stream, not a file path + byte[] imageBytes = ms.ToArray(); + + // Determine a suitable file extension based on the image header + string extension = GetImageExtensionFromBytes(imageBytes); + + // Build a unique file name: _page_img. + string pdfName = Path.GetFileNameWithoutExtension(pdfPath); + string fileName = $"{pdfName}_page{pageIndex}_img{imageIndex}{extension}"; + string outPath = Path.Combine(outputFolder, fileName); + + // Write the image bytes to disk + File.WriteAllBytes(outPath, imageBytes); + Console.WriteLine($"Saved image: {outPath}"); + } + + imageIndex++; + } + } + } + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error processing '{pdfPath}': {ex.Message}"); + } + } + } + + // Helper method to obtain a file extension based on the image header bytes. + // Falls back to .png if the format cannot be determined. + static string GetImageExtensionFromBytes(byte[] bytes) + { + if (bytes == null || bytes.Length < 4) + return ".png"; // default + + // JPEG: FF D8 FF + if (bytes.Length >= 3 && bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF) + return ".jpg"; + + // PNG: 89 50 4E 47 0D 0A 1A 0A + if (bytes.Length >= 8 && bytes[0] == 0x89 && bytes[1] == 0x50 && bytes[2] == 0x4E && bytes[3] == 0x47) + return ".png"; + + // GIF: 47 49 46 38 (GIF8) + if (bytes.Length >= 4 && bytes[0] == 0x47 && bytes[1] == 0x49 && bytes[2] == 0x46 && bytes[3] == 0x38) + return ".gif"; + + // BMP: 42 4D + if (bytes.Length >= 2 && bytes[0] == 0x42 && bytes[1] == 0x4D) + return ".bmp"; + + // TIFF (little endian): 49 49 2A 00 + if (bytes.Length >= 4 && bytes[0] == 0x49 && bytes[1] == 0x49 && bytes[2] == 0x2A && bytes[3] == 0x00) + return ".tiff"; + + // TIFF (big endian): 4D 4D 00 2A + if (bytes.Length >= 4 && bytes[0] == 0x4D && bytes[1] == 0x4D && bytes[2] == 0x00 && bytes[3] == 0x2A) + return ".tiff"; + + // WebP: RIFF....WEBP + if (bytes.Length >= 12 && bytes[0] == 0x52 && bytes[1] == 0x49 && bytes[2] == 0x46 && bytes[3] == 0x46 && + bytes[8] == 0x57 && bytes[9] == 0x45 && bytes[10] == 0x42 && bytes[11] == 0x50) + return ".webp"; + + // Default fallback + return ".png"; + } +} diff --git a/working-with-images/batch-extract-vector-graphics-from-pdfs.cs b/working-with-images/batch-extract-vector-graphics-from-pdfs.cs new file mode 100644 index 00000000..5dd6af86 --- /dev/null +++ b/working-with-images/batch-extract-vector-graphics-from-pdfs.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Vector; + +class BatchVectorGraphicsExtractor +{ + static void Main() + { + // Input directory containing PDF files + const string inputDirectory = @"C:\InputPdfs"; + // Output root directory where each PDF will have its own folder + const string outputRoot = @"C:\ExtractedVectors"; + + if (!Directory.Exists(inputDirectory)) + { + Console.Error.WriteLine($"Input directory not found: {inputDirectory}"); + return; + } + + // Ensure the output root exists + Directory.CreateDirectory(outputRoot); + + // Get all PDF files in the input directory + string[] pdfFiles = Directory.GetFiles(inputDirectory, "*.pdf", SearchOption.TopDirectoryOnly); + if (pdfFiles.Length == 0) + { + Console.WriteLine("No PDF files found to process."); + return; + } + + foreach (string pdfPath in pdfFiles) + { + string pdfName = Path.GetFileNameWithoutExtension(pdfPath); + // Create a dedicated folder for this PDF's extracted graphics + string pdfOutputFolder = Path.Combine(outputRoot, pdfName); + Directory.CreateDirectory(pdfOutputFolder); + + try + { + // Load the PDF document (lifecycle rule: wrap in using) + using (Document doc = new Document(pdfPath)) + { + // Iterate pages using 1‑based indexing (global rule) + for (int pageIndex = 1; pageIndex <= doc.Pages.Count; pageIndex++) + { + Page page = doc.Pages[pageIndex]; + + // Check if the page actually contains vector graphics + if (!page.HasVectorGraphics()) + continue; // Skip pages without vector content + + // Create a sub‑folder for this page's SVG files + string pageFolder = Path.Combine(pdfOutputFolder, $"Page_{pageIndex}"); + Directory.CreateDirectory(pageFolder); + + // Use SvgExtractor to write each vector graphic as an SVG file + SvgExtractor extractor = new SvgExtractor(); + extractor.Extract(page, pageFolder); + } + } + + Console.WriteLine($"Extracted vectors from '{pdfPath}' to '{pdfOutputFolder}'."); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error processing '{pdfPath}': {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/working-with-images/collect-image-resolution-metadata.cs b/working-with-images/collect-image-resolution-metadata.cs new file mode 100644 index 00000000..6d071334 --- /dev/null +++ b/working-with-images/collect-image-resolution-metadata.cs @@ -0,0 +1,42 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Iterate over all pages (1‑based indexing) + for (int i = 1; i <= doc.Pages.Count; i++) + { + Page page = doc.Pages[i]; + + // Search for image placements on the current page + ImagePlacementAbsorber absorber = new ImagePlacementAbsorber(); + page.Accept(absorber); + + Console.WriteLine($"Page {i}: {absorber.ImagePlacements.Count} image(s) found."); + + // Report resolution (DPI) and visible size for each image + foreach (ImagePlacement placement in absorber.ImagePlacements) + { + double dpiX = placement.Resolution.X; + double dpiY = placement.Resolution.Y; + Console.WriteLine($" Image resolution: {dpiX} DPI (horizontal), {dpiY} DPI (vertical)"); + Console.WriteLine($" Visible size: {placement.Rectangle.Width} x {placement.Rectangle.Height}"); + } + } + } + } +} \ No newline at end of file diff --git a/working-with-images/compress-large-images-in-pdf.cs b/working-with-images/compress-large-images-in-pdf.cs new file mode 100644 index 00000000..96a61a10 --- /dev/null +++ b/working-with-images/compress-large-images-in-pdf.cs @@ -0,0 +1,50 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Optimization; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_compressed.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document (using the lifecycle rule) + using (Document doc = new Document(inputPath)) + { + // Configure optimization options to compress images. + // This will replace large images with compressed JPEG versions. + OptimizationOptions opt = new OptimizationOptions + { + // Merge identical objects to reduce size. + CompressObjects = true, + + // Configure image compression. + ImageCompressionOptions = + { + CompressImages = true, // Enable image compression. + ImageQuality = 75, // JPEG quality (0‑100). Adjust as needed. + // MaxResolution = 150; // Optional: limit image resolution (DPI). + } + }; + + // Apply the optimization to the document. + doc.OptimizeResources(opt); + + // Optional: enable additional stream merging. + doc.OptimizeSize = true; + + // Save the optimized PDF (using the lifecycle rule). + doc.Save(outputPath); + } + + Console.WriteLine($"Compressed PDF saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/compress-large-images-in-pdf__v2.cs b/working-with-images/compress-large-images-in-pdf__v2.cs new file mode 100644 index 00000000..55b092ae --- /dev/null +++ b/working-with-images/compress-large-images-in-pdf__v2.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Optimization; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_compressed.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document (lifecycle rule: load) + using (Document doc = new Document(inputPath)) + { + // Create optimization options. Some options are set via object initializer, + // but ImageCompressionOptions is read‑only, so we modify its instance later. + OptimizationOptions opt = new OptimizationOptions + { + RemoveUnusedObjects = true, + CompressObjects = true + // other options can be added here if needed + }; + + // Configure image compression on the existing ImageCompressionOptions instance. + opt.ImageCompressionOptions.CompressImages = true; + opt.ImageCompressionOptions.ImageQuality = 75; // 0‑100, lower = smaller size + // Optional: set the encoding (e.g., JPEG) if you want explicit control. + // opt.ImageCompressionOptions.Encoding = ImageEncoding.Jpeg; + + // Apply the optimization to the document. + doc.OptimizeResources(opt); + + // Save the optimized PDF (lifecycle rule: save) + doc.Save(outputPath); + } + + Console.WriteLine($"Optimized PDF saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/convert-even-pages-to-grayscale.cs b/working-with-images/convert-even-pages-to-grayscale.cs new file mode 100644 index 00000000..f4ed70d5 --- /dev/null +++ b/working-with-images/convert-even-pages-to-grayscale.cs @@ -0,0 +1,39 @@ +using System; +using System.IO; +using Aspose.Pdf; // Core API +using Aspose.Pdf.Devices; // For page processing if needed (not used here) + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_grayscale_even_pages.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Pages are 1‑based in Aspose.Pdf + for (int i = 1; i <= doc.Pages.Count; i++) + { + // Process only even‑numbered pages + if (i % 2 == 0) + { + // Convert the entire page to grayscale (includes all images on the page) + doc.Pages[i].MakeGrayscale(); + } + } + + // Save the modified document (PDF format) + doc.Save(outputPath); + } + + Console.WriteLine($"Processed PDF saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/convert-pdf-pages-to-jpeg-with-default-font.cs b/working-with-images/convert-pdf-pages-to-jpeg-with-default-font.cs new file mode 100644 index 00000000..e24421b8 --- /dev/null +++ b/working-with-images/convert-pdf-pages-to-jpeg-with-default-font.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Devices; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + const string outputDir = "Images"; + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"File not found: {inputPdf}"); + return; + } + + Directory.CreateDirectory(outputDir); + + // Load the PDF document inside a using block for proper disposal + using (Document doc = new Document(inputPdf)) + { + // Iterate through all pages (1‑based indexing) + for (int pageNumber = 1; pageNumber <= doc.Pages.Count; pageNumber++) + { + // Create a JPEG device with desired resolution + JpegDevice jpegDevice = new JpegDevice(new Resolution(300)); + + // Set the default font name for missing fonts + jpegDevice.RenderingOptions.DefaultFontName = "Arial"; + + // Define output file name for the current page + string outputPath = Path.Combine(outputDir, $"Page_{pageNumber}.jpg"); + + // Convert the page to an image and save it + jpegDevice.Process(doc.Pages[pageNumber], outputPath); + } + } + + Console.WriteLine($"Images saved to '{outputDir}'."); + } +} \ No newline at end of file diff --git a/working-with-images/convert-pdf-to-multi-page-tiff-default-font.cs b/working-with-images/convert-pdf-to-multi-page-tiff-default-font.cs new file mode 100644 index 00000000..e97feac1 --- /dev/null +++ b/working-with-images/convert-pdf-to-multi-page-tiff-default-font.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Devices; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.tif"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document + using (Document pdfDoc = new Document(inputPath)) + { + // Define the resolution for the TIFF output (e.g., 300 DPI) + Resolution resolution = new Resolution(300); + + // Configure TIFF settings + TiffSettings tiffSettings = new TiffSettings + { + Compression = CompressionType.None, + Depth = ColorDepth.Default, + Shape = ShapeType.Landscape, + SkipBlankPages = false + }; + + // Create the TIFF device with the specified resolution and settings + TiffDevice tiffDevice = new TiffDevice(resolution, tiffSettings); + + // Apply a default font for rendering any missing fonts in the PDF + tiffDevice.RenderingOptions.DefaultFontName = "Arial"; + + // Convert the entire PDF to a multi‑page TIFF file + tiffDevice.Process(pdfDoc, outputPath); + } + + Console.WriteLine($"TIFF file saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/convert-pdf-to-png-with-default-font.cs b/working-with-images/convert-pdf-to-png-with-default-font.cs new file mode 100644 index 00000000..d783b483 --- /dev/null +++ b/working-with-images/convert-pdf-to-png-with-default-font.cs @@ -0,0 +1,44 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Devices; + +class PdfToImages +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; + const string outputFolder = "Images"; + + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"File not found: {inputPdfPath}"); + return; + } + + Directory.CreateDirectory(outputFolder); + + // Load the PDF document inside a using block for deterministic disposal + using (Document pdfDoc = new Document(inputPdfPath)) + { + // Define the resolution for the output images (e.g., 300 DPI) + Resolution resolution = new Resolution(300); + // Create a PNG device that will render pages to PNG images + PngDevice pngDevice = new PngDevice(resolution); + + // Configure rendering options – set the default font to substitute missing fonts + pngDevice.RenderingOptions = new RenderingOptions(); + pngDevice.RenderingOptions.DefaultFontName = "Times New Roman"; + + // Iterate over all pages (Aspose.Pdf uses 1‑based indexing) + for (int pageNumber = 1; pageNumber <= pdfDoc.Pages.Count; pageNumber++) + { + string outputPath = Path.Combine(outputFolder, $"Page_{pageNumber}.png"); + // Render the current page to an image file + pngDevice.Process(pdfDoc.Pages[pageNumber], outputPath); + } + } + + Console.WriteLine($"All pages have been saved to '{outputFolder}'."); + } +} diff --git a/working-with-images/correct-pdf-image-orientation.cs b/working-with-images/correct-pdf-image-orientation.cs new file mode 100644 index 00000000..022c02e5 --- /dev/null +++ b/working-with-images/correct-pdf-image-orientation.cs @@ -0,0 +1,93 @@ +using System; +using System.IO; +using System.Drawing; // Keep for RotateFlipType enum (fully qualified usage) +using Aspose.Pdf; + +class Program +{ + // Maps EXIF orientation values to System.Drawing.RotateFlipType + static System.Drawing.RotateFlipType GetRotateFlip(int orientation) + { + return orientation switch + { + 1 => System.Drawing.RotateFlipType.RotateNoneFlipNone, + 2 => System.Drawing.RotateFlipType.RotateNoneFlipX, + 3 => System.Drawing.RotateFlipType.Rotate180FlipNone, + 4 => System.Drawing.RotateFlipType.Rotate180FlipX, + 5 => System.Drawing.RotateFlipType.Rotate90FlipX, + 6 => System.Drawing.RotateFlipType.Rotate90FlipNone, + 7 => System.Drawing.RotateFlipType.Rotate270FlipX, + 8 => System.Drawing.RotateFlipType.Rotate270FlipNone, + _ => System.Drawing.RotateFlipType.RotateNoneFlipNone, + }; + } + + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_corrected.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF (lifecycle rule: use using for deterministic disposal) + using (Document doc = new Document(inputPath)) + { + // Iterate over all pages (Aspose.Pdf uses 1‑based indexing) + for (int p = 1; p <= doc.Pages.Count; p++) + { + Page page = doc.Pages[p]; + var images = page.Resources.Images; + + // Iterate over images using 1‑based index (XImageCollection follows the same rule) + for (int i = 1; i <= images.Count; i++) + { + XImage xImg = images[i]; + + // Extract the original image bytes + using (MemoryStream originalStream = new MemoryStream()) + { + xImg.Save(originalStream); + originalStream.Position = 0; + + // Load into System.Drawing.Image to read EXIF orientation + using (System.Drawing.Image sysImg = System.Drawing.Image.FromStream(originalStream)) + { + const int orientationTag = 0x0112; // EXIF orientation tag + if (Array.Exists(sysImg.PropertyIdList, id => id == orientationTag)) + { + var prop = sysImg.GetPropertyItem(orientationTag); + int orientation = BitConverter.ToUInt16(prop.Value, 0); + System.Drawing.RotateFlipType rotateFlip = GetRotateFlip(orientation); + + // Apply rotation only when needed + if (rotateFlip != System.Drawing.RotateFlipType.RotateNoneFlipNone) + { + sysImg.RotateFlip(rotateFlip); + + // Save the corrected image back to a stream (preserve original format) + using (MemoryStream correctedStream = new MemoryStream()) + { + sysImg.Save(correctedStream, sysImg.RawFormat); + correctedStream.Position = 0; + + // Replace the image in the PDF's image collection + images.Replace(i, correctedStream); + } + } + } + } + } + } + } + + // Save the modified PDF (lifecycle rule: Save inside using block) + doc.Save(outputPath); + } + + Console.WriteLine($"Processed PDF saved to '{outputPath}'."); + } +} diff --git a/working-with-images/delete-raster-image-from-pdf-page.cs b/working-with-images/delete-raster-image-from-pdf-page.cs new file mode 100644 index 00000000..d5ba291c --- /dev/null +++ b/working-with-images/delete-raster-image-from-pdf-page.cs @@ -0,0 +1,35 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document (using statement ensures proper disposal) + using (Document doc = new Document(inputPath)) + { + // Choose the page that contains the raster image to delete (1‑based indexing) + Page page = doc.Pages[1]; + + // Delete the first image from the page's resources. + // ImageDeleteAction.None removes the image reference from the page contents + // but keeps the image object in the document (file size unchanged). + page.Resources.Images.Delete(1, ImageDeleteAction.None); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Image removed and PDF saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/export-pdf-pages-to-bmp-300-dpi.cs b/working-with-images/export-pdf-pages-to-bmp-300-dpi.cs new file mode 100644 index 00000000..1ce1aba7 --- /dev/null +++ b/working-with-images/export-pdf-pages-to-bmp-300-dpi.cs @@ -0,0 +1,51 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Devices; + +class ExportPdfToBmp +{ + static void Main() + { + // Resolve a concrete folder where the PDF resides and BMPs will be written. + // Here we use a "Data" sub‑folder of the current working directory. + string dataDir = Path.Combine(Environment.CurrentDirectory, "Data"); + Directory.CreateDirectory(dataDir); // ensure the folder exists + + // Name of the source PDF – replace "sample.pdf" with your actual file name. + string pdfFileName = "sample.pdf"; + string pdfPath = Path.Combine(dataDir, pdfFileName); + + if (!File.Exists(pdfPath)) + { + Console.WriteLine($"PDF file not found: {pdfPath}"); + Console.WriteLine("Place the PDF in the above folder or change the file name/path in the code."); + return; + } + + // Load the PDF document (using ensures proper disposal) + using (Document pdfDocument = new Document(pdfPath)) + { + // Desired resolution – 300 DPI for high‑quality rasterisation + Resolution resolution = new Resolution(300); + + // Create a BMP device with the specified resolution. + // The BmpDevice constructor that accepts a Resolution uses that DPI for rendering. + BmpDevice bmpDevice = new BmpDevice(resolution); + + // Process each page (Aspose.Pdf uses 1‑based page indexing) + for (int pageNum = 1; pageNum <= pdfDocument.Pages.Count; pageNum++) + { + string outBmpPath = Path.Combine(dataDir, $"image{pageNum}_out.bmp"); + + // Write the BMP image to a file stream + using (FileStream bmpStream = new FileStream(outBmpPath, FileMode.Create)) + { + bmpDevice.Process(pdfDocument.Pages[pageNum], bmpStream); + } + + Console.WriteLine($"Page {pageNum} saved as BMP: {outBmpPath}"); + } + } + } +} diff --git a/working-with-images/extract-raster-images-from-pdf-preserve-format.cs b/working-with-images/extract-raster-images-from-pdf-preserve-format.cs new file mode 100644 index 00000000..428258a9 --- /dev/null +++ b/working-with-images/extract-raster-images-from-pdf-preserve-format.cs @@ -0,0 +1,102 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; + const string outputFolder = "ExtractedImages"; + + // Verify input file exists + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPdfPath}"); + return; + } + + // Ensure output directory exists + Directory.CreateDirectory(outputFolder); + + // Load the PDF document (lifecycle rule: use using for deterministic disposal) + using (Document pdfDoc = new Document(inputPdfPath)) + { + int imageIndex = 1; + + // Iterate over all pages (pages are 1‑based) + foreach (Page page in pdfDoc.Pages) + { + // Iterate over the image collection (rule: foreach XImage, not dictionary) + foreach (XImage img in page.Resources.Images) + { + // Save the image to a memory stream first so we can inspect the header + using (MemoryStream ms = new MemoryStream()) + { + img.Save(ms); // preserves original format + ms.Position = 0; + + // Determine the original image format from the header bytes + string extension = GetExtensionFromHeader(ms); + string outPath = Path.Combine(outputFolder, $"image_{imageIndex}{extension}"); + + // Write the stream to the final file + using (FileStream fs = new FileStream(outPath, FileMode.Create, FileAccess.Write)) + { + ms.CopyTo(fs); + } + + Console.WriteLine($"Saved image #{imageIndex} to '{outPath}'"); + imageIndex++; + } + } + } + } + } + + /// + /// Inspects the first bytes of a stream that contains an image and returns a suitable file extension. + /// Supports the most common raster formats. If the format cannot be identified, returns ".bin". + /// + private static string GetExtensionFromHeader(Stream imageStream) + { + // Read up to 12 bytes – enough for the signatures we check. + byte[] header = new byte[12]; + int read = imageStream.Read(header, 0, header.Length); + if (read < 4) + return ".bin"; + + // JPEG: FF D8 FF + if (header[0] == 0xFF && header[1] == 0xD8 && header[2] == 0xFF) + return ".jpg"; + + // PNG: 89 50 4E 47 0D 0A 1A 0A + if (header[0] == 0x89 && header[1] == 0x50 && header[2] == 0x4E && header[3] == 0x47) + return ".png"; + + // GIF: 47 49 46 38 (GIF8) + if (header[0] == 0x47 && header[1] == 0x49 && header[2] == 0x46 && header[3] == 0x38) + return ".gif"; + + // BMP: 42 4D + if (header[0] == 0x42 && header[1] == 0x4D) + return ".bmp"; + + // TIFF (little endian): 49 49 2A 00 ; big endian: 4D 4D 00 2A + if ((header[0] == 0x49 && header[1] == 0x49 && header[2] == 0x2A && header[3] == 0x00) || + (header[0] == 0x4D && header[1] == 0x4D && header[2] == 0x00 && header[3] == 0x2A)) + return ".tiff"; + + // JPEG2000 (JP2): 00 00 00 0C 6A 50 20 20 + if (header[0] == 0x00 && header[1] == 0x00 && header[2] == 0x00 && header[3] == 0x0C && + header[4] == 0x6A && header[5] == 0x50 && header[6] == 0x20 && header[7] == 0x20) + return ".jp2"; + + // JBIG2: 97 4A 42 32 ("\x97JB2") – rare, but we include a simple check + if (header[0] == 0x97 && header[1] == 0x4A && header[2] == 0x42 && header[3] == 0x32) + return ".jb2"; + + // Fallback for unknown formats + return ".bin"; + } +} diff --git a/working-with-images/extract-raster-images-from-pdf.cs b/working-with-images/extract-raster-images-from-pdf.cs new file mode 100644 index 00000000..a0861e38 --- /dev/null +++ b/working-with-images/extract-raster-images-from-pdf.cs @@ -0,0 +1,51 @@ +using System; +using System.IO; +using Aspose.Pdf; // Core Aspose.Pdf namespace +using System.Drawing.Imaging; // For ImageFormat (PNG) + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; // Source PDF file + const string outputDir = "ExtractedImages"; // Folder for PNG files + + // Verify input file exists + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"File not found: {inputPdf}"); + return; + } + + // Create output directory if it does not exist + Directory.CreateDirectory(outputDir); + + // Open the PDF document inside a using block for deterministic disposal + using (Document pdfDoc = new Document(inputPdf)) + { + int imageIndex = 1; // Counter for naming output files + + // Iterate over all pages (Aspose.Pdf uses 1‑based indexing) + foreach (Page page in pdfDoc.Pages) + { + // Iterate over each image resource on the current page + foreach (XImage xImg in page.Resources.Images) + { + // Build a unique file name for each extracted image + string outPath = Path.Combine(outputDir, $"image_{imageIndex}.png"); + + // Save the XImage to a PNG file + using (FileStream outStream = new FileStream(outPath, FileMode.Create)) + { + xImg.Save(outStream, ImageFormat.Png); + } + + Console.WriteLine($"Saved image {imageIndex} → {outPath}"); + imageIndex++; + } + } + } + + Console.WriteLine("Image extraction completed."); + } +} \ No newline at end of file diff --git a/working-with-images/extract-vector-graphics-to-svg.cs b/working-with-images/extract-vector-graphics-to-svg.cs new file mode 100644 index 00000000..19ab2b7f --- /dev/null +++ b/working-with-images/extract-vector-graphics-to-svg.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Vector; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputSvg = "page1_graphics.svg"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document (lifecycle rule: using block for disposal) + using (Document doc = new Document(inputPath)) + { + // Pages are 1‑based (global rule) + Page page = doc.Pages[1]; + + // Verify that the page actually contains vector graphics + if (!page.HasVectorGraphics()) + { + Console.WriteLine("The selected page does not contain vector graphics."); + return; + } + + // Create a GraphicsAbsorber and collect graphics from the page + GraphicsAbsorber absorber = new GraphicsAbsorber(); + absorber.Visit(page); + + // Create an SvgExtractor (default options) + SvgExtractor extractor = new SvgExtractor(); + + // Predicate that selects all graphic elements + Predicate allGraphics = g => true; + + // Extract the collected graphics to an SVG file + extractor.Extract(absorber, allGraphics, page, outputSvg); + + Console.WriteLine($"Vector graphics extracted to '{outputSvg}'."); + } + } +} \ No newline at end of file diff --git a/working-with-images/generate-pdf-page-thumbnails-png.cs b/working-with-images/generate-pdf-page-thumbnails-png.cs new file mode 100644 index 00000000..baf25179 --- /dev/null +++ b/working-with-images/generate-pdf-page-thumbnails-png.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Devices; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputDir = "Thumbnails"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Ensure the output directory exists + Directory.CreateDirectory(outputDir); + + // Load the PDF document inside a using block for deterministic disposal + using (Document pdfDoc = new Document(inputPath)) + { + // Create a ThumbnailDevice with the required dimensions (150x200 pixels) + Aspose.Pdf.Devices.ThumbnailDevice thumbDevice = new Aspose.Pdf.Devices.ThumbnailDevice(150, 200); + + // Pages are 1‑based indexed in Aspose.Pdf + for (int pageNum = 1; pageNum <= pdfDoc.Pages.Count; pageNum++) + { + string outPath = Path.Combine(outputDir, $"page_{pageNum}.png"); + + // Write each thumbnail to a separate PNG file + using (FileStream outStream = new FileStream(outPath, FileMode.Create)) + { + thumbDevice.Process(pdfDoc.Pages[pageNum], outStream); + } + } + } + + Console.WriteLine("Thumbnail images have been generated successfully."); + } +} \ No newline at end of file diff --git a/working-with-images/index.json b/working-with-images/index.json new file mode 100644 index 00000000..b3120292 --- /dev/null +++ b/working-with-images/index.json @@ -0,0 +1,1589 @@ +{ + "category": "working-with-images", + "nuget_version": "26.4.0", + "last_updated": "2026-05-08T09:57:25Z", + "examples": { + "add-png-logo-to-first-page": { + "title": "Add PNG Logo to First Page of PDF", + "filename": "add-png-logo-to-first-page.cs", + "description": "Shows how to load a PDF with Aspose.Pdf, place a PNG logo at specific coordinates on the first page, and save the modified document.", + "tags": [ + "pdf", + "image", + "logo", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Rectangle", + "Aspose.Pdf.Page.AddImage", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-background-image-to-pdf-pages": { + "title": "Add Background Image to PDF Pages with Opacity", + "filename": "add-background-image-to-pdf-pages.cs", + "description": "Shows how to place a background image on every page of a PDF and set its opacity to 30 % using Aspose.Pdf.", + "tags": [ + "pdf", + "background", + "image", + "opacity", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.BackgroundArtifact", + "Aspose.Pdf.Page.Artifacts", + "Aspose.Pdf.BackgroundArtifact.SetImage", + "Aspose.Pdf.BackgroundArtifact.Opacity", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-transparent-png-overlay-to-pdf-pages": { + "title": "Add Transparent PNG Overlay to PDF Pages", + "filename": "add-transparent-png-overlay-to-pdf-pages.cs", + "description": "Shows how to place a transparent PNG image over every page of a PDF as a foreground stamp using Aspose.Pdf.", + "tags": [ + "pdf", + "overlay", + "png", + "image-stamp", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImageStamp", + "Aspose.Pdf.Page.AddStamp", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-diagonal-image-watermark-to-pdf": { + "title": "Add Diagonal Image Watermark to PDF Pages", + "filename": "add-diagonal-image-watermark-to-pdf.cs", + "description": "Demonstrates how to load a PDF with Aspose.Pdf, add an image stamp as a watermark on each page, rotate it 45 degrees for diagonal placement, and save the result.", + "tags": [ + "pdf", + "watermark", + "image", + "rotation", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImageStamp", + "Aspose.Pdf.Page.AddStamp", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-company-logo-to-first-page": { + "title": "Add Company Logo to First Page of PDF", + "filename": "add-company-logo-to-first-page.cs", + "description": "Shows how to load a PDF with Aspose.Pdf, create an ImageStamp for a logo, center it on the first page, and save the modified document.", + "tags": [ + "pdf", + "image", + "logo", + "stamp", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImageStamp", + "Aspose.Pdf.Page.AddStamp", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-header-image-to-pdf-pages": { + "title": "Add Header Image to Each PDF Page", + "filename": "add-header-image-to-pdf-pages.cs", + "description": "Shows how to load a PDF with Aspose.Pdf, calculate a top‑margin rectangle for each page, insert a decorative header image without overlapping existing content, and save the modified document.", + "tags": [ + "pdf", + "header-image", + "aspose-pdf", + "image-overlay", + "page-manipulation" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.PageInfo", + "Aspose.Pdf.Rectangle", + "Aspose.Pdf.Page.AddImage", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-scalable-footer-image-to-pdf-pages": { + "title": "Add Scalable Footer Image to PDF Pages", + "filename": "add-scalable-footer-image-to-pdf-pages.cs", + "description": "Shows how to insert a decorative footer image on every page of a PDF and scale it proportionally to the page width using Aspose.Pdf.", + "tags": [ + "pdf", + "footer", + "image", + "scaling", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Image", + "Aspose.Pdf.Rectangle", + "Aspose.Pdf.Page.AddImage", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-background-pattern-image-to-pdf-pages": { + "title": "Add Background Pattern Image to PDF Pages", + "filename": "add-background-pattern-image-to-pdf-pages.cs", + "description": "Shows how to place a semi‑transparent pattern image as a background on every page of a PDF using Aspose.Pdf.", + "tags": [ + "background", + "image", + "pdf", + "opacity", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.BackgroundArtifact", + "Aspose.Pdf.BackgroundArtifact.SetImage", + "Aspose.Pdf.BackgroundArtifact.Opacity" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-background-pattern-to-pdf-pages": { + "title": "Add Background Pattern Image to PDF Pages", + "filename": "add-background-pattern-to-pdf-pages.cs", + "description": "Shows how to place a semi‑transparent background pattern image on every page of a PDF using Aspose.Pdf.", + "tags": [ + "background", + "image", + "pdf", + "opacity", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.BackgroundArtifact", + "Aspose.Pdf.BackgroundArtifact.SetImage", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-background-image-multiply-blend-mode": { + "title": "Add Background Image with Multiply Blend Mode to PDF", + "filename": "add-background-image-multiply-blend-mode.cs", + "description": "Shows how to load an existing PDF, attach a background image artifact to a page, optionally set its blend mode to Multiply for subtle shading, and save the modified document.", + "tags": [ + "pdf", + "background-image", + "blend-mode", + "Aspose.Pdf", + "C#" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Document.Save", + "Aspose.Pdf.BackgroundArtifact", + "Aspose.Pdf.BackgroundArtifact.SetImage", + "Aspose.Pdf.BackgroundArtifact.IsBackground", + "Aspose.Pdf.Page.Artifacts.Add", + "Aspose.Pdf.Drawing.BlendMode" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-background-texture-to-pdf-pages": { + "title": "Add Background Texture Image to PDF Pages", + "filename": "add-background-texture-to-pdf-pages.cs", + "description": "Shows how to place a subtle texture image as a background on every page of an existing PDF and simulate an overlay effect by adjusting opacity using Aspose.Pdf.", + "tags": [ + "pdf", + "background", + "image", + "texture", + "overlay" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Image", + "Aspose.Pdf.BackgroundArtifact", + "Aspose.Pdf.Page.BackgroundImage", + "Aspose.Pdf.Page.Artifacts.Add", + "Aspose.Pdf.BackgroundArtifact.SetImage", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-semi-transparent-overlay-image-to-pdf": { + "title": "Add Semi-Transparent Overlay Image to PDF", + "filename": "add-semi-transparent-overlay-image-to-pdf.cs", + "description": "Shows how to place a semi‑transparent PNG overlay on every page of a PDF using Aspose.Pdf's ImageStamp and control its opacity and alignment.", + "tags": [ + "overlay", + "image", + "pdf", + "opacity", + "stamp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.ImageStamp", + "Aspose.Pdf.Page.AddStamp", + "Aspose.Pdf.ImageStamp.Opacity", + "Aspose.Pdf.ImageStamp.Background", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-semi-transparent-overlay-to-pdf-pages": { + "title": "Add Semi-Transparent Color Overlay to PDF Pages", + "filename": "add-semi-transparent-overlay-to-pdf-pages.cs", + "description": "The example reads a theme configuration (hex color and opacity) from a JSON file and applies a semi‑transparent colored overlay to every page of an existing PDF using Aspose.Pdf.", + "tags": [ + "pdf", + "overlay", + "color", + "opacity", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Drawing.Graph", + "Aspose.Pdf.Drawing.Rectangle", + "Aspose.Pdf.Drawing.GraphInfo", + "Aspose.Pdf.Color.FromArgb", + "Aspose.Pdf.Color.FromRgb" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-semi-transparent-image-watermark-to-pdf-pages": { + "title": "Add Semi-Transparent Image Watermark to PDF Pages", + "filename": "add-semi-transparent-image-watermark-to-pdf-pages.cs", + "description": "Demonstrates loading a PDF with Aspose.Pdf, creating an ImageStamp, setting its opacity for a semi‑transparent watermark, applying it to each page, and saving the result.", + "tags": [ + "pdf", + "watermark", + "image", + "opacity", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.ImageStamp", + "Aspose.Pdf.Page.AddStamp", + "Aspose.Pdf.Document.Save", + "Aspose.Pdf.HorizontalAlignment", + "Aspose.Pdf.VerticalAlignment" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-jpeg-with-png-on-pdf-page": { + "title": "Replace JPEG with PNG on PDF Page Using Resources.Images", + "filename": "replace-jpeg-with-png-on-pdf-page.cs", + "description": "Demonstrates how to replace an existing image on a specific PDF page with a higher‑resolution PNG by using the page's Resources.Images collection.", + "tags": [ + "pdf", + "image-replacement", + "resources", + "png", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.XImageCollection", + "Aspose.Pdf.XImageCollection.Replace", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-jpeg-with-png-in-pdf": { + "title": "Replace JPEG Images with PNG in PDF", + "filename": "replace-jpeg-with-png-in-pdf.cs", + "description": "Shows how to load a PDF, iterate through its pages and image resources, and replace each JPEG image with a PNG while keeping the original positions.", + "tags": [ + "pdf", + "image-replacement", + "aspose.pdf", + "csharp", + "png" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImageCollection", + "Aspose.Pdf.ImageCollection.Replace", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-raster-images-with-vector-placeholders": { + "title": "Replace Raster Images with Vector Placeholders in PDF", + "filename": "replace-raster-images-with-vector-placeholders.cs", + "description": "Loads a PDF, removes raster images from each page, inserts a vector graphic placeholder (a light‑gray rectangle), optimizes resources, and saves the resulting vectorized PDF.", + "tags": [ + "pdf", + "vectorization", + "image-replacement", + "Aspose.Pdf", + "optimization" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Page.Resources.Images", + "Aspose.Pdf.Drawing.Graph", + "Aspose.Pdf.Drawing.Rectangle", + "Aspose.Pdf.GraphInfo", + "Aspose.Pdf.Document.OptimizeResources", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-images-odd-pages-placeholder": { + "title": "Replace Images on Odd PDF Pages with Placeholder", + "filename": "replace-images-odd-pages-placeholder.cs", + "description": "Shows how to iterate through a PDF, locate image placements on odd‑numbered pages, and replace each image with a placeholder graphic while keeping the original dimensions.", + "tags": [ + "pdf", + "image", + "placeholder", + "odd-pages", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImagePlacementAbsorber", + "Aspose.Pdf.ImagePlacement", + "Aspose.Pdf.ImagePlacement.Replace" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-images-odd-pages-qr-placeholder": { + "title": "Replace Images on Odd PDF Pages with QR‑Code Placeholder", + "filename": "replace-images-odd-pages-qr-placeholder.cs", + "description": "Demonstrates how to iterate through a PDF, identify odd‑numbered pages, and replace each image with a pre‑generated QR‑code placeholder while adding alternative text for accessibility.", + "tags": [ + "pdf", + "image-replacement", + "qr-code", + "accessibility", + "aspnet" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.XImageCollection", + "Aspose.Pdf.XImage", + "Aspose.Pdf.XImage.TrySetAlternativeText", + "Aspose.Pdf.XImageCollection.Replace", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "convert-even-pages-to-grayscale": { + "title": "Convert Even Pages to Grayscale in PDF", + "filename": "convert-even-pages-to-grayscale.cs", + "description": "Shows how to load a PDF with Aspose.Pdf, iterate through its pages, apply a grayscale conversion only to even-numbered pages, and save the modified document.", + "tags": [ + "pdf", + "grayscale", + "even-pages", + "image-manipulation", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Page.MakeGrayscale", + "Aspose.Pdf.Document.Save", + "Aspose.Pdf.PageCollection" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-images-last-page-with-banner": { + "title": "Replace Images on Last PDF Page with Full-Width Banner", + "filename": "replace-images-last-page-with-banner.cs", + "description": "Shows how to hide all existing images on the last page of a PDF and insert a single banner image that spans the entire page width using Aspose.Pdf.", + "tags": [ + "pdf", + "image", + "banner", + "Aspose.Pdf", + "last-page" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImagePlacementAbsorber", + "Aspose.Pdf.ImagePlacement.Hide", + "Aspose.Pdf.Page.AddImage", + "Aspose.Pdf.Rectangle" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "compress-large-images-in-pdf": { + "title": "Compress Large Images in PDF to Reduce File Size", + "filename": "compress-large-images-in-pdf.cs", + "description": "Shows how to replace images larger than 1 MB with compressed JPEG versions using Aspose.Pdf optimization options.", + "tags": [ + "pdf", + "image-compression", + "optimization", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Optimization.OptimizationOptions", + "Aspose.Pdf.Optimization.ImageCompressionOptions", + "Aspose.Pdf.Document.OptimizeResources", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-pdf-images-with-placeholder-and-hyperlink": { + "title": "Replace PDF Images with Placeholder and Hyperlink", + "filename": "replace-pdf-images-with-placeholder-and-hyperlink.cs", + "description": "The example loads a PDF, replaces each embedded image with a low‑resolution placeholder, and adds a clickable hyperlink annotation that points to the original image location.", + "tags": [ + "pdf", + "image-replacement", + "hyperlink", + "annotation", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Annotations.ImagePlacementAbsorber", + "Aspose.Pdf.ImagePlacement", + "Aspose.Pdf.XImage", + "Aspose.Pdf.Resources.Images.Replace", + "Aspose.Pdf.Annotations.LinkAnnotation", + "Aspose.Pdf.Annotations.GoToURIAction" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-pdf-images-with-grayscale": { + "title": "Replace PDF Images with Grayscale Versions", + "filename": "replace-pdf-images-with-grayscale.cs", + "description": "Demonstrates how to load a PDF with Aspose.Pdf, iterate through each page and image, convert each image to a grayscale bitmap, replace the original image with the grayscale JPEG, and save the modified document.", + "tags": [ + "pdf", + "image-processing", + "grayscale", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.XImageCollection", + "Aspose.Pdf.XImage", + "Aspose.Pdf.XImage.Grayscaled", + "Aspose.Pdf.XImageCollection.Replace", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "correct-pdf-image-orientation": { + "title": "Correct PDF Image Orientation Using EXIF Data", + "filename": "correct-pdf-image-orientation.cs", + "description": "Loads a PDF, reads EXIF orientation from each embedded image, rotates the image when needed, and replaces it in the PDF to ensure proper display.", + "tags": [ + "pdf", + "exif", + "image-rotation", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.XImageCollection", + "Aspose.Pdf.XImage", + "Aspose.Pdf.XImageCollection.Replace" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "compress-large-images-in-pdf__v2": { + "title": "Compress Large Images in PDF to Reduce File Size", + "filename": "compress-large-images-in-pdf__v2.cs", + "description": "Demonstrates loading a PDF, configuring image compression options to downsize images, optimizing the document, and saving the reduced‑size PDF using Aspose.Pdf.", + "tags": [ + "pdf", + "image-compression", + "optimization", + "csharp", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Optimization.OptimizationOptions", + "Aspose.Pdf.Optimization.ImageCompressionOptions", + "Aspose.Pdf.Document.OptimizeResources", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-images-on-pdf-page": { + "title": "Replace Images on a Specific PDF Page", + "filename": "replace-images-on-pdf-page.cs", + "description": "Shows how to replace selected images on a given PDF page by mapping image indices to new image files using Aspose.Pdf.", + "tags": [ + "pdf", + "image-replacement", + "aspose-pdf", + "csharp", + "page-manipulation" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.XImageCollection", + "Aspose.Pdf.XImageCollection.Replace", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-pdf-images-with-icc-embedded": { + "title": "Replace PDF Images with ICC‑Embedded Versions", + "filename": "replace-pdf-images-with-icc-embedded.cs", + "description": "Shows how to iterate through each page of a PDF and replace every image with a JPEG that already contains an embedded ICC profile using Aspose.Pdf.", + "tags": [ + "pdf", + "image-replacement", + "icc", + "color-management", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.XImageCollection", + "Aspose.Pdf.XImageCollection.Replace", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-images-with-logo": { + "title": "Replace Images on PDF Pages with a Logo", + "filename": "replace-images-with-logo.cs", + "description": "Shows how to use ImagePlacementAbsorber to locate all image placements on each PDF page and replace them with a specified logo image.", + "tags": [ + "image-replacement", + "pdf", + "logo", + "aspose-pdf", + "image-absorber" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImagePlacementAbsorber", + "Aspose.Pdf.ImagePlacement", + "Aspose.Pdf.ImagePlacement.Replace", + "Aspose.Pdf.Page.Accept" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-title-page-images-with-banner": { + "title": "Replace Title Page Images with High‑Resolution Banner", + "filename": "replace-title-page-images-with-banner.cs", + "description": "Shows how to replace every image on the first (title) page of a PDF with a high‑resolution banner using Aspose.Pdf.", + "tags": [ + "pdf", + "image-replacement", + "banner", + "aspose-pdf", + "title-page" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.XImageCollection", + "Aspose.Pdf.XImageCollection.Replace", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-index-page-images-with-banner": { + "title": "Replace Index Page Images with a Banner", + "filename": "replace-index-page-images-with-banner.cs", + "description": "Shows how to replace an existing image or add a new banner image on the first page of a PDF using Aspose.Pdf.", + "tags": [ + "pdf", + "image", + "banner", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImageCollection", + "Aspose.Pdf.ImageCollection.Replace", + "Aspose.Pdf.Page.AddImage", + "Aspose.Pdf.Rectangle", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-pdf-images-with-placeholder": { + "title": "Replace All PDF Images with Placeholder", + "filename": "replace-pdf-images-with-placeholder.cs", + "description": "Demonstrates how to iterate through each page of a PDF and replace every embedded image with a low‑resolution placeholder using Aspose.Pdf.", + "tags": [ + "pdf", + "image-replacement", + "placeholder", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.XImageCollection", + "Aspose.Pdf.XImageCollection.Replace", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "remove-all-images-from-pdf": { + "title": "Remove All Images from PDF", + "filename": "remove-all-images-from-pdf.cs", + "description": "Shows how to delete every image on each page of a PDF by clearing the Images collection with Aspose.Pdf and then saving the modified document.", + "tags": [ + "pdf", + "images", + "remove", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Page.Resources", + "Aspose.Pdf.XImageCollection.Delete", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "remove-low-resolution-images-from-pdf": { + "title": "Remove Low-Resolution Images from PDF", + "filename": "remove-low-resolution-images-from-pdf.cs", + "description": "Shows how to delete images in a PDF whose DPI is lower than 72 using ImagePlacementAbsorber and related APIs.", + "tags": [ + "pdf", + "image", + "dpi", + "aspose.pdf", + "optimization" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.ImagePlacementAbsorber", + "Aspose.Pdf.ImagePlacement", + "Aspose.Pdf.Page.Accept", + "Aspose.Pdf.ImagePlacement.Hide", + "Aspose.Pdf.Document.OptimizeResources", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "remove-low-resolution-images-from-pdf__v2": { + "title": "Remove Images Below 72 DPI from PDF", + "filename": "remove-low-resolution-images-from-pdf__v2.cs", + "description": "Loads a PDF, uses ImagePlacementAbsorber to locate all image placements, hides any image whose X or Y resolution is lower than 72 DPI, optimizes resources, and saves the modified document.", + "tags": [ + "pdf", + "image", + "dpi", + "optimize", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.ImagePlacementAbsorber", + "Aspose.Pdf.ImagePlacement", + "Aspose.Pdf.ImagePlacement.Hide", + "Aspose.Pdf.Document.OptimizeResources", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "remove-duplicate-images-from-pdf": { + "title": "Remove Duplicate Images from PDF", + "filename": "remove-duplicate-images-from-pdf.cs", + "description": "Shows how to load a PDF, merge identical image resources across all pages using OptimizeResources, and save the document without duplicate images.", + "tags": [ + "pdf", + "duplicate-images", + "optimize", + "resources", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Document.OptimizeResources", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "collect-image-resolution-metadata": { + "title": "Collect Image Resolution Metadata from PDF Pages", + "filename": "collect-image-resolution-metadata.cs", + "description": "Loads a PDF, iterates through each page, extracts image placements with ImagePlacementAbsorber, and reports each image's DPI and visible size.", + "tags": [ + "pdf", + "image", + "resolution", + "metadata", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImagePlacementAbsorber", + "Aspose.Pdf.ImagePlacement", + "Aspose.Pdf.Page.Accept" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "resize-images-half-size": { + "title": "Resize Images on PDF Pages to Half Size", + "filename": "resize-images-half-size.cs", + "description": "Loads a PDF, extracts each image on every page, scales it to 50% of its original dimensions, and replaces the image in the document before saving.", + "tags": [ + "pdf", + "image-resize", + "aspose-pdf", + "csharp", + "bitmap" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImagePlacementAbsorber", + "Aspose.Pdf.ImagePlacement", + "Aspose.Pdf.ImagePlacement.Replace" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "resize-images-in-pdf": { + "title": "Resize Images in PDF Using a Scaling Factor", + "filename": "resize-images-in-pdf.cs", + "description": "Demonstrates how to read a scaling factor from a configuration file and resize all images embedded in a PDF using Aspose.Pdf APIs.", + "tags": [ + "pdf", + "image-resize", + "aspose-pdf", + "csharp", + "configuration" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Facades.ImagePlacementAbsorber", + "Aspose.Pdf.ImagePlacement", + "Aspose.Pdf.ImagePlacement.Replace" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "resize-pdf-images-using-configurable-scale-factor": { + "title": "Resize PDF Images Using Configurable Scale Factor", + "filename": "resize-pdf-images-using-configurable-scale-factor.cs", + "description": "Reads an image scaling factor from appsettings.json, loads a PDF, scales each image on every page with Aspose.Pdf, and saves the result, creating a placeholder PDF if the source file is missing.", + "tags": [ + "pdf", + "image-scaling", + "configuration", + "aspose.pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Image", + "Aspose.Pdf.Document.Save", + "Aspose.Pdf.Page.Paragraphs", + "Aspose.Pdf.Image.ImageScale" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "resize-images-on-pdf-pages": { + "title": "Resize Images on PDF Pages Using JSON Configuration", + "filename": "resize-images-on-pdf-pages.cs", + "description": "Shows how to load a JSON file that defines target widths and heights per page, absorb existing images, remove them, and add them back with new dimensions in a PDF.", + "tags": [ + "pdf", + "image-resize", + "json-config", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImagePlacementAbsorber", + "Aspose.Pdf.ImagePlacement", + "Aspose.Pdf.Rectangle", + "Aspose.Pdf.Page.AddImage", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-raster-image-to-pdf-page": { + "title": "Add Raster Image to PDF Page", + "filename": "add-raster-image-to-pdf-page.cs", + "description": "Demonstrates how to insert a PNG/JPEG raster image onto a new PDF page using Aspose.Pdf's Image class and the Paragraphs collection.", + "tags": [ + "image", + "pdf", + "aspose.pdf", + "csharp", + "raster" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Image", + "Aspose.Pdf.PageCollection.Add", + "Aspose.Pdf.Page.Paragraphs.Add", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "insert-raster-image-into-pdf": { + "title": "Insert Raster Image into PDF at Absolute Coordinates", + "filename": "insert-raster-image-into-pdf.cs", + "description": "Demonstrates how to place a raster image onto a specific location of an existing PDF page using absolute coordinates with Aspose.Pdf.", + "tags": [ + "image", + "pdf", + "aspose", + "coordinates", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Rectangle", + "Aspose.Pdf.Page.AddImage", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "resize-embedded-raster-image": { + "title": "Resize Embedded Raster Image in PDF", + "filename": "resize-embedded-raster-image.cs", + "description": "Shows how to load a PDF, locate raster Image objects on each page, change their dimensions using FixWidth and FixHeight, and save the modified document.", + "tags": [ + "pdf", + "image", + "resize", + "raster", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Image", + "Aspose.Pdf.Rectangle", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-image-on-pdf-page": { + "title": "Replace Image on PDF Page", + "filename": "replace-image-on-pdf-page.cs", + "description": "Demonstrates how to replace an existing image on a specific PDF page with a new image loaded from a file stream using Aspose.Pdf.", + "tags": [ + "pdf", + "image", + "replace", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImageCollection", + "Aspose.Pdf.ImageCollection.Replace", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "delete-raster-image-from-pdf-page": { + "title": "Delete Raster Image from PDF Page", + "filename": "delete-raster-image-from-pdf-page.cs", + "description": "Demonstrates how to remove a specific raster image from a PDF page by deleting its reference from the page resources using Aspose.Pdf.", + "tags": [ + "pdf", + "image", + "delete", + "resources", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.ImageDeleteAction", + "Aspose.Pdf.Page.Resources.Images", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "extract-raster-images-from-pdf": { + "title": "Extract Raster Images from PDF to PNG", + "filename": "extract-raster-images-from-pdf.cs", + "description": "Shows how to iterate through PDF pages, locate raster image resources, and save each image as an individual PNG file using Aspose.Pdf.", + "tags": [ + "pdf", + "image-extraction", + "png", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Page.Resources", + "Aspose.Pdf.Page.Resources.Images", + "Aspose.Pdf.XImage.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "extract-raster-images-from-pdf-preserve-format": { + "title": "Extract Raster Images from PDF Preserving Original Format", + "filename": "extract-raster-images-from-pdf-preserve-format.cs", + "description": "The example loads a PDF with Aspose.Pdf, iterates through each page's image resources, determines each image's original format by inspecting its header bytes, and writes the images to disk while preserving their native format.", + "tags": [ + "pdf", + "image-extraction", + "aspose-pdf", + "raster-images", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.XImage", + "Aspose.Pdf.Page.Resources", + "Aspose.Pdf.XImage.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "batch-extract-images-from-pdfs": { + "title": "Batch Extract Images from PDFs", + "filename": "batch-extract-images-from-pdfs.cs", + "description": "Demonstrates how to iterate over PDF files in a folder, access each page's image resources with Aspose.Pdf, and save the extracted images to an output directory with proper file extensions.", + "tags": [ + "pdf", + "image-extraction", + "batch-processing", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.XImage", + "Aspose.Pdf.Page.Resources.Images", + "Aspose.Pdf.XImage.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-dicom-image-to-pdf-using-filestream": { + "title": "Add DICOM Image to PDF Using FileStream", + "filename": "add-dicom-image-to-pdf-using-filestream.cs", + "description": "Shows how to embed a DICOM medical image into a PDF page by reading the image from a FileStream and adding it to the document with Aspose.Pdf.", + "tags": [ + "dicom", + "pdf", + "image", + "aspose-pdf", + "filestream" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Image", + "Aspose.Pdf.PageCollection.Add", + "Aspose.Pdf.Page.Paragraphs.Add", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "insert-dicom-image-with-custom-size": { + "title": "Insert DICOM Image with Custom Size into PDF", + "filename": "insert-dicom-image-with-custom-size.cs", + "description": "Shows how to add a DICOM image to a PDF document and control its on‑page dimensions by setting custom width and height using Aspose.Pdf's tagged content API.", + "tags": [ + "dicom", + "image", + "pdf", + "tagged-content", + "custom-size" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.AutoTaggingSettings", + "Aspose.Pdf.Tagged.ITaggedContent", + "Aspose.Pdf.Tagged.StructureElement", + "Aspose.Pdf.Tagged.FigureElement" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "render-pdf-page-to-png-fallback-font": { + "title": "Render PDF Page to PNG with Fallback Font", + "filename": "render-pdf-page-to-png-fallback-font.cs", + "description": "Shows how to render a selected PDF page to a PNG image using Aspose.Pdf while specifying a fallback font through RenderingOptions.", + "tags": [ + "pdf", + "png", + "rendering", + "fallback-font", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Devices.PngDevice", + "Aspose.Pdf.Devices.Resolution", + "Aspose.Pdf.Devices.PngDevice.RenderingOptions", + "Aspose.Pdf.Devices.PngDevice.Process" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "render-pdf-pages-to-jpeg-default-font": { + "title": "Render PDF Pages to JPEG with Default Font", + "filename": "render-pdf-pages-to-jpeg-default-font.cs", + "description": "Shows how to convert every page of a PDF document to JPEG images using Aspose.Pdf while specifying a default font for missing glyphs.", + "tags": [ + "pdf", + "jpeg", + "rendering", + "default-font", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Devices.JpegDevice", + "Aspose.Pdf.Devices.Resolution", + "Aspose.Pdf.Devices.JpegDevice.RenderingOptions", + "Aspose.Pdf.Devices.JpegDevice.Process" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "generate-pdf-page-thumbnails-png": { + "title": "Generate PDF Page Thumbnails as PNG", + "filename": "generate-pdf-page-thumbnails-png.cs", + "description": "Creates a 150x200 pixel PNG thumbnail for each page of a PDF document using Aspose.Pdf's ThumbnailDevice.", + "tags": [ + "pdf", + "thumbnail", + "png", + "image", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Devices.ThumbnailDevice", + "Aspose.Pdf.Devices.ThumbnailDevice.Process", + "Aspose.Pdf.PageCollection", + "Aspose.Pdf.Page" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "convert-pdf-pages-to-jpeg-with-default-font": { + "title": "Convert PDF Pages to JPEG with Default Font Override", + "filename": "convert-pdf-pages-to-jpeg-with-default-font.cs", + "description": "Demonstrates loading a PDF, setting the default font to Arial for rendering, and converting each page to a high‑resolution JPEG image.", + "tags": [ + "pdf", + "image-conversion", + "default-font", + "jpeg", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Devices.JpegDevice", + "Aspose.Pdf.Devices.Resolution", + "Aspose.Pdf.Devices.JpegDevice.RenderingOptions", + "Aspose.Pdf.Devices.JpegDevice.Process" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "render-pdf-to-tiff-with-lzw-and-font-fallback": { + "title": "Render PDF to Multi‑Page TIFF with LZW Compression and Font Fallback", + "filename": "render-pdf-to-tiff-with-lzw-and-font-fallback.cs", + "description": "Loads a PDF, applies a default font fallback for missing characters, and renders the document to a multi‑page TIFF using 300 DPI resolution with LZW compression.", + "tags": [ + "pdf", + "tiff", + "font-fallback", + "lzw", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.PdfSaveOptions", + "Aspose.Pdf.Devices.TiffDevice", + "Aspose.Pdf.Devices.Resolution", + "Aspose.Pdf.Devices.TiffSettings", + "Aspose.Pdf.Devices.TiffDevice.Process" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "export-pdf-pages-to-bmp-300-dpi": { + "title": "Export PDF Pages as BMP Images (300 DPI)", + "filename": "export-pdf-pages-to-bmp-300-dpi.cs", + "description": "Loads a PDF document, sets a 300 DPI resolution, and renders each page to a separate BMP file using Aspose.Pdf's BmpDevice.", + "tags": [ + "pdf", + "bmp", + "image-conversion", + "300dpi", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Resolution", + "Aspose.Pdf.Devices.BmpDevice", + "Aspose.Pdf.Devices.BmpDevice.Process", + "Aspose.Pdf.Page" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "convert-pdf-to-multi-page-tiff-default-font": { + "title": "Convert PDF to Multi-Page TIFF with Default Font", + "filename": "convert-pdf-to-multi-page-tiff-default-font.cs", + "description": "Loads a PDF document and converts it into a multi‑page TIFF image using Aspose.Pdf, applying a specific resolution, TIFF settings, and a default font for rendering missing fonts.", + "tags": [ + "pdf", + "tiff", + "conversion", + "default-font", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Devices.Resolution", + "Aspose.Pdf.Devices.TiffSettings", + "Aspose.Pdf.Devices.TiffDevice", + "Aspose.Pdf.Devices.TiffDevice.Process" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "extract-vector-graphics-to-svg": { + "title": "Extract Vector Graphics from PDF Page to SVG", + "filename": "extract-vector-graphics-to-svg.cs", + "description": "Demonstrates how to load a PDF, detect vector graphics on a specific page, absorb those graphics, and export them as an SVG file using Aspose.Pdf.", + "tags": [ + "pdf", + "vector-graphics", + "svg", + "extraction", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page.HasVectorGraphics", + "Aspose.Pdf.Vector.GraphicsAbsorber", + "Aspose.Pdf.Vector.GraphicsAbsorber.Visit", + "Aspose.Pdf.Vector.SvgExtractor", + "Aspose.Pdf.Vector.SvgExtractor.Extract" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "move-vector-graphic-position": { + "title": "Move Extracted Vector Graphic to New Position in PDF", + "filename": "move-vector-graphic-position.cs", + "description": "Demonstrates how to extract a vector graphic from a PDF page, change its coordinates by updating its Matrix/Position, and re‑insert it back onto the same page using Aspose.Pdf.", + "tags": [ + "vector-graphics", + "pdf", + "position", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Vector.GraphicsAbsorber", + "Aspose.Pdf.Vector.GraphicElement", + "Aspose.Pdf.Vector.Point", + "Aspose.Pdf.Document.Save", + "GraphicsAbsorber.Visit", + "GraphicElement.Remove", + "GraphicElement.AddOnPage" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "transfer-vector-graphic-between-pdf-pages": { + "title": "Transfer Vector Graphic Between PDF Pages with Position Offset", + "filename": "transfer-vector-graphic-between-pdf-pages.cs", + "description": "Shows how to extract vector graphics from a source PDF page using GraphicsAbsorber, modify their position via the transformation matrix, and add them to another page.", + "tags": [ + "vector-graphics", + "graphicsabsorber", + "position-offset", + "pdf-pages", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Vector.GraphicsAbsorber", + "Aspose.Pdf.Vector.GraphicElement", + "Aspose.Pdf.Point", + "Aspose.Pdf.Vector.GraphicElement.AddOnPage", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "remove-vector-graphic-from-pdf-page": { + "title": "Remove Vector Graphic from PDF Page", + "filename": "remove-vector-graphic-from-pdf-page.cs", + "description": "Shows how to locate a vector graphic on a PDF page using GraphicsAbsorber and delete it from the page's content collection.", + "tags": [ + "pdf", + "vector-graphics", + "remove", + "graphics-absorber", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Vector.GraphicsAbsorber", + "Aspose.Pdf.Vector.GraphicElement.Remove", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "transfer-vector-graphic-between-pdf-pages__v2": { + "title": "Transfer Vector Graphic Between PDF Pages", + "filename": "transfer-vector-graphic-between-pdf-pages__v2.cs", + "description": "Shows how to extract vector graphics from a source PDF page using GraphicsAbsorber and insert each graphic onto a target PDF page.", + "tags": [ + "vector-graphics", + "pdf-manipulation", + "graphics-absorber", + "page-merge", + "document-processing" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Vector.GraphicsAbsorber", + "Aspose.Pdf.Vector.GraphicElement.AddOnPage", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "batch-extract-vector-graphics-from-pdfs": { + "title": "Batch Extract Vector Graphics from PDFs", + "filename": "batch-extract-vector-graphics-from-pdfs.cs", + "description": "Shows how to process multiple PDF files, detect pages containing vector graphics, and extract each page's vectors as SVG files into dedicated folders.", + "tags": [ + "pdf", + "vector-graphics", + "svg", + "batch-processing", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Vector.SvgExtractor", + "Aspose.Pdf.Page.HasVectorGraphics", + "Aspose.Pdf.Vector.SvgExtractor.Extract" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "set-image-alternative-text-pdf": { + "title": "Set Alternative Text for Images in PDF", + "filename": "set-image-alternative-text-pdf.cs", + "description": "Shows how to open a PDF, iterate through its pages and image resources, and assign alternative (alt) text to each image to improve accessibility for screen readers.", + "tags": [ + "pdf", + "accessibility", + "image", + "alt-text", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.XImage", + "Aspose.Pdf.XImage.TrySetAlternativeText", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "retrieve-alt-text-from-pdf-images": { + "title": "Retrieve Alternative Text from PDF Images", + "filename": "retrieve-alt-text-from-pdf-images.cs", + "description": "Shows how to load a PDF with Aspose.Pdf, iterate through its pages and images, extract each image's alternative (alt) text, and log the results for auditing.", + "tags": [ + "pdf", + "alternative-text", + "images", + "aspose", + "audit" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.XImage", + "Aspose.Pdf.XImage.GetAlternativeText", + "Aspose.Pdf.Page.Resources" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "add-image-with-alt-text-to-pdf": { + "title": "Add Image with Alternative Text to PDF", + "filename": "add-image-with-alt-text-to-pdf.cs", + "description": "Demonstrates inserting an image into a PDF and assigning alternative text for accessibility using Aspose.Pdf.", + "tags": [ + "pdf", + "image", + "alt-text", + "accessibility", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Image", + "Aspose.Pdf.XImage.TrySetAlternativeText", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "render-pdf-pages-to-png-300-dpi": { + "title": "Render PDF Pages to PNG at 300 DPI", + "filename": "render-pdf-pages-to-png-300-dpi.cs", + "description": "Demonstrates loading a PDF with Aspose.Pdf, setting a 300 DPI resolution, and converting each page to a PNG image.", + "tags": [ + "pdf", + "png", + "render", + "300dpi", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Devices.Resolution", + "Aspose.Pdf.Devices.PngDevice", + "Aspose.Pdf.Devices.PngDevice.Process", + "Aspose.Pdf.PageCollection", + "Aspose.Pdf.Page" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "convert-pdf-to-png-with-default-font": { + "title": "Convert PDF Pages to PNG Images with Default Font Substitution", + "filename": "convert-pdf-to-png-with-default-font.cs", + "description": "Loads a PDF document, sets the rendering default font to Times New Roman to handle missing fonts, and converts each page to a PNG image at 300 DPI.", + "tags": [ + "pdf", + "image-conversion", + "font-substitution", + "png", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Devices.Resolution", + "Aspose.Pdf.Devices.PngDevice", + "Aspose.Pdf.Devices.RenderingOptions", + "Aspose.Pdf.Devices.PngDevice.Process" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + }, + "replace-vector-with-raster-image": { + "title": "Replace Vector Graphic with Raster Image in PDF", + "filename": "replace-vector-with-raster-image.cs", + "description": "Shows how to overlay a raster image onto a PDF page to visually replace a vector graphic while keeping the original layout intact.", + "tags": [ + "pdf", + "vector-graphics", + "raster-image", + "overlay", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Page.HasVectorGraphics", + "Aspose.Pdf.Rectangle", + "Aspose.Pdf.Page.Resources.Images.Add", + "Aspose.Pdf.Page.AddImage", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:57:25Z", + "status": "verified" + } + } +} \ No newline at end of file diff --git a/working-with-images/insert-dicom-image-with-custom-size.cs b/working-with-images/insert-dicom-image-with-custom-size.cs new file mode 100644 index 00000000..64ceebdc --- /dev/null +++ b/working-with-images/insert-dicom-image-with-custom-size.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Tagged; +using Aspose.Pdf.LogicalStructure; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + const string outputPdf = "output.pdf"; + const string dicomPath = "image.dcm"; + + // Desired size of the image on the page (points; 1 point = 1/72 inch) + double customWidth = 200; // e.g., 200 points + double customHeight = 300; // e.g., 300 points + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + + if (!File.Exists(dicomPath)) + { + Console.Error.WriteLine($"DICOM image not found: {dicomPath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPdf)) + { + // Enable automatic tagging if the document is not already tagged + AutoTaggingSettings.Default.EnableAutoTagging = true; + + // Access tagged content (creates a tagged structure if none exists) + ITaggedContent tagged = doc.TaggedContent; + tagged.SetLanguage("en-US"); + tagged.SetTitle(Path.GetFileNameWithoutExtension(outputPdf)); + + // Root element of the structure tree + StructureElement root = tagged.RootElement; + + // Create a figure element (used for images) and set the DICOM image with custom dimensions + FigureElement figure = tagged.CreateFigureElement(); + figure.SetImage(dicomPath, customWidth, customHeight); + figure.AlternativeText = "DICOM image"; + + // Attach the figure to the document structure + root.AppendChild(figure); + + // Save the modified PDF + doc.Save(outputPdf); + } + + Console.WriteLine($"PDF with DICOM image saved to '{outputPdf}'."); + } +} diff --git a/working-with-images/insert-raster-image-into-pdf.cs b/working-with-images/insert-raster-image-into-pdf.cs new file mode 100644 index 00000000..ad3aff03 --- /dev/null +++ b/working-with-images/insert-raster-image-into-pdf.cs @@ -0,0 +1,84 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Aspose.Pdf; + +class InsertImageExample +{ + static void Main() + { + // Paths to the source PDF, the raster image, and the output PDF + const string pdfPath = "input.pdf"; + const string imgPath = "image.jpg"; + const string outPath = "output.pdf"; + + // Desired absolute coordinates (points) on the page + // lower‑left corner (x1, y1) and upper‑right corner (x2, y2) + const float llx = 100f; // lower‑left X + const float lly = 500f; // lower‑left Y + const float urx = 300f; // upper‑right X + const float ury = 700f; // upper‑right Y + + // Ensure the source files exist + if (!File.Exists(pdfPath)) + { + Console.Error.WriteLine($"PDF file not found: {pdfPath}"); + return; + } + if (!File.Exists(imgPath)) + { + Console.Error.WriteLine($"Image file not found: {imgPath}"); + return; + } + + // Open the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(pdfPath)) + { + // Aspose.Pdf uses 1‑based page indexing; here we modify the first page + Page page = doc.Pages[1]; + + // Define the rectangle where the image will be placed + // Fully qualified type name avoids ambiguity with System.Drawing.Rectangle + Aspose.Pdf.Rectangle imgRect = new Aspose.Pdf.Rectangle(llx, lly, urx, ury); + + // Open the image file as a stream and add it to the page + using (FileStream imgStream = File.OpenRead(imgPath)) + { + // This overload centers the image within the rectangle while preserving its aspect ratio + page.AddImage(imgStream, imgRect); + } + + // Save the modified document. + // On non‑Windows platforms Aspose.Pdf may require libgdiplus; guard against that. + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + doc.Save(outPath); + Console.WriteLine($"Image inserted and PDF saved to '{outPath}'."); + } + else + { + try + { + doc.Save(outPath); + Console.WriteLine($"Image inserted and PDF saved to '{outPath}'."); + } + catch (TypeInitializationException ex) when (ContainsDllNotFound(ex)) + { + Console.WriteLine("Saving failed: GDI+ (libgdiplus) is not available on this platform."); + } + } + } + } + + // Helper to detect a nested DllNotFoundException (libgdiplus missing) + private static bool ContainsDllNotFound(Exception ex) + { + while (ex != null) + { + if (ex is DllNotFoundException) + return true; + ex = ex.InnerException; + } + return false; + } +} \ No newline at end of file diff --git a/working-with-images/move-vector-graphic-position.cs b/working-with-images/move-vector-graphic-position.cs new file mode 100644 index 00000000..e377dfa4 --- /dev/null +++ b/working-with-images/move-vector-graphic-position.cs @@ -0,0 +1,79 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Vector; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_moved.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document inside a using block for proper disposal + using (Document doc = new Document(inputPath)) + { + // Aspose.Pdf uses 1‑based page indexing + Page page = doc.Pages[1]; + + // Check if the page contains any vector graphics + if (!page.HasVectorGraphics()) + { + Console.WriteLine("No vector graphics found on the first page."); + doc.Save(outputPath); + return; + } + + // ----------------------------------------------------------------- + // Extract vector graphics from the page. + // The correct absorber class is GraphicsAbsorber (not VectorGraphicsAbsorber). + // ----------------------------------------------------------------- + GraphicsAbsorber absorber = new GraphicsAbsorber(); + absorber.Visit(page); + + // Ensure at least one graphic element was extracted + if (absorber.Elements.Count == 0) + { + Console.WriteLine("Vector graphics extraction returned no elements."); + doc.Save(outputPath); + return; + } + + // Take the first extracted graphic element (e.g., a SubPath) + GraphicElement graphic = absorber.Elements[0]; + + // ----------------------------------------------------------------- + // Move the graphic to new coordinates. + // ----------------------------------------------------------------- + double deltaX = 100.0; // shift right + double deltaY = 50.0; // shift up + + // Current position of the graphic + Point currentPos = graphic.Position; + + // Compute new position + Point newPos = new Point(currentPos.X + deltaX, currentPos.Y + deltaY); + + // Apply the new position + graphic.Position = newPos; + + // ----------------------------------------------------------------- + // Remove the original graphic from the page and add the modified one. + // ----------------------------------------------------------------- + graphic.Remove(); // Remove original instance + graphic.AddOnPage(page); // Add the modified instance back + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Vector graphic moved and saved to '{outputPath}'."); + } +} diff --git a/working-with-images/remove-all-images-from-pdf.cs b/working-with-images/remove-all-images-from-pdf.cs new file mode 100644 index 00000000..de38dc0b --- /dev/null +++ b/working-with-images/remove-all-images-from-pdf.cs @@ -0,0 +1,35 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "images_removed.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Iterate over all pages (1‑based indexing) + foreach (Page page in doc.Pages) + { + // Delete all images from the current page + // XImageCollection provides a Delete() method that removes every image + page.Resources.Images.Delete(); + } + + // Save the modified document + doc.Save(outputPath); + } + + Console.WriteLine($"All images removed. Saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/remove-duplicate-images-from-pdf.cs b/working-with-images/remove-duplicate-images-from-pdf.cs new file mode 100644 index 00000000..e4e6c181 --- /dev/null +++ b/working-with-images/remove-duplicate-images-from-pdf.cs @@ -0,0 +1,31 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_no_duplicate_images.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPath}"); + return; + } + + // Load the PDF document (using the required load rule) + using (Document doc = new Document(inputPath)) + { + // OptimizeResources merges identical resources (including images) across all pages. + // This effectively removes duplicate images by comparing their raw data. + doc.OptimizeResources(); + + // Save the cleaned document (using the required save rule) + doc.Save(outputPath); + } + + Console.WriteLine($"Document saved without duplicate images: {outputPath}"); + } +} \ No newline at end of file diff --git a/working-with-images/remove-low-resolution-images-from-pdf.cs b/working-with-images/remove-low-resolution-images-from-pdf.cs new file mode 100644 index 00000000..60f6f08b --- /dev/null +++ b/working-with-images/remove-low-resolution-images-from-pdf.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Iterate through all pages (Aspose.Pdf uses 1‑based indexing) + for (int i = 1; i <= doc.Pages.Count; i++) + { + // Create a fresh absorber for the current page + ImagePlacementAbsorber absorber = new ImagePlacementAbsorber(); + + // Perform the search on the page + doc.Pages[i].Accept(absorber); + + // Examine each found image placement + foreach (ImagePlacement placement in absorber.ImagePlacements) + { + // Resolution is expressed in DPI (dots per inch) + double dpiX = placement.Resolution.X; + double dpiY = placement.Resolution.Y; + + // If either horizontal or vertical DPI is lower than 72, remove the image + if (dpiX < 72 || dpiY < 72) + { + placement.Hide(); // Deletes the image from the page + } + } + } + + // Optional: clean up unused resources after deletions + doc.OptimizeResources(); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Processed PDF saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/remove-low-resolution-images-from-pdf__v2.cs b/working-with-images/remove-low-resolution-images-from-pdf__v2.cs new file mode 100644 index 00000000..6cdc1322 --- /dev/null +++ b/working-with-images/remove-low-resolution-images-from-pdf__v2.cs @@ -0,0 +1,48 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Annotations; // ImagePlacementAbsorber and related types are here + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Create an absorber that will find all image placements in the document + ImagePlacementAbsorber absorber = new ImagePlacementAbsorber(); + + // Perform the search on the whole document + absorber.Visit(doc); + + // Iterate over each found image placement + foreach (ImagePlacement placement in absorber.ImagePlacements) + { + // Image resolution is given in DPI (dots per inch) for X and Y axes + // If either axis is lower than 72 DPI, hide (delete) the image from its page + if (placement.Resolution.X < 72 || placement.Resolution.Y < 72) + { + placement.Hide(); + } + } + + // Optional: clean up unused resources after deletions + doc.OptimizeResources(); + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Processed PDF saved to '{outputPath}'."); + } +} diff --git a/working-with-images/remove-vector-graphic-from-pdf-page.cs b/working-with-images/remove-vector-graphic-from-pdf-page.cs new file mode 100644 index 00000000..83453643 --- /dev/null +++ b/working-with-images/remove-vector-graphic-from-pdf-page.cs @@ -0,0 +1,44 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Vector; // GraphicsAbsorber and GraphicElement + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document (lifecycle rule: use using for disposal) + using (Document doc = new Document(inputPath)) + { + // Choose the page that contains the vector graphic (1‑based index) + Page page = doc.Pages[1]; + + // Absorb all vector graphics on the page + GraphicsAbsorber absorber = new GraphicsAbsorber(); + absorber.Visit(page); + + // Locate the specific vector graphic to delete. + // Here we simply delete the first one; replace this logic + // with any condition that identifies the target graphic. + if (absorber.Elements.Count > 0) + { + // Remove the graphic from the page + absorber.Elements[0].Remove(); + } + + // Save the modified PDF (lifecycle rule: use Save inside using) + doc.Save(outputPath); + } + + Console.WriteLine($"Modified PDF saved to '{outputPath}'."); + } +} diff --git a/working-with-images/render-pdf-page-to-png-fallback-font.cs b/working-with-images/render-pdf-page-to-png-fallback-font.cs new file mode 100644 index 00000000..835563ce --- /dev/null +++ b/working-with-images/render-pdf-page-to-png-fallback-font.cs @@ -0,0 +1,53 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Devices; + +class RenderPdfPageToPng +{ + static void Main() + { + // Input PDF file and the page to render (1‑based index) + const string inputPdfPath = "input.pdf"; + const int pageNumber = 1; // change as needed + const string outputPngPath = "page1.png"; + + // Verify the source file exists + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"File not found: {inputPdfPath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document pdfDocument = new Document(inputPdfPath)) + { + // Ensure the requested page exists + if (pageNumber < 1 || pageNumber > pdfDocument.Pages.Count) + { + Console.Error.WriteLine($"Page number {pageNumber} is out of range. Document has {pdfDocument.Pages.Count} pages."); + return; + } + + // Create a resolution (e.g., 300 DPI) for the PNG output + Resolution resolution = new Resolution(300); + + // Initialize the PNG device with the desired resolution + PngDevice pngDevice = new PngDevice(resolution); + + // Configure rendering options – specify a fallback font name + // This font will be used when the original PDF references a missing font. + pngDevice.RenderingOptions.DefaultFontName = "Arial"; + // Optional: enable font analysis to improve substitution + pngDevice.RenderingOptions.AnalyzeFonts = true; + + // Render the selected page to a PNG file + using (FileStream pngStream = new FileStream(outputPngPath, FileMode.Create)) + { + pngDevice.Process(pdfDocument.Pages[pageNumber], pngStream); + } + + Console.WriteLine($"Page {pageNumber} rendered to PNG: {outputPngPath}"); + } + } +} \ No newline at end of file diff --git a/working-with-images/render-pdf-pages-to-jpeg-default-font.cs b/working-with-images/render-pdf-pages-to-jpeg-default-font.cs new file mode 100644 index 00000000..ea51f4e5 --- /dev/null +++ b/working-with-images/render-pdf-pages-to-jpeg-default-font.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Devices; + +class Program +{ + static void Main() + { + // Input PDF file + const string inputPath = "input.pdf"; + // Directory where JPEG images will be saved + const string outputDir = "Images"; + // Font to use when a glyph is missing in the original PDF + const string defaultFont = "Arial"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Ensure the output directory exists + Directory.CreateDirectory(outputDir); + + // Load the PDF document (lifecycle rule: using for disposal) + using (Document pdfDocument = new Document(inputPath)) + { + // Create a resolution object (e.g., 300 DPI) + Resolution resolution = new Resolution(300); + + // Initialize JpegDevice with the specified resolution + JpegDevice jpegDevice = new JpegDevice(resolution); + + // Set the default font name for missing glyphs + jpegDevice.RenderingOptions.DefaultFontName = defaultFont; + + // Iterate over all pages (1‑based indexing) + for (int pageNumber = 1; pageNumber <= pdfDocument.Pages.Count; pageNumber++) + { + // Build the output file name for the current page + string outputPath = Path.Combine(outputDir, $"page_{pageNumber}.jpeg"); + + // Save the page as a JPEG image (lifecycle rule: using for stream) + using (FileStream imageStream = new FileStream(outputPath, FileMode.Create)) + { + jpegDevice.Process(pdfDocument.Pages[pageNumber], imageStream); + } + } + } + + Console.WriteLine("All pages have been rendered to JPEG images."); + } +} \ No newline at end of file diff --git a/working-with-images/render-pdf-pages-to-png-300-dpi.cs b/working-with-images/render-pdf-pages-to-png-300-dpi.cs new file mode 100644 index 00000000..96c3a16f --- /dev/null +++ b/working-with-images/render-pdf-pages-to-png-300-dpi.cs @@ -0,0 +1,51 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Devices; + +class Program +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; + const string outputFolder = "output_images"; + + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPdfPath}"); + return; + } + + // Ensure the output directory exists + Directory.CreateDirectory(outputFolder); + + // Load the PDF document (lifecycle rule: use using for disposal) + using (Document pdfDocument = new Document(inputPdfPath)) + { + // NOTE: The Document class no longer exposes a DefaultFontName property. + // If a default font is required for missing fonts, register the font with the + // FontRepository (e.g., pdfDocument.FontRepository.AddFont("Arial.ttf")). + // For the purpose of rendering pages to images, this step can be omitted. + + // Create a Resolution object for 300 DPI + Resolution resolution = new Resolution(300); + + // Initialize the PNG device with the specified resolution + PngDevice pngDevice = new PngDevice(resolution); + + // Iterate pages using 1‑based indexing (rule: page-indexing-one-based) + for (int pageNumber = 1; pageNumber <= pdfDocument.Pages.Count; pageNumber++) + { + string outputPath = Path.Combine(outputFolder, $"page_{pageNumber}.png"); + + // Save each page as a PNG image + using (FileStream pngStream = new FileStream(outputPath, FileMode.Create)) + { + pngDevice.Process(pdfDocument.Pages[pageNumber], pngStream); + } + } + } + + Console.WriteLine("All pages have been rendered to PNG at 300 DPI."); + } +} diff --git a/working-with-images/render-pdf-to-tiff-with-lzw-and-font-fallback.cs b/working-with-images/render-pdf-to-tiff-with-lzw-and-font-fallback.cs new file mode 100644 index 00000000..d09cbf2d --- /dev/null +++ b/working-with-images/render-pdf-to-tiff-with-lzw-and-font-fallback.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Devices; + +class Program +{ + static void Main() + { + // Input PDF path + const string inputPdfPath = "input.pdf"; + // Output TIFF path + const string outputTiffPath = "output.tif"; + + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPdfPath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document pdfDocument = new Document(inputPdfPath)) + { + // ------------------------------------------------------------ + // Set a default font fallback for characters whose fonts are missing. + // This uses PdfSaveOptions.DefaultFontName which tells Aspose.Pdf which + // font to substitute when the original font cannot be found. + // ------------------------------------------------------------ + PdfSaveOptions fontFallbackOptions = new PdfSaveOptions + { + DefaultFontName = "Arial" // Choose a font that is guaranteed to exist on the system + }; + + // Apply the fallback options by saving to a temporary stream (no file is created). + // This forces the document to resolve missing fonts using the specified fallback. + using (MemoryStream tempStream = new MemoryStream()) + { + pdfDocument.Save(tempStream, fontFallbackOptions); + // Reset the stream position so the document can continue to be used. + tempStream.Position = 0; + // Reload the document from the stream to ensure the fallback is applied. + // Dispose the original instance manually because we are inside a using block. + pdfDocument.Dispose(); + // Re‑assign a new Document instance from the stream. + Document reloaded = new Document(tempStream); + // Continue processing with the reloaded document. + // ------------------------------------------------------------ + // Configure TIFF rendering: 300 DPI resolution and LZW compression. + // ------------------------------------------------------------ + Resolution resolution = new Resolution(300); // 300 DPI + TiffSettings tiffSettings = new TiffSettings + { + Compression = CompressionType.LZW // LZW compression + }; + + // Create the TIFF device with the specified resolution and settings + TiffDevice tiffDevice = new TiffDevice(resolution, tiffSettings); + + // Render the entire PDF document to a single multi‑page TIFF file + tiffDevice.Process(reloaded, outputTiffPath); + } + } + + Console.WriteLine($"PDF has been rendered to TIFF with LZW compression: {outputTiffPath}"); + } +} diff --git a/working-with-images/replace-image-on-pdf-page.cs b/working-with-images/replace-image-on-pdf-page.cs new file mode 100644 index 00000000..8cd9e941 --- /dev/null +++ b/working-with-images/replace-image-on-pdf-page.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using Aspose.Pdf; // Core Aspose.Pdf namespace (no Facades) + +class Program +{ + static void Main() + { + // Paths – adjust as needed + const string inputPdfPath = "input.pdf"; + const string outputPdfPath = "output.pdf"; + const string newImagePath = "newImage.jpg"; + + // Page and image indexes are 1‑based in Aspose.Pdf + const int pageNumber = 1; // page where the image will be replaced + const int imageIndex = 1; // index of the image to replace on that page + + // Verify files exist + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + if (!File.Exists(newImagePath)) + { + Console.Error.WriteLine($"Replacement image not found: {newImagePath}"); + return; + } + + // Open the PDF document inside a using block for deterministic disposal + using (Document pdfDoc = new Document(inputPdfPath)) + { + // Ensure the requested page exists + if (pageNumber < 1 || pageNumber > pdfDoc.Pages.Count) + { + Console.Error.WriteLine($"Page {pageNumber} is out of range. Document has {pdfDoc.Pages.Count} pages."); + return; + } + + // Access the page's image resources collection + Page page = pdfDoc.Pages[pageNumber]; + var images = page.Resources.Images; + + // Validate the image index + if (imageIndex < 1 || imageIndex > images.Count) + { + Console.Error.WriteLine($"Image index {imageIndex} is out of range. Page contains {images.Count} images."); + return; + } + + // Open the new image as a stream and replace the existing image + using (FileStream imgStream = new FileStream(newImagePath, FileMode.Open, FileAccess.Read)) + { + // Replace the image at the specified index with the new image stream + images.Replace(imageIndex, imgStream); + } + + // Save the modified PDF + pdfDoc.Save(outputPdfPath); + } + + Console.WriteLine($"Image on page {pageNumber} (index {imageIndex}) replaced successfully."); + Console.WriteLine($"Modified PDF saved to '{outputPdfPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/replace-images-last-page-with-banner.cs b/working-with-images/replace-images-last-page-with-banner.cs new file mode 100644 index 00000000..3442a475 --- /dev/null +++ b/working-with-images/replace-images-last-page-with-banner.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class ReplaceImagesWithBanner +{ + static void Main() + { + const string inputPdf = "input.pdf"; // source PDF + const string bannerImg = "banner.jpg"; // banner image (JPEG) + const string outputPdf = "output.pdf"; // result PDF + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input file not found: {inputPdf}"); + return; + } + if (!File.Exists(bannerImg)) + { + Console.Error.WriteLine($"Banner image not found: {bannerImg}"); + return; + } + + // Load the PDF document (lifecycle rule) + using (Document doc = new Document(inputPdf)) + { + // Get the last page (Aspose.Pdf uses 1‑based indexing) + Page lastPage = doc.Pages[doc.Pages.Count]; + + // Hide all existing images on the last page + ImagePlacementAbsorber imgAbsorber = new ImagePlacementAbsorber(); + lastPage.Accept(imgAbsorber); + foreach (ImagePlacement placement in imgAbsorber.ImagePlacements) + { + placement.Hide(); // removes the image from the page + } + + // Add the banner image spanning the full page width + using (FileStream bannerStream = File.OpenRead(bannerImg)) + { + // Use the page rectangle (media box) as the target area + Aspose.Pdf.Rectangle pageRect = lastPage.Rect; + lastPage.AddImage(bannerStream, + new Aspose.Pdf.Rectangle(pageRect.LLX, pageRect.LLY, + pageRect.URX, pageRect.URY)); + } + + // Save the modified PDF (lifecycle rule) + doc.Save(outputPdf); + } + + Console.WriteLine($"Banner applied and saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/replace-images-odd-pages-placeholder.cs b/working-with-images/replace-images-odd-pages-placeholder.cs new file mode 100644 index 00000000..8493a90e --- /dev/null +++ b/working-with-images/replace-images-odd-pages-placeholder.cs @@ -0,0 +1,60 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const string placeholderPath = "placeholder.png"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPath}"); + return; + } + + if (!File.Exists(placeholderPath)) + { + Console.Error.WriteLine($"Placeholder image not found: {placeholderPath}"); + return; + } + + // Load placeholder image into memory once; it will be reused for each replacement. + byte[] placeholderBytes = File.ReadAllBytes(placeholderPath); + + // Load the PDF document (lifecycle: load → modify → save). + using (Document doc = new Document(inputPath)) + { + // Pages are 1‑based in Aspose.Pdf. + for (int pageNum = 1; pageNum <= doc.Pages.Count; pageNum++) + { + // Process only odd‑numbered pages. + if (pageNum % 2 == 0) continue; + + Page page = doc.Pages[pageNum]; + + // Find all image placements on the current page. + ImagePlacementAbsorber absorber = new ImagePlacementAbsorber(); + page.Accept(absorber); + + // Replace each image with the placeholder while keeping its rectangle. + foreach (ImagePlacement placement in absorber.ImagePlacements) + { + // Each Replace call consumes the stream, so provide a fresh one. + using (MemoryStream ms = new MemoryStream(placeholderBytes)) + { + placement.Replace(ms); + } + } + } + + // Save the modified PDF (lifecycle: save). + doc.Save(outputPath); + } + + Console.WriteLine($"Images on odd pages replaced. Output saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/replace-images-odd-pages-qr-placeholder.cs b/working-with-images/replace-images-odd-pages-qr-placeholder.cs new file mode 100644 index 00000000..cb40b93a --- /dev/null +++ b/working-with-images/replace-images-odd-pages-qr-placeholder.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; + const string outputPdfPath = "output.pdf"; + const string placeholderImg = "placeholder.png"; // QR‑code image prepared beforehand + + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPdfPath}"); + return; + } + + if (!File.Exists(placeholderImg)) + { + Console.Error.WriteLine($"Placeholder image not found: {placeholderImg}"); + return; + } + + // Load the PDF document + using (Document pdfDoc = new Document(inputPdfPath)) + { + // Iterate over all pages (1‑based indexing) + for (int pageIndex = 1; pageIndex <= pdfDoc.Pages.Count; pageIndex++) + { + // Process only odd‑numbered pages + if (pageIndex % 2 == 1) + { + Page page = pdfDoc.Pages[pageIndex]; + var imageCollection = page.Resources.Images; + + // XImageCollection uses 1‑based indexing as well + int imageCount = imageCollection.Count; + + for (int imgIdx = 1; imgIdx <= imageCount; imgIdx++) + { + // Retrieve the original image (optional – for alt text) + XImage originalImage = imageCollection[imgIdx]; + + // Set alternative text indicating replacement (helps accessibility) + originalImage.TrySetAlternativeText( + $"Image on page {pageIndex} replaced by QR‑code placeholder.", page); + + // Replace the image with the prepared QR‑code placeholder + using (FileStream placeholderStream = File.OpenRead(placeholderImg)) + { + // Replace expects a stream containing JPEG data; ensure the placeholder is JPEG + imageCollection.Replace(imgIdx, placeholderStream); + } + } + } + } + + // Save the modified PDF + pdfDoc.Save(outputPdfPath); + } + + Console.WriteLine($"PDF saved with placeholders: {outputPdfPath}"); + } +} \ No newline at end of file diff --git a/working-with-images/replace-images-on-pdf-page.cs b/working-with-images/replace-images-on-pdf-page.cs new file mode 100644 index 00000000..53a555aa --- /dev/null +++ b/working-with-images/replace-images-on-pdf-page.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const int targetPageNumber = 2; // page to modify (1‑based) + + // Map of image index (1‑based) on the page to the new image file path + var replacements = new Dictionary + { + { 1, "newImage1.jpg" }, + { 3, "newImage3.png" } + }; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPath}"); + return; + } + + foreach (var path in replacements.Values) + { + if (!File.Exists(path)) + { + Console.Error.WriteLine($"Replacement image not found: {path}"); + return; + } + } + + using (Document doc = new Document(inputPath)) + { + if (targetPageNumber < 1 || targetPageNumber > doc.Pages.Count) + { + Console.Error.WriteLine("Invalid page number."); + return; + } + + Page page = doc.Pages[targetPageNumber]; + var images = page.Resources.Images; // XImageCollection + + foreach (var kvp in replacements) + { + int index = kvp.Key; + string newImagePath = kvp.Value; + + if (index < 1 || index > images.Count) + { + Console.Error.WriteLine($"Image index {index} out of range on page {targetPageNumber}."); + continue; + } + + using (FileStream fs = File.OpenRead(newImagePath)) + { + images.Replace(index, fs); + } + } + + doc.Save(outputPath); + } + + Console.WriteLine($"Images replaced and saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/replace-images-with-logo.cs b/working-with-images/replace-images-with-logo.cs new file mode 100644 index 00000000..3b1590f6 --- /dev/null +++ b/working-with-images/replace-images-with-logo.cs @@ -0,0 +1,60 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class ReplaceImagesWithLogo +{ + static void Main() + { + // Paths for the source PDF, the logo image, and the output PDF. + const string inputPdfPath = "input.pdf"; + const string logoImagePath = "logo.png"; + const string outputPdfPath = "output.pdf"; + + // Validate that the required files exist. + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + if (!File.Exists(logoImagePath)) + { + Console.Error.WriteLine($"Logo image not found: {logoImagePath}"); + return; + } + + // Load the logo image once into memory; it will be used for all replacements. + byte[] logoBytes = File.ReadAllBytes(logoImagePath); + + // Open the PDF document inside a using block for deterministic disposal. + using (Document pdfDoc = new Document(inputPdfPath)) + { + // Iterate over all pages (Aspose.Pdf uses 1‑based indexing). + for (int pageIndex = 1; pageIndex <= pdfDoc.Pages.Count; pageIndex++) + { + Page page = pdfDoc.Pages[pageIndex]; + + // Create an absorber that finds image placements on the current page. + ImagePlacementAbsorber absorber = new ImagePlacementAbsorber(); + + // Perform the search on the page. + page.Accept(absorber); + + // Replace each found image with the logo. + foreach (ImagePlacement placement in absorber.ImagePlacements) + { + // Use a fresh MemoryStream for each replacement. + using (MemoryStream logoStream = new MemoryStream(logoBytes)) + { + placement.Replace(logoStream); + } + } + } + + // Save the modified document. + pdfDoc.Save(outputPdfPath); + } + + Console.WriteLine($"Images replaced with logo. Output saved to '{outputPdfPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/replace-index-page-images-with-banner.cs b/working-with-images/replace-index-page-images-with-banner.cs new file mode 100644 index 00000000..4ce3f89d --- /dev/null +++ b/working-with-images/replace-index-page-images-with-banner.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; // source PDF + const string outputPdf = "output.pdf"; // result PDF + const string bannerImg = "banner.jpg"; // new branding image + + if (!File.Exists(inputPdf) || !File.Exists(bannerImg)) + { + Console.Error.WriteLine("Input PDF or banner image not found."); + return; + } + + // Load the PDF (lifecycle: load) + using (Document doc = new Document(inputPdf)) + { + // Assume the index page is the first page (1‑based indexing) + Page indexPage = doc.Pages[1]; + + // If the page already contains images, replace the first one + if (indexPage.Resources.Images.Count > 0) + { + using (FileStream bannerStream = File.OpenRead(bannerImg)) + { + // XImageCollection.Replace uses 1‑based index + indexPage.Resources.Images.Replace(1, bannerStream); + } + } + else + { + // No existing images – add the banner as a new image + using (FileStream bannerStream = File.OpenRead(bannerImg)) + { + // Define where the banner should appear (full width at top) + double pageWidth = indexPage.PageInfo.Width; + double pageHeight = indexPage.PageInfo.Height; + Aspose.Pdf.Rectangle bannerRect = new Aspose.Pdf.Rectangle( + 0, // left + pageHeight - 100, // bottom (100 pts height banner) + pageWidth, // right + pageHeight); // top + + // Add the image to the page at the specified rectangle + indexPage.AddImage(bannerStream, bannerRect); + } + } + + // Save the modified PDF (lifecycle: save) + doc.Save(outputPdf); + } + + Console.WriteLine($"Branding updated and saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/replace-jpeg-with-png-in-pdf.cs b/working-with-images/replace-jpeg-with-png-in-pdf.cs new file mode 100644 index 00000000..9614fdd4 --- /dev/null +++ b/working-with-images/replace-jpeg-with-png-in-pdf.cs @@ -0,0 +1,54 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class ReplaceJpegWithPng +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; + const string outputPdfPath = "output.pdf"; + const string pngReplacementPath = "replacement.png"; + + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + + if (!File.Exists(pngReplacementPath)) + { + Console.Error.WriteLine($"Replacement PNG not found: {pngReplacementPath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPdfPath)) + { + // Iterate through all pages (1‑based indexing) + for (int pageNum = 1; pageNum <= doc.Pages.Count; pageNum++) + { + Page page = doc.Pages[pageNum]; + // XImageCollection does not provide an indexer for direct access, + // but it supports 1‑based indexing via the collection itself. + // Replace each image resource with the PNG stream. + int imageCount = page.Resources.Images.Count; + for (int imgIndex = 1; imgIndex <= imageCount; imgIndex++) + { + // Load the PNG data into a memory stream + using (FileStream pngStream = File.OpenRead(pngReplacementPath)) + { + // Replace the image at the current index. + // The Replace method expects a stream containing the new image data. + page.Resources.Images.Replace(imgIndex, pngStream); + } + } + } + + // Save the modified PDF + doc.Save(outputPdfPath); + } + + Console.WriteLine($"PDF saved with PNG replacements: {outputPdfPath}"); + } +} \ No newline at end of file diff --git a/working-with-images/replace-jpeg-with-png-on-pdf-page.cs b/working-with-images/replace-jpeg-with-png-on-pdf-page.cs new file mode 100644 index 00000000..5943f037 --- /dev/null +++ b/working-with-images/replace-jpeg-with-png-on-pdf-page.cs @@ -0,0 +1,60 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; // source PDF + const string outputPdf = "output.pdf"; // result PDF + const string newPng = "high_res.png"; // replacement image + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + if (!File.Exists(newPng)) + { + Console.Error.WriteLine($"Replacement image not found: {newPng}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPdf)) + { + // Ensure the document has at least three pages + if (doc.Pages.Count < 3) + { + Console.Error.WriteLine("The document has fewer than 3 pages."); + return; + } + + // Access page three + Page page = doc.Pages[3]; + + // Access the image collection of the page + XImageCollection images = page.Resources.Images; + + // If there is at least one image, replace the first one + if (images.Count > 0) + { + // Replace image at index 1 (1‑based) with the new PNG stream + using (FileStream pngStream = File.OpenRead(newPng)) + { + images.Replace(1, pngStream); + } + } + else + { + Console.WriteLine("No images found on page 3 to replace."); + } + + // Save the modified PDF + doc.Save(outputPdf); + } + + Console.WriteLine($"Image replaced and saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/replace-pdf-images-with-grayscale.cs b/working-with-images/replace-pdf-images-with-grayscale.cs new file mode 100644 index 00000000..5688c437 --- /dev/null +++ b/working-with-images/replace-pdf-images-with-grayscale.cs @@ -0,0 +1,58 @@ +using System; +using System.IO; +using System.Drawing; +using System.Drawing.Imaging; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_monochrome.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Iterate over all pages (1‑based indexing) + for (int p = 1; p <= doc.Pages.Count; p++) + { + Page page = doc.Pages[p]; + XImageCollection images = page.Resources.Images; + + // Iterate over images (also 1‑based) + for (int i = 1; i <= images.Count; i++) + { + XImage img = images[i]; + + // Obtain a grayscale version of the image (System.Drawing.Image) + System.Drawing.Image gray = img.Grayscaled; + + // Encode the grayscale image as JPEG into a memory stream + using (MemoryStream ms = new MemoryStream()) + { + gray.Save(ms, ImageFormat.Jpeg); + ms.Position = 0; // reset stream position for replacement + + // Replace the original image with the grayscale JPEG + images.Replace(i, ms); + } + + // Dispose the temporary grayscale bitmap + gray.Dispose(); + } + } + + // Save the modified PDF (no special SaveOptions needed for PDF output) + doc.Save(outputPath); + } + + Console.WriteLine($"Monochrome PDF saved to '{outputPath}'."); + } +} diff --git a/working-with-images/replace-pdf-images-with-icc-embedded.cs b/working-with-images/replace-pdf-images-with-icc-embedded.cs new file mode 100644 index 00000000..3693b148 --- /dev/null +++ b/working-with-images/replace-pdf-images-with-icc-embedded.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class ReplaceImagesWithICC +{ + static void Main() + { + // Paths – adjust as needed + const string inputPdfPath = "input.pdf"; + const string iccImagePath = "image_with_icc.jpg"; // JPEG that already contains an ICC profile + const string outputPdfPath = "output.pdf"; + + // Verify files exist + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + if (!File.Exists(iccImagePath)) + { + Console.Error.WriteLine($"ICC‑embedded image not found: {iccImagePath}"); + return; + } + + // Load the PDF document (lifecycle rule: use using for deterministic disposal) + using (Document doc = new Document(inputPdfPath)) + { + // Iterate over all pages (Aspose.Pdf uses 1‑based indexing) + for (int pageNum = 1; pageNum <= doc.Pages.Count; pageNum++) + { + Page page = doc.Pages[pageNum]; + + // Access the collection of images on the current page + XImageCollection images = page.Resources.Images; + + // Replace each image with the ICC‑profile‑embedded version + // XImageCollection indexing is also 1‑based + for (int imgIdx = 1; imgIdx <= images.Count; imgIdx++) + { + // Open a stream for the replacement image + using (FileStream replacementStream = File.OpenRead(iccImagePath)) + { + // Replace the image at the given index + images.Replace(imgIdx, replacementStream); + } + } + } + + // Save the modified PDF (lifecycle rule: use Document.Save) + doc.Save(outputPdfPath); + } + + Console.WriteLine($"Images replaced and saved to '{outputPdfPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/replace-pdf-images-with-placeholder-and-hyperlink.cs b/working-with-images/replace-pdf-images-with-placeholder-and-hyperlink.cs new file mode 100644 index 00000000..e57fcdd3 --- /dev/null +++ b/working-with-images/replace-pdf-images-with-placeholder-and-hyperlink.cs @@ -0,0 +1,85 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Annotations; + +class ReplaceImagesWithPlaceholder +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; + const string placeholderImgPath = "placeholder.png"; // low‑resolution placeholder image + const string outputPdfPath = "output.pdf"; + + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + if (!File.Exists(placeholderImgPath)) + { + Console.Error.WriteLine($"Placeholder image not found: {placeholderImgPath}"); + return; + } + + // Load the original PDF + using (Document doc = new Document(inputPdfPath)) + { + // Read placeholder image into a byte array once (will be reused for each replacement) + byte[] placeholderBytes = File.ReadAllBytes(placeholderImgPath); + + // Process each page + foreach (Page page in doc.Pages) + { + // Find all image placements on the page (to obtain their rectangles) + ImagePlacementAbsorber imgAbsorber = new ImagePlacementAbsorber(); + page.Accept(imgAbsorber); + + // Iterate over each placed image + foreach (ImagePlacement placement in imgAbsorber.ImagePlacements) + { + // ------------------------------------------------------------ + // 1. Replace the underlying XImage resource with the placeholder + // ------------------------------------------------------------ + XImage originalImg = placement.Image; + int imgIndex = 0; + foreach (XImage x in page.Resources.Images) + { + imgIndex++; + if (ReferenceEquals(x, originalImg)) + break; + } + + // Replace using a fresh MemoryStream for each call (required by the API) + using (MemoryStream placeholderStream = new MemoryStream(placeholderBytes)) + { + page.Resources.Images.Replace(imgIndex, placeholderStream); + } + + // ------------------------------------------------------------ + // 2. Add a hyperlink annotation that points to the original image URL + // ------------------------------------------------------------ + // Build a reference URL – in a real scenario this could be derived from metadata. + // Here we simply use a placeholder URL that includes the page and image index. + string originalImageUrl = $"https://example.com/original-image/page{page.Number}_img{imgIndex}.png"; + + // Create a link annotation covering the image rectangle + Aspose.Pdf.Rectangle linkRect = placement.Rectangle; // rectangle of the image on the page + LinkAnnotation link = new LinkAnnotation(page, linkRect); + link.Color = Aspose.Pdf.Color.Blue; // optional visual cue + link.Action = new GoToURIAction(originalImageUrl); + // Border must be created after the annotation instance exists + link.Border = new Border(link) { Width = 1 }; + + // Add the annotation to the page + page.Annotations.Add(link); + } + } + + // Save the modified PDF + doc.Save(outputPdfPath); + } + + Console.WriteLine($"PDF saved with placeholders and hyperlinks: {outputPdfPath}"); + } +} diff --git a/working-with-images/replace-pdf-images-with-placeholder.cs b/working-with-images/replace-pdf-images-with-placeholder.cs new file mode 100644 index 00000000..b98f0422 --- /dev/null +++ b/working-with-images/replace-pdf-images-with-placeholder.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const string placeholderImg = "placeholder.jpg"; // low‑resolution placeholder + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPath}"); + return; + } + + if (!File.Exists(placeholderImg)) + { + Console.Error.WriteLine($"Placeholder image not found: {placeholderImg}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPath)) + { + // Iterate over all pages (1‑based indexing) + for (int pageNum = 1; pageNum <= doc.Pages.Count; pageNum++) + { + Page page = doc.Pages[pageNum]; + var images = page.Resources.Images; // XImageCollection + + // Replace each image on the page with the placeholder + // XImageCollection uses 1‑based indexes as well + for (int imgIdx = 1; imgIdx <= images.Count; imgIdx++) + { + using (FileStream placeholderStream = File.OpenRead(placeholderImg)) + { + // Replace the image at the current index + images.Replace(imgIdx, placeholderStream); + } + } + } + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"All images replaced with placeholder. Saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/replace-raster-images-with-vector-placeholders.cs b/working-with-images/replace-raster-images-with-vector-placeholders.cs new file mode 100644 index 00000000..cade71ad --- /dev/null +++ b/working-with-images/replace-raster-images-with-vector-placeholders.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Drawing; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_vectorized.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + try + { + // Load the source PDF + using (Aspose.Pdf.Document doc = new Aspose.Pdf.Document(inputPath)) + { + // Process each page + foreach (Aspose.Pdf.Page page in doc.Pages) + { + // If the page contains raster images, replace them with vector placeholders + if (page.Resources.Images.Count > 0) + { + // Remove all raster images from the page resources + page.Resources.Images.Clear(); + + // Create a vector graphic container (Graph) sized to the page + Aspose.Pdf.Drawing.Graph graph = new Aspose.Pdf.Drawing.Graph(page.PageInfo.Width, page.PageInfo.Height); + + // Example vector placeholder: a light‑gray rectangle covering the page area + Aspose.Pdf.Drawing.Rectangle rect = new Aspose.Pdf.Drawing.Rectangle( + 0f, + 0f, + (float)page.PageInfo.Width, + (float)page.PageInfo.Height); + rect.GraphInfo = new Aspose.Pdf.GraphInfo + { + Color = Aspose.Pdf.Color.LightGray, + FillColor = Aspose.Pdf.Color.Transparent, + LineWidth = 0.5f + }; + + // Add the rectangle to the graph and the graph to the page + graph.Shapes.Add(rect); + page.Paragraphs.Add(graph); + } + } + + // Optimize resources after modifications (removes unused objects, merges duplicates, etc.) + doc.OptimizeResources(); + + // Save the resulting PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Vectorized PDF saved to '{outputPath}'."); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } +} diff --git a/working-with-images/replace-title-page-images-with-banner.cs b/working-with-images/replace-title-page-images-with-banner.cs new file mode 100644 index 00000000..3bc4e0eb --- /dev/null +++ b/working-with-images/replace-title-page-images-with-banner.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + const string outputPdf = "output.pdf"; + const string bannerPath = "banner.jpg"; + + if (!File.Exists(inputPdf) || !File.Exists(bannerPath)) + { + Console.Error.WriteLine("Input PDF or banner image not found."); + return; + } + + // Load the PDF document (lifecycle rule: use using for disposal) + using (Document doc = new Document(inputPdf)) + { + // Title page is assumed to be the first page (1‑based indexing) + Page titlePage = doc.Pages[1]; + + // Access the image collection of the page + XImageCollection images = titlePage.Resources.Images; + + // Replace every image on the title page with the high‑resolution banner + for (int i = 1; i <= images.Count; i++) + { + // Open the banner image as a stream (JPEG format expected) + using (FileStream bannerStream = File.OpenRead(bannerPath)) + { + // XImageCollection.Replace replaces the image at the given index + images.Replace(i, bannerStream); + } + } + + // Save the modified PDF (lifecycle rule: use Document.Save) + doc.Save(outputPdf); + } + + Console.WriteLine($"Banner replaced on title page. Saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/replace-vector-with-raster-image.cs b/working-with-images/replace-vector-with-raster-image.cs new file mode 100644 index 00000000..7ef13097 --- /dev/null +++ b/working-with-images/replace-vector-with-raster-image.cs @@ -0,0 +1,79 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Annotations; + +class ReplaceVectorWithRaster +{ + static void Main() + { + const string inputPdf = "input.pdf"; // source PDF containing a vector graphic + const string outputPdf = "output.pdf"; // result PDF + const string rasterImg = "replacement.png"; // raster image that will replace the vector graphic + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + if (!File.Exists(rasterImg)) + { + Console.Error.WriteLine($"Raster image not found: {rasterImg}"); + return; + } + + // Load the PDF document (lifecycle rule: use using for deterministic disposal) + using (Document doc = new Document(inputPdf)) + { + // Iterate through all pages (page indexing is 1‑based) + for (int pageNum = 1; pageNum <= doc.Pages.Count; pageNum++) + { + Page page = doc.Pages[pageNum]; + + // Check whether the page contains any vector graphics + if (!page.HasVectorGraphics()) + continue; // no vector graphics on this page + + // ----------------------------------------------------------------- + // NOTE: + // Aspose.Pdf does not provide a direct API to delete a specific + // vector graphic. The common approach is to overlay a raster image + // on top of the area occupied by the vector graphic. This preserves + // the original layout while visually replacing the vector content. + // ----------------------------------------------------------------- + + // Define the rectangle where the vector graphic resides. + // In a real scenario you would obtain these coordinates + // programmatically (e.g., via a GraphicsAbsorber). Here we use + // hard‑coded values for illustration. + // Rectangle constructor: (llx, lly, urx, ury) + Aspose.Pdf.Rectangle targetRect = new Aspose.Pdf.Rectangle(100, 400, 300, 600); + + // Add the raster image to the page resources and place it + // at the same rectangle as the vector graphic. + using (FileStream imgStream = File.OpenRead(rasterImg)) + { + // Add the image to the page resources (optional, but useful if the + // same image is reused later). The method returns the image name. + string imgName = page.Resources.Images.Add(imgStream); + + // Reset the stream position before the second use. + imgStream.Position = 0; + + // Place the image on the page at the target rectangle. + page.AddImage(imgStream, targetRect); + } + + // OPTIONAL: If you want to make the original vector graphic invisible, + // you can flatten the page's transparency which rasterizes the whole + // page content. This step is not required for a simple overlay. + // page.FlattenTransparency(); + } + + // Save the modified PDF (lifecycle rule: use doc.Save inside the using block) + doc.Save(outputPdf); + } + + Console.WriteLine($"Vector graphics have been visually replaced with raster image. Output saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/resize-embedded-raster-image.cs b/working-with-images/resize-embedded-raster-image.cs new file mode 100644 index 00000000..fc44db21 --- /dev/null +++ b/working-with-images/resize-embedded-raster-image.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using Aspose.Pdf; // Core PDF API +using Aspose.Pdf.Text; // For text-related types if needed + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; // source PDF containing the raster image + const string outputPath = "output_resized.pdf"; // PDF after resizing the image + const double newWidth = 200; // desired width in points (1 point = 1/72 inch) + const double newHeight = 150; // desired height in points + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Iterate through all pages (Aspose.Pdf uses 1‑based indexing) + for (int pageIndex = 1; pageIndex <= doc.Pages.Count; pageIndex++) + { + Page page = doc.Pages[pageIndex]; + + // Scan the page's paragraph collection for Image objects + for (int i = 1; i <= page.Paragraphs.Count; i++) + { + // The Paragraphs collection is also 1‑based + var paragraph = page.Paragraphs[i]; + + // Check if the paragraph is an Image (raster image) + if (paragraph is Aspose.Pdf.Image img) + { + // Resize the image by setting FixWidth and FixHeight. + // These properties override the original dimensions when the PDF is saved. + img.FixWidth = newWidth; + img.FixHeight = newHeight; + + // Optionally, you can also adjust the image's position by modifying its + // Rectangle (left, bottom, right, top) if needed. + // Example: keep the lower‑left corner unchanged + // double left = img.Rectangle.LLX; + // double bottom = img.Rectangle.LLY; + // img.Rectangle = new Aspose.Pdf.Rectangle(left, bottom, left + newWidth, bottom + newHeight); + } + } + } + + // Save the modified document. The Save method without SaveOptions always writes PDF. + doc.Save(outputPath); + } + + Console.WriteLine($"Resized PDF saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/resize-images-half-size.cs b/working-with-images/resize-images-half-size.cs new file mode 100644 index 00000000..649f2897 --- /dev/null +++ b/working-with-images/resize-images-half-size.cs @@ -0,0 +1,72 @@ +using System; +using System.Drawing; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Text; // required for ImagePlacementAbsorber + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output_resized.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPath)) + { + // Iterate through all pages (1‑based indexing) + for (int pageNum = 1; pageNum <= doc.Pages.Count; pageNum++) + { + Page page = doc.Pages[pageNum]; + + // Absorb image placements on the current page + ImagePlacementAbsorber absorber = new ImagePlacementAbsorber(); + page.Accept(absorber); + + // Process each image placement + foreach (ImagePlacement placement in absorber.ImagePlacements) + { + // Retrieve the original image as a stream + using (MemoryStream originalStream = new MemoryStream()) + { + placement.Image.Save(originalStream); + originalStream.Position = 0; + + // Load the image into a Bitmap for scaling + using (Bitmap originalBitmap = new Bitmap(originalStream)) + { + // Calculate half size (ensure at least 1 pixel) + int newWidth = Math.Max(1, originalBitmap.Width / 2); + int newHeight = Math.Max(1, originalBitmap.Height / 2); + + // Create a scaled bitmap + using (Bitmap scaledBitmap = new Bitmap(originalBitmap, new Size(newWidth, newHeight))) + { + // Save the scaled bitmap to a new memory stream (PNG format) + using (MemoryStream scaledStream = new MemoryStream()) + { + scaledBitmap.Save(scaledStream, System.Drawing.Imaging.ImageFormat.Png); + scaledStream.Position = 0; + + // Replace the image in the PDF with the scaled version + placement.Replace(scaledStream); + } + } + } + } + } + } + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"Resized PDF saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/working-with-images/resize-images-in-pdf.cs b/working-with-images/resize-images-in-pdf.cs new file mode 100644 index 00000000..b961dad0 --- /dev/null +++ b/working-with-images/resize-images-in-pdf.cs @@ -0,0 +1,83 @@ +using System; +using System.IO; +using System.Drawing; +using System.Drawing.Imaging; +using Aspose.Pdf; +using Aspose.Pdf.Text; +using Aspose.Pdf.Facades; + +// Read scaling factor from a simple configuration file (e.g., "config.txt" containing a double value) +double scalingFactor = 1.0; +const string configPath = "config.txt"; +if (File.Exists(configPath)) +{ + string text = File.ReadAllText(configPath).Trim(); + if (!double.TryParse(text, out scalingFactor) || scalingFactor <= 0) + { + Console.Error.WriteLine($"Invalid scaling factor in '{configPath}'. Using default 1.0."); + scalingFactor = 1.0; + } +} +else +{ + Console.Error.WriteLine($"Config file '{configPath}' not found. Using default scaling factor 1.0."); +} + +// Input and output PDF paths +const string inputPdf = "input.pdf"; +const string outputPdf = "output_resized.pdf"; + +if (!File.Exists(inputPdf)) +{ + Console.Error.WriteLine($"Input PDF '{inputPdf}' not found."); + return; +} + +// Load the PDF document +using (Document pdfDoc = new Document(inputPdf)) +{ + // Iterate through all pages + foreach (Page page in pdfDoc.Pages) + { + // Absorb image placements on the current page + ImagePlacementAbsorber absorber = new ImagePlacementAbsorber(); + page.Accept(absorber); + + // Process each image placement + foreach (ImagePlacement imgPlacement in absorber.ImagePlacements) + { + // Extract the original image into a memory stream + using (MemoryStream originalStream = new MemoryStream()) + { + imgPlacement.Image.Save(originalStream, ImageFormat.Png); + originalStream.Position = 0; + + // Load the image with System.Drawing (Windows‑only) + using (Bitmap originalBitmap = new Bitmap(originalStream)) + { + // Compute new dimensions based on the scaling factor + int newWidth = (int)(originalBitmap.Width * scalingFactor); + int newHeight = (int)(originalBitmap.Height * scalingFactor); + + // Create a scaled bitmap + using (Bitmap scaledBitmap = new Bitmap(originalBitmap, new Size(newWidth, newHeight))) + { + // Save the scaled bitmap back to a stream + using (MemoryStream scaledStream = new MemoryStream()) + { + scaledBitmap.Save(scaledStream, ImageFormat.Png); + scaledStream.Position = 0; + + // Replace the original image in the PDF with the scaled one + imgPlacement.Replace(scaledStream); + } + } + } + } + } + } + + // Save the modified PDF + pdfDoc.Save(outputPdf); + Console.WriteLine($"Images resized with factor {scalingFactor} and saved to '{outputPdf}'."); +} \ No newline at end of file diff --git a/working-with-images/resize-images-on-pdf-pages.cs b/working-with-images/resize-images-on-pdf-pages.cs new file mode 100644 index 00000000..2ddfe627 --- /dev/null +++ b/working-with-images/resize-images-on-pdf-pages.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Drawing.Imaging; // added for ImageFormat +using Aspose.Pdf; +using Aspose.Pdf.Devices; // still needed for other device‑related types (e.g., Resolution) + +// Configuration model matching the JSON file structure +public class PageResizeConfig +{ + public int Page { get; set; } + public double Width { get; set; } // target width in points + public double Height { get; set; } // target height in points +} + +class Program +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; + const string outputPdfPath = "output_resized.pdf"; + const string configPath = "resizeConfig.json"; + + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + + if (!File.Exists(configPath)) + { + Console.Error.WriteLine($"Configuration file not found: {configPath}"); + return; + } + + // Load configuration: map page number -> (width, height) + Dictionary pageSizeMap = LoadConfiguration(configPath); + + // Open the PDF document (lifecycle rule: wrap in using) + using (Document pdfDoc = new Document(inputPdfPath)) + { + // Iterate through all pages (1‑based indexing rule) + for (int pageIndex = 1; pageIndex <= pdfDoc.Pages.Count; pageIndex++) + { + if (!pageSizeMap.TryGetValue(pageIndex, out var targetSize)) + continue; // No resize instruction for this page + + Page page = pdfDoc.Pages[pageIndex]; + + // Absorb image placements on the current page + ImagePlacementAbsorber imgAbsorber = new ImagePlacementAbsorber(); + page.Accept(imgAbsorber); + + // Process each image found on the page + foreach (ImagePlacement imgPlacement in imgAbsorber.ImagePlacements) + { + // Save the original image to a memory stream + using (MemoryStream imgStream = new MemoryStream()) + { + // Use System.Drawing.Imaging.ImageFormat (correct enum) + imgPlacement.Image.Save(imgStream, ImageFormat.Png); + imgStream.Position = 0; // Reset stream for reading + + // Remove the original image from the page + imgPlacement.Hide(); + + // Determine new rectangle using the same lower‑left corner + double llx = imgPlacement.Rectangle.LLX; + double lly = imgPlacement.Rectangle.LLY; + double urx = llx + targetSize.width; + double ury = lly + targetSize.height; + Aspose.Pdf.Rectangle newRect = new Aspose.Pdf.Rectangle(llx, lly, urx, ury); + + // Add the resized image back to the page + page.AddImage(imgStream, newRect); + } + } + } + + // Save the modified PDF (save rule: use Document.Save) + pdfDoc.Save(outputPdfPath); + } + + Console.WriteLine($"Resized PDF saved to '{outputPdfPath}'."); + } + + // Helper to read the JSON configuration file + private static Dictionary LoadConfiguration(string configFilePath) + { + string json = File.ReadAllText(configFilePath); + PageResizeConfig[]? configs = JsonSerializer.Deserialize(json); + + var map = new Dictionary(); + if (configs != null) + { + foreach (var cfg in configs) + { + // Ensure positive dimensions before adding + if (cfg.Width > 0 && cfg.Height > 0) + { + map[cfg.Page] = (cfg.Width, cfg.Height); + } + } + } + return map; + } +} diff --git a/working-with-images/resize-pdf-images-using-configurable-scale-factor.cs b/working-with-images/resize-pdf-images-using-configurable-scale-factor.cs new file mode 100644 index 00000000..ef064625 --- /dev/null +++ b/working-with-images/resize-pdf-images-using-configurable-scale-factor.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using System.Text.Json; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + // Paths – adjust as needed + const string inputPdfPath = "input.pdf"; + const string outputPdfPath = "output.pdf"; + const string configPath = "appsettings.json"; + + // --------------------------------------------------------------------- + // 1. Read scaling factor from appsettings.json (default = 1.0 – no scaling) + // --------------------------------------------------------------------- + double scaleFactor = 1.0; + if (File.Exists(configPath)) + { + string json = File.ReadAllText(configPath); + using JsonDocument doc = JsonDocument.Parse(json); + if (doc.RootElement.TryGetProperty("ImageScaleFactor", out JsonElement factorElem) && + factorElem.TryGetDouble(out double factor)) + { + scaleFactor = factor; + } + } + + // --------------------------------------------------------------- + // 2. Ensure the input PDF exists – create a minimal placeholder if it does not. + // --------------------------------------------------------------- + if (!File.Exists(inputPdfPath)) + { + CreatePlaceholderPdf(inputPdfPath); + Console.WriteLine($"Placeholder PDF created at '{inputPdfPath}'."); + } + + // --------------------------------------------------------------- + // 3. Load the PDF, resize any images, and save the result. + // --------------------------------------------------------------- + using (Document pdfDoc = new Document(inputPdfPath)) + { + // Aspose.Pdf uses 1‑based page indexing. + for (int pageIndex = 1; pageIndex <= pdfDoc.Pages.Count; pageIndex++) + { + Page page = pdfDoc.Pages[pageIndex]; + + // Iterate over all paragraph elements on the page. + for (int i = 0; i < page.Paragraphs.Count; i++) + { + // Identify Image objects (Aspose.Pdf.Image). + if (page.Paragraphs[i] is Aspose.Pdf.Image img) + { + // Apply the scaling factor read from configuration. + img.ImageScale = scaleFactor; + } + } + } + + pdfDoc.Save(outputPdfPath); + } + + Console.WriteLine($"Images resized with factor {scaleFactor} and saved to '{outputPdfPath}'."); + } + + /// + /// Creates a very small PDF containing a single blank page. This method is used only + /// when the expected input file does not exist, preventing a FileNotFoundException at runtime. + /// + /// Full path where the placeholder PDF should be saved. + private static void CreatePlaceholderPdf(string path) + { + // Create a new empty document. + using (Document doc = new Document()) + { + // Add a single blank page (default size A4). + doc.Pages.Add(); + doc.Save(path); + } + } +} diff --git a/working-with-images/retrieve-alt-text-from-pdf-images.cs b/working-with-images/retrieve-alt-text-from-pdf-images.cs new file mode 100644 index 00000000..f7f5f7d1 --- /dev/null +++ b/working-with-images/retrieve-alt-text-from-pdf-images.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Aspose.Pdf; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Load the PDF document + using (Document doc = new Document(inputPath)) + { + // Iterate over all pages (1‑based indexing) + foreach (Page page in doc.Pages) + { + // Iterate over all images on the current page + foreach (XImage img in page.Resources.Images) + { + // Retrieve alternative text for the image on this page + List altTexts = img.GetAlternativeText(page); + + if (altTexts != null && altTexts.Count > 0) + { + foreach (string alt in altTexts) + { + Console.WriteLine($"Page {page.Number}, Image \"{img.Name}\": Alt Text = \"{alt}\""); + } + } + else + { + Console.WriteLine($"Page {page.Number}, Image \"{img.Name}\": No alternative text."); + } + } + } + } + } +} \ No newline at end of file diff --git a/working-with-images/set-image-alternative-text-pdf.cs b/working-with-images/set-image-alternative-text-pdf.cs new file mode 100644 index 00000000..1dbde439 --- /dev/null +++ b/working-with-images/set-image-alternative-text-pdf.cs @@ -0,0 +1,49 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Tagged; // for ITaggedContent if needed (not required here) + +class SetImageAltText +{ + static void Main() + { + // Input PDF containing images + const string inputPath = "input.pdf"; + // Output PDF with alternative text set + const string outputPath = "output_with_alt.pdf"; + // Desired alternative text for all images + const string altText = "Descriptive text for the image"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // Open the PDF document inside a using block for deterministic disposal + using (Document doc = new Document(inputPath)) + { + // Iterate over all pages (Aspose.Pdf uses 1‑based indexing) + for (int i = 1; i <= doc.Pages.Count; i++) + { + Page page = doc.Pages[i]; + + // Iterate over each XImage resource on the page + foreach (XImage img in page.Resources.Images) + { + // Try to set the alternative text; returns true if successful + bool success = img.TrySetAlternativeText(altText, page); + if (!success) + { + Console.WriteLine($"Could not set alt text for an image on page {i}."); + } + } + } + + // Save the modified PDF + doc.Save(outputPath); + } + + Console.WriteLine($"PDF saved with alternative text: {outputPath}"); + } +} \ No newline at end of file diff --git a/working-with-images/transfer-vector-graphic-between-pdf-pages.cs b/working-with-images/transfer-vector-graphic-between-pdf-pages.cs new file mode 100644 index 00000000..f36def4e --- /dev/null +++ b/working-with-images/transfer-vector-graphic-between-pdf-pages.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Vector; + +class Program +{ + static void Main() + { + const string inputPdf = "source.pdf"; // PDF containing the vector graphic + const string outputPdf = "result.pdf"; // PDF with the graphic transferred + const int sourcePageNumber = 1; // page to extract from (1‑based) + const int destPageNumber = 2; // page to place the graphic onto (1‑based) + + // Offsets to move the graphic on the destination page + const float offsetX = 100f; // move right by 100 points + const float offsetY = 50f; // move up by 50 points + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"File not found: {inputPdf}"); + return; + } + + // Load the PDF document (core API) + using (Document doc = new Document(inputPdf)) + { + // Ensure the destination page exists; add a blank page if necessary + while (doc.Pages.Count < Math.Max(sourcePageNumber, destPageNumber)) + doc.Pages.Add(); + + Page sourcePage = doc.Pages[sourcePageNumber]; + Page destPage = doc.Pages[destPageNumber]; + + // Extract vector graphics from the source page + using (GraphicsAbsorber absorber = new GraphicsAbsorber()) + { + // NOTE: GraphicsAbsorber uses Visit(page) – not Page.Accept + absorber.Visit(sourcePage); + + // If no vector graphics were found, exit + if (absorber.Elements.Count == 0) + { + Console.WriteLine("No vector graphics found on the source page."); + } + else + { + // Transfer each extracted graphic to the destination page + foreach (GraphicElement element in absorber.Elements) + { + // Adjust position by setting the Position property. + // This updates the internal transformation matrix. + // Position expects an Aspose.Pdf.Point (X, Y) in user space. + element.Position = new Aspose.Pdf.Point( + element.Position.X + offsetX, + element.Position.Y + offsetY); + + // Add the element to the destination page. + // AddOnPage works for a single element; for many elements AddGraphics is faster. + element.AddOnPage(destPage); + } + } + } + + // Save the modified document + doc.Save(outputPdf); + } + + Console.WriteLine($"Vector graphic transferred and saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/working-with-images/transfer-vector-graphic-between-pdf-pages__v2.cs b/working-with-images/transfer-vector-graphic-between-pdf-pages__v2.cs new file mode 100644 index 00000000..a4a720ea --- /dev/null +++ b/working-with-images/transfer-vector-graphic-between-pdf-pages__v2.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Vector; + +class Program +{ + static void Main() + { + const string sourcePdfPath = "source.pdf"; + const string targetPdfPath = "target.pdf"; + const string outputPdfPath = "result.pdf"; + + // Verify input files exist + if (!File.Exists(sourcePdfPath) || !File.Exists(targetPdfPath)) + { + Console.Error.WriteLine("Source or target PDF file not found."); + return; + } + + // Load source and target documents inside using blocks for deterministic disposal + using (Document sourceDoc = new Document(sourcePdfPath)) + using (Document targetDoc = new Document(targetPdfPath)) + { + // Choose pages to work with (first page in this example) + Page sourcePage = sourceDoc.Pages[1]; + Page targetPage = targetDoc.Pages[1]; + + // Extract vector graphics from the source page using the correct absorber class + GraphicsAbsorber absorber = new GraphicsAbsorber(); + absorber.Visit(sourcePage); + + // Add each extracted graphic element to the target page. + // GraphicsAbsorber.Elements returns a collection of GraphicElement objects. + foreach (var graphic in absorber.Elements) + { + graphic.AddOnPage(targetPage); + } + + // Save the modified target document + targetDoc.Save(outputPdfPath); + } + + Console.WriteLine($"Vector graphic transferred and saved to '{outputPdfPath}'."); + } +}