diff --git a/facades-texts-and-images/add-background-image-to-all-pdf-pages.cs b/facades-texts-and-images/add-background-image-to-all-pdf-pages.cs new file mode 100644 index 00000000..ebac144c --- /dev/null +++ b/facades-texts-and-images/add-background-image-to-all-pdf-pages.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Facades; + +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 source PDF to obtain page dimensions and count + using (Document doc = new Document(inputPdf)) + { + int pageCount = doc.Pages.Count; + + // Retrieve page size from the first page (assuming all pages have the same size) + // MediaBox properties are double, cast to float for PdfFileMend.AddImage + float pageWidth = (float)doc.Pages[1].MediaBox.URX; + float pageHeight = (float)doc.Pages[1].MediaBox.URY; + + // Initialize the facade for modifying the PDF + PdfFileMend mender = new PdfFileMend(); + mender.BindPdf(inputPdf); // bind the source PDF + + // Add the background image to each page + for (int i = 1; i <= pageCount; i++) + { + // AddImage(string imagePath, int pageNum, float llx, float lly, float urx, float ury) + // Coordinates cover the whole page (0,0) to (pageWidth,pageHeight) + mender.AddImage(imagePath, i, 0f, 0f, pageWidth, pageHeight); + } + + // Save the modified PDF + mender.Save(outputPdf); + mender.Close(); + } + + Console.WriteLine($"Background image added to all pages. Output saved to '{outputPdf}'."); + } +} diff --git a/facades-texts-and-images/add-header-image-to-pdf.cs b/facades-texts-and-images/add-header-image-to-pdf.cs new file mode 100644 index 00000000..2d6e0cc4 --- /dev/null +++ b/facades-texts-and-images/add-header-image-to-pdf.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main(string[] args) + { + // Expect first argument to be the header image file, + // remaining arguments are PDF files to process. + if (args.Length < 2) + { + Console.Error.WriteLine("Usage: [ ...]"); + return; + } + + string headerImagePath = args[0]; + if (!File.Exists(headerImagePath)) + { + Console.Error.WriteLine($"Header image not found: {headerImagePath}"); + return; + } + + // Process each PDF file. + for (int i = 1; i < args.Length; i++) + { + string inputPdf = args[i]; + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"PDF not found: {inputPdf}"); + continue; + } + + // Create output file name by inserting "_header" before the extension. + string outputPdf = Path.Combine( + Path.GetDirectoryName(inputPdf) ?? string.Empty, + Path.GetFileNameWithoutExtension(inputPdf) + "_header.pdf"); + + try + { + // Use PdfFileStamp facade to add a header image. + using (PdfFileStamp fileStamp = new PdfFileStamp()) + { + // Bind the source PDF. + fileStamp.BindPdf(inputPdf); + + // Add the header image. Top margin is set to 50 units. + fileStamp.AddHeader(headerImagePath, 50f); + + // Save the modified PDF to the output path. + fileStamp.Save(outputPdf); + + // Close the facade (releases resources). + fileStamp.Close(); + } + + Console.WriteLine($"Processed '{inputPdf}' -> '{outputPdf}'"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error processing '{inputPdf}': {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/facades-texts-and-images/add-image-and-text-to-pdf-with-logging.cs b/facades-texts-and-images/add-image-and-text-to-pdf-with-logging.cs new file mode 100644 index 00000000..d573d110 --- /dev/null +++ b/facades-texts-and-images/add-image-and-text-to-pdf-with-logging.cs @@ -0,0 +1,72 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Facades; + +class Program +{ + // Simple logger that writes timestamp, operation, file name and page number + static void Log(string operation, string fileName, int pageNumber) + { + Console.WriteLine($"{DateTime.Now:O} | {operation} | File: {fileName} | Page: {pageNumber}"); + } + + static void Main() + { + const string inputPdf = "input.pdf"; + const string outputPdf = "output.pdf"; + + // Example resources + const string imagePath = "logo.png"; + const string text = "Sample Text"; + + // Validate input files + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + if (!File.Exists(imagePath)) + { + Console.Error.WriteLine($"Image file not found: {imagePath}"); + return; + } + + // Initialize the PdfFileMend facade + PdfFileMend mend = new PdfFileMend(); + mend.BindPdf(inputPdf); + + // ---------- AddImage ---------- + int imagePage = 1; + float imgLlx = 50f, imgLly = 50f, imgUrx = 200f, imgUry = 200f; + bool imageAdded = mend.AddImage(imagePath, imagePage, imgLlx, imgLly, imgUrx, imgUry); + if (imageAdded) + { + Log("AddImage", imagePath, imagePage); + } + + // ---------- AddText ---------- + int textPage = 2; + // FormattedText constructor requires System.Drawing.Color + FormattedText formatted = new FormattedText( + text, + System.Drawing.Color.Black, + "Helvetica", + EncodingType.Winansi, + false, + 12); + + float txtLlx = 100f, txtLly = 500f, txtUrx = 300f, txtUry = 520f; + bool textAdded = mend.AddText(formatted, textPage, txtLlx, txtLly, txtUrx, txtUry); + if (textAdded) + { + Log("AddText", "FormattedText", textPage); + } + + // Save the modified PDF and release resources + mend.Save(outputPdf); + mend.Close(); + + Console.WriteLine($"Processing completed. Output saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/add-image-stamp-to-pdf-with-cleanup.cs b/facades-texts-and-images/add-image-stamp-to-pdf-with-cleanup.cs new file mode 100644 index 00000000..c3bd6772 --- /dev/null +++ b/facades-texts-and-images/add-image-stamp-to-pdf-with-cleanup.cs @@ -0,0 +1,47 @@ +using System; +using System.IO; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const string imagePath = "stamp.png"; + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPath}"); + return; + } + + PdfFileMend mend = null; + try + { + // Initialize the facade and bind the source PDF + mend = new PdfFileMend(); + mend.BindPdf(inputPath); + + // Example operation: add an image to the first page if the image file exists + if (File.Exists(imagePath)) + { + // AddImage(string imageFile, int pageNumber, float x, float y, float width, float height) + mend.AddImage(imagePath, 1, 100f, 500f, 200f, 100f); + } + + // Persist the modifications + mend.Save(outputPath); + } + finally + { + // Guarantee that resources are released even if an exception occurs + if (mend != null) + { + mend.Close(); + } + } + + Console.WriteLine($"PDF processing completed. Output saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/add-image-to-all-pdf-pages-dynamic-positioning.cs b/facades-texts-and-images/add-image-to-all-pdf-pages-dynamic-positioning.cs new file mode 100644 index 00000000..8fe57f54 --- /dev/null +++ b/facades-texts-and-images/add-image-to-all-pdf-pages-dynamic-positioning.cs @@ -0,0 +1,76 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; + const string imagePath = "logo.png"; + const string outputPdfPath = "output.pdf"; + + 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 PDF document inside a using block (document-disposal-with-using rule) + using (Document pdfDoc = new Document(inputPdfPath)) + { + // Initialize PdfFileMend facade with the loaded document + PdfFileMend mender = new PdfFileMend(pdfDoc); + + // Open the image once as a stream (will be reused for each page) + using (FileStream imgStream = File.OpenRead(imagePath)) + { + // Iterate through all pages (Aspose.Pdf uses 1‑based indexing) + for (int pageNum = 1; pageNum <= pdfDoc.Pages.Count; pageNum++) + { + Page page = pdfDoc.Pages[pageNum]; + + // Retrieve page dimensions (width and height in points) + double pageWidth = page.Rect.Width; + double pageHeight = page.Rect.Height; + + // Define margins as a percentage of page size (e.g., 5%) + double marginX = pageWidth * 0.05; + double marginY = pageHeight * 0.05; + + // Desired image size (e.g., 20% of page width, keep aspect ratio) + double imgWidth = pageWidth * 0.20; + double imgHeight = imgWidth; // square placeholder; adjust as needed + + // Calculate lower‑left and upper‑right coordinates for bottom‑right placement + double lowerLeftX = pageWidth - marginX - imgWidth; + double lowerLeftY = marginY; + double upperRightX = pageWidth - marginX; + double upperRightY = marginY + imgHeight; + + // Add the image to the current page at the calculated rectangle + // AddImage(Stream, int, float, float, float, float) overload + mender.AddImage(imgStream, pageNum, + (float)lowerLeftX, (float)lowerLeftY, + (float)upperRightX, (float)upperRightY); + + // Reset the stream position for the next iteration + imgStream.Position = 0; + } + } + + // Save the modified document (PdfFileMend inherits SaveableFacade) + mender.Save(outputPdfPath); + mender.Close(); // optional, releases resources held by the facade + } + + Console.WriteLine($"Image placed on all pages and saved to '{outputPdfPath}'."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/add-image-to-pdf-page.cs b/facades-texts-and-images/add-image-to-pdf-page.cs new file mode 100644 index 00000000..ba76e5ab --- /dev/null +++ b/facades-texts-and-images/add-image-to-pdf-page.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using Aspose.Pdf.Facades; + +public static class PdfHelper +{ + /// + /// Adds an image to a specific page of a PDF file at the given rectangle coordinates. + /// + /// Path to the source PDF. + /// Path where the modified PDF will be saved. + /// Path to the image file to be added. + /// 1‑based page number where the image will be placed. + /// Lower‑left X coordinate of the image rectangle. + /// Lower‑left Y coordinate of the image rectangle. + /// Upper‑right X coordinate of the image rectangle. + /// Upper‑right Y coordinate of the image rectangle. + public static void AddImageToPage( + string inputPdfPath, + string outputPdfPath, + string imagePath, + int pageNumber, + float lowerLeftX, + float lowerLeftY, + float upperRightX, + float upperRightY) + { + // Validate arguments (optional but helpful) + if (string.IsNullOrWhiteSpace(inputPdfPath)) + throw new ArgumentException("Input PDF path is required.", nameof(inputPdfPath)); + if (string.IsNullOrWhiteSpace(outputPdfPath)) + throw new ArgumentException("Output PDF path is required.", nameof(outputPdfPath)); + if (string.IsNullOrWhiteSpace(imagePath)) + throw new ArgumentException("Image path is required.", nameof(imagePath)); + if (!File.Exists(inputPdfPath)) + throw new FileNotFoundException("Input PDF not found.", inputPdfPath); + if (!File.Exists(imagePath)) + throw new FileNotFoundException("Image file not found.", imagePath); + if (pageNumber < 1) + throw new ArgumentOutOfRangeException(nameof(pageNumber), "Page number must be 1 or greater."); + + // Use the parameter‑less constructor and bind the source PDF. + using (PdfFileMend mend = new PdfFileMend()) + { + mend.BindPdf(inputPdfPath); + mend.AddImage(imagePath, pageNumber, lowerLeftX, lowerLeftY, upperRightX, upperRightY); + mend.Save(outputPdfPath); + } + } +} + +// Minimal entry point so the project builds as an executable. +public class Program +{ + public static void Main(string[] args) + { + // The helper can be invoked from other code or unit tests. + } +} \ No newline at end of file diff --git a/facades-texts-and-images/add-image-to-pdf-with-format-validation.cs b/facades-texts-and-images/add-image-to-pdf-with-format-validation.cs new file mode 100644 index 00000000..24fa711f --- /dev/null +++ b/facades-texts-and-images/add-image-to-pdf-with-format-validation.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + const string outputPdf = "output.pdf"; + const string imagePath = "image.png"; + + // Verify source PDF exists + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + + // Verify image file exists + if (!File.Exists(imagePath)) + { + Console.Error.WriteLine($"Image file not found: {imagePath}"); + return; + } + + // Validate image format (JPG, PNG, GIF, BMP, TIFF) + if (!IsSupportedImage(imagePath)) + { + Console.Error.WriteLine("Unsupported image format. Allowed extensions: .jpg, .jpeg, .png, .gif, .bmp, .tif, .tiff"); + return; + } + + // Use PdfFileMend (Facade) to add the image + using (PdfFileMend mender = new PdfFileMend()) + { + // Bind the existing PDF document + mender.BindPdf(inputPdf); + + // Add the image to page 1 at the specified rectangle + using (FileStream imgStream = File.OpenRead(imagePath)) + { + // lower-left (10,10), upper-right (200,200) – adjust as needed + mender.AddImage(imgStream, 1, 10f, 10f, 200f, 200f); + } + + // Save the modified PDF + mender.Save(outputPdf); + mender.Close(); + } + + Console.WriteLine($"Image added successfully. Output saved to '{outputPdf}'."); + } + + // Helper to check allowed image extensions + static bool IsSupportedImage(string filePath) + { + string ext = Path.GetExtension(filePath).ToLowerInvariant(); + return ext == ".jpg" || ext == ".jpeg" || + ext == ".png" || + ext == ".gif" || + ext == ".bmp" || + ext == ".tif" || ext == ".tiff"; + } +} \ No newline at end of file diff --git a/facades-texts-and-images/add-images-to-pdf-with-error-handling.cs b/facades-texts-and-images/add-images-to-pdf-with-error-handling.cs new file mode 100644 index 00000000..9b65124f --- /dev/null +++ b/facades-texts-and-images/add-images-to-pdf-with-error-handling.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main() + { + // Input PDF, output PDF and images to add + const string inputPdf = "input.pdf"; + const string outputPdf = "output.pdf"; + string[] images = { "image1.jpg", "image2.png", "image3.bmp" }; + + // Verify input PDF exists + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + + // Verify each image exists before processing + foreach (string imgPath in images) + { + if (!File.Exists(imgPath)) + { + Console.Error.WriteLine($"Image file not found and will be skipped: {imgPath}"); + } + } + + // Initialize PdfFileMend facade with input and output files + // PdfFileMend implements IDisposable via SaveableFacade, so we use using + using (PdfFileMend mender = new PdfFileMend(inputPdf, outputPdf)) + { + // Add each image to page 1; coordinates are example values + foreach (string imgPath in images) + { + if (!File.Exists(imgPath)) + { + // Skip missing files + continue; + } + + try + { + // AddImage(string imagePath, int pageNum, float llx, float lly, float urx, float ury) + bool success = mender.AddImage(imgPath, 1, 10, 10, 200, 200); + if (!success) + { + Console.Error.WriteLine($"AddImage returned false for: {imgPath}"); + } + } + catch (Exception ex) + { + // Log the problematic image file path and exception details + Console.Error.WriteLine($"Failed to add image '{imgPath}': {ex.Message}"); + } + } + + // Close the facade to finalize the output PDF + mender.Close(); + } + + Console.WriteLine($"Processing completed. Output saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/add-multi-line-text-custom-spacing-page-3.cs b/facades-texts-and-images/add-multi-line-text-custom-spacing-page-3.cs new file mode 100644 index 00000000..793c788a --- /dev/null +++ b/facades-texts-and-images/add-multi-line-text-custom-spacing-page-3.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Facades; +using Aspose.Pdf.Text; + +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 using the Facades API + using (PdfFileMend mend = new PdfFileMend()) + { + mend.BindPdf(inputPath); // initialize facade with source PDF + Document doc = mend.Document; // underlying Document object + + // Verify that page 3 exists (Aspose.Pdf uses 1‑based indexing) + if (doc.Pages.Count < 3) + { + Console.Error.WriteLine("The document has fewer than 3 pages."); + return; + } + + Page page = doc.Pages[3]; // target page + + // Create a multi‑line text paragraph + TextParagraph paragraph = new TextParagraph(); + + // Position the paragraph at the left margin (adjust coordinates as needed) + paragraph.Rectangle = new Aspose.Pdf.Rectangle(0, 500, 150, 700); + + // Optional: enable word‑wrap + paragraph.FormattingOptions.WrapMode = TextFormattingOptions.WordWrapMode.ByWords; + + // Append lines with custom additional line spacing (in points) + paragraph.AppendLine("First line of text", 5f); + paragraph.AppendLine("Second line with extra spacing", 10f); + paragraph.AppendLine("Third line", 5f); + + // Add the paragraph to the page + TextBuilder builder = new TextBuilder(page); + builder.AppendParagraph(paragraph); + + // Save the modified PDF via the facade + mend.Save(outputPath); + } + + Console.WriteLine($"Modified PDF saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/add-png-image-to-pdf-page.cs b/facades-texts-and-images/add-png-image-to-pdf-page.cs new file mode 100644 index 00000000..41614b5b --- /dev/null +++ b/facades-texts-and-images/add-png-image-to-pdf-page.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + const string outputPdf = "output.pdf"; + const string imagePath = "image.png"; + + // Verify that source files exist + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + if (!File.Exists(imagePath)) + { + Console.Error.WriteLine($"Image file not found: {imagePath}"); + return; + } + + // Use a using‑statement to ensure the facade is disposed correctly. + // This also eliminates the need for an explicit Close() call and avoids + // potential file‑handle conflicts that can trigger the package assets + // cache I/O warning when builds run in parallel. + using (PdfFileMend mend = new PdfFileMend()) + { + // Bind the PDF document to be edited + mend.BindPdf(inputPdf); + + // Add the PNG image to page 2. + // Coordinates are: lower‑left X, lower‑left Y, upper‑right X, upper‑right Y. + // Adjust these values as needed for the desired placement. + mend.AddImage(imagePath, 2, 100f, 200f, 300f, 400f); + + // Save the modified PDF to a new file + mend.Save(outputPdf); + } + } +} diff --git a/facades-texts-and-images/add-promotional-text-to-specific-pdf-pages.cs b/facades-texts-and-images/add-promotional-text-to-specific-pdf-pages.cs new file mode 100644 index 00000000..99555df4 --- /dev/null +++ b/facades-texts-and-images/add-promotional-text-to-specific-pdf-pages.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using System.Drawing; // for Color +using Aspose.Pdf.Facades; +using Aspose.Pdf.Text; // for EncodingType + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + const string outputPdf = "output.pdf"; + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input file not found: {inputPdf}"); + return; + } + + // Use PdfFileMend – it provides AddText that accepts an array of page numbers + PdfFileMend pdfMend = new PdfFileMend(); + try + { + // Bind the source PDF + pdfMend.BindPdf(inputPdf); + + // Prepare the promotional message as FormattedText (all styling via constructor) + FormattedText promoText = new FormattedText( + "Special Offer! Buy now.", // text + Color.Red, // text color (System.Drawing.Color) + "Helvetica", // font name + EncodingType.Winansi, // encoding + false, // embed font? + 24); // font size + + // Pages on which the text will be placed (1‑based indexing) + int[] targetPages = new int[] { 3, 5, 7 }; + + // Define the rectangle where the text will appear (lower‑left and upper‑right coordinates) + float lowerLeftX = 100f; + float lowerLeftY = 500f; + float upperRightX = 300f; + float upperRightY = 600f; + + // Add the same promotional message to the specified pages + pdfMend.AddText(promoText, targetPages, lowerLeftX, lowerLeftY, upperRightX, upperRightY); + + // Save the result + pdfMend.Save(outputPdf); + } + finally + { + // Release file handles + pdfMend.Close(); + } + + Console.WriteLine($"Promotional message added to pages 3, 5, and 7. Output saved to '{outputPdf}'."); + } +} diff --git a/facades-texts-and-images/add-semi-transparent-image-text-watermark.cs b/facades-texts-and-images/add-semi-transparent-image-text-watermark.cs new file mode 100644 index 00000000..77bd1461 --- /dev/null +++ b/facades-texts-and-images/add-semi-transparent-image-text-watermark.cs @@ -0,0 +1,77 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main() + { + // Paths – adjust as needed + const string inputPdf = "input.pdf"; + const string outputPdf = "watermarked.pdf"; + const string imagePath = "logo.png"; + const string watermarkText = "CONFIDENTIAL"; + + // Verify files exist + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + if (!File.Exists(imagePath)) + { + Console.Error.WriteLine($"Image file not found: {imagePath}"); + return; + } + + // ----------------------------------------------------------------- + // Create a PdfFileStamp facade – it will edit the PDF and write the + // result to the specified output file. + // ----------------------------------------------------------------- + PdfFileStamp fileStamp = new PdfFileStamp(); + fileStamp.InputFile = inputPdf; // source PDF + fileStamp.OutputFile = outputPdf; // destination PDF + + // Bind the source PDF to the facade + fileStamp.BindPdf(inputPdf); + + // --------------------------------------------------------------- + // 1) Image stamp – placed as background, semi‑transparent + // --------------------------------------------------------------- + Aspose.Pdf.Facades.Stamp imageStamp = new Aspose.Pdf.Facades.Stamp(); + imageStamp.BindImage(imagePath); // use the image file + imageStamp.IsBackground = true; // render behind page content + imageStamp.Opacity = 0.5f; // 50 % opacity + imageStamp.SetOrigin(100f, 400f); // position (X, Y) in points + + // --------------------------------------------------------------- + // 2) Text stamp – rendered over the image, also semi‑transparent + // --------------------------------------------------------------- + // FormattedText constructor sets text, color, font, encoding, bold flag, size + Aspose.Pdf.Facades.FormattedText ft = new Aspose.Pdf.Facades.FormattedText( + watermarkText, + System.Drawing.Color.Red, // text color (System.Drawing.Color is required here) + "Helvetica", // font name + Aspose.Pdf.Facades.EncodingType.Winansi, + false, // not bold + 48); // font size + + Aspose.Pdf.Facades.Stamp textStamp = new Aspose.Pdf.Facades.Stamp(); + textStamp.BindLogo(ft); // bind the formatted text + textStamp.IsBackground = false; // render on top of page content + textStamp.Opacity = 0.5f; // 50 % opacity for the text + textStamp.SetOrigin(100f, 400f); // same position as the image + + // --------------------------------------------------------------- + // Add both stamps to the PDF + // --------------------------------------------------------------- + fileStamp.AddStamp(imageStamp); + fileStamp.AddStamp(textStamp); + + // Persist changes and release resources + fileStamp.Close(); + + Console.WriteLine($"Watermarked PDF saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/add-tiff-image-to-last-pdf-page.cs b/facades-texts-and-images/add-tiff-image-to-last-pdf-page.cs new file mode 100644 index 00000000..5f4fb760 --- /dev/null +++ b/facades-texts-and-images/add-tiff-image-to-last-pdf-page.cs @@ -0,0 +1,58 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; // source PDF + const string tiffImage = "image.tif"; // TIFF to add + const string outputPdf = "output.pdf"; // result PDF + + // Validate files + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + if (!File.Exists(tiffImage)) + { + Console.Error.WriteLine($"TIFF image not found: {tiffImage}"); + return; + } + + // Determine the last page number and its dimensions + int lastPageNumber; + float pageWidth, pageHeight; + using (Document doc = new Document(inputPdf)) + { + // Aspose.Pdf uses 1‑based page indexing + lastPageNumber = doc.Pages.Count; + Page lastPage = doc.Pages[lastPageNumber]; + // PageInfo.Width/Height are double – cast to float for PdfFileMend + pageWidth = (float)lastPage.PageInfo.Width; + pageHeight = (float)lastPage.PageInfo.Height; + } + + // Add the TIFF image to the last page without affecting existing content + PdfFileMend mend = new PdfFileMend(); + mend.BindPdf(inputPdf); + + // Example placement: lower‑left corner, scaled to half the page size + float lowerLeftX = 0f; + float lowerLeftY = 0f; + float upperRightX = pageWidth / 2f; + float upperRightY = pageHeight / 2f; + + // AddImage(string imagePath, int pageNum, float llx, float lly, float urx, float ury) + mend.AddImage(tiffImage, lastPageNumber, lowerLeftX, lowerLeftY, upperRightX, upperRightY); + + // Save the modified PDF + mend.Save(outputPdf); + mend.Close(); + + Console.WriteLine($"TIFF image added to page {lastPageNumber}. Saved as '{outputPdf}'."); + } +} diff --git a/facades-texts-and-images/add-word-wrap-footer-to-pdf-pages.cs b/facades-texts-and-images/add-word-wrap-footer-to-pdf-pages.cs new file mode 100644 index 00000000..074e15b4 --- /dev/null +++ b/facades-texts-and-images/add-word-wrap-footer-to-pdf-pages.cs @@ -0,0 +1,72 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; +using Aspose.Pdf; +using Aspose.Pdf.Facades; +using Aspose.Pdf.Text; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + const string outputPdf = "output.pdf"; + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"File not found: {inputPdf}"); + return; + } + + // Bind the source PDF to the facade + using (PdfFileMend mend = new PdfFileMend()) + { + mend.BindPdf(inputPdf); + + // Enable word‑by‑word wrapping for AddText operations + mend.IsWordWrap = true; + + // Create formatted text (uses System.Drawing.Color for the constructor) + FormattedText footerText = new FormattedText( + "This is a sample footer that will wrap word by word across the page width.", + System.Drawing.Color.DarkGray, + "Helvetica", + EncodingType.Winansi, + false, + 10); // font size + + // Determine page dimensions (assume all pages have the same size) + // Use the first page as a reference + using (Document tempDoc = new Document(inputPdf)) + { + // PageInfo.Width and Height are double – cast to float for PdfFileMend.AddText + float pageWidth = (float)tempDoc.Pages[1].PageInfo.Width; + float pageHeight = (float)tempDoc.Pages[1].PageInfo.Height; + + // Define footer rectangle (bottom margin of 20 units, left/right margins of 30 units) + float leftMargin = 30f; + float rightMargin = 30f; + float bottomMargin = 20f; + float footerHeight = 40f; // enough height for wrapped text + + float lowerLeftX = leftMargin; + float lowerLeftY = bottomMargin; + float upperRightX = pageWidth - rightMargin; + float upperRightY = bottomMargin + footerHeight; + + // Build an array with all page numbers (1‑based indexing) + int[] allPages = Enumerable.Range(1, tempDoc.Pages.Count).ToArray(); + + // Add the formatted footer text to every page within the defined rectangle + mend.AddText(footerText, allPages, lowerLeftX, lowerLeftY, upperRightX, upperRightY); + } + + // Save the modified PDF + mend.Save(outputPdf); + mend.Close(); + } + + Console.WriteLine($"Footer added to all pages: {outputPdf}"); + } +} diff --git a/facades-texts-and-images/add-word-wrapped-paragraph-to-pdf.cs b/facades-texts-and-images/add-word-wrapped-paragraph-to-pdf.cs new file mode 100644 index 00000000..4340120b --- /dev/null +++ b/facades-texts-and-images/add-word-wrapped-paragraph-to-pdf.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Facades; +using Aspose.Pdf.Text; // for EncodingType + +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 existing PDF document + using (Document doc = new Document(inputPath)) + { + // Initialize the PdfFileMend facade with the loaded document + using (PdfFileMend mend = new PdfFileMend(doc)) + { + // Enable word wrap and set the algorithm to wrap by whole words + mend.IsWordWrap = true; + mend.WrapMode = Aspose.Pdf.Facades.WordWrapMode.ByWords; + + // Create formatted text (content, color, font, encoding, embed flag, font size) + var formattedText = new FormattedText( + "This is a very long paragraph that will exceed the defined width of the rectangle and should wrap by words automatically.", + System.Drawing.Color.Blue, + "Helvetica", + EncodingType.Winansi, + false, + 12); + + // Define the rectangle area where the text will be placed + // lower-left corner (X, Y) and upper-right corner (X, Y) + float lowerLeftX = 50f; + float lowerLeftY = 500f; + float upperRightX = 550f; + float upperRightY = 700f; + + // Add the text to page 1 within the specified rectangle + mend.AddText(formattedText, 1, lowerLeftX, lowerLeftY, upperRightX, upperRightY); + + // Save the modified PDF document + mend.Save(outputPath); + } + } + + Console.WriteLine($"Word‑wrapped paragraph added and saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/agents.md b/facades-texts-and-images/agents.md new file mode 100644 index 00000000..5c930773 --- /dev/null +++ b/facades-texts-and-images/agents.md @@ -0,0 +1,125 @@ +--- +name: facades-texts-and-images +description: C# examples for facades-texts-and-images using Aspose.PDF for .NET +language: csharp +framework: net10.0 +parent: ../agents.md +--- + +# AGENTS - facades-texts-and-images + +## Persona + +You are a C# developer specializing in PDF processing using Aspose.PDF for .NET, +working within the **facades-texts-and-images** category. +This folder contains standalone C# examples for facades-texts-and-images operations. +See the root [agents.md](../agents.md) for repository-wide conventions and boundaries. + +## Scope +- This folder contains examples for **facades-texts-and-images**. +- Files are standalone `.cs` examples stored directly in this folder. + +## Required Namespaces + +- `using Aspose.Pdf.Facades;` (27/27 files) ← category-specific +- `using Aspose.Pdf;` (14/27 files) ← category-specific +- `using Aspose.Pdf.Text;` (4/27 files) +- `using Aspose.Pdf.Devices;` (1/27 files) +- `using System;` (27/27 files) +- `using System.IO;` (27/27 files) +- `using System.Drawing.Imaging;` (2/27 files) +- `using System.Linq;` (2/27 files) +- `using NUnit.Framework;` (1/27 files) +- `using System.Drawing;` (1/27 files) +- `using System.Text;` (1/27 files) +- `using System.Threading;` (1/27 files) +- `using System.Threading.Tasks;` (1/27 files) + +## Common Code Pattern + +Most files in this category use `PdfFileMend` from `Aspose.Pdf.Facades`: + +```csharp +PdfFileMend tool = new PdfFileMend(); +tool.BindPdf("input.pdf"); +// ... PdfFileMend operations ... +tool.Save("output.pdf"); +``` + +## Files in this folder + +| File | Title | Key APIs | Description | +|------|-------|----------|-------------| +| [add-background-image-to-all-pdf-pages](./add-background-image-to-all-pdf-pages.cs) | Add Background Image to All PDF Pages | `Document`, `PdfFileMend`, `BindPdf` | Shows how to overlay a PNG background image on every page of a PDF by retrieving page dimensions ... | +| [add-header-image-to-pdf](./add-header-image-to-pdf.cs) | Add Header Image to PDF Files | `PdfFileStamp`, `BindPdf`, `AddHeader` | Shows how to use Aspose.Pdf.Facades.PdfFileStamp in a console app to insert a header image into o... | +| [add-image-and-text-to-pdf-with-logging](./add-image-and-text-to-pdf-with-logging.cs) | Add Image and Text to PDF with Audit Logging | `PdfFileMend`, `BindPdf`, `AddImage` | Shows how to use Aspose.Pdf.Facades.PdfFileMend to insert an image and formatted text onto specif... | +| [add-image-stamp-to-pdf-with-cleanup](./add-image-stamp-to-pdf-with-cleanup.cs) | Add Image Stamp to PDF with Proper Resource Cleanup | `PdfFileMend`, `BindPdf`, `AddImage` | Demonstrates how to bind a PDF, add an image stamp to a page, save the changes, and guarantee res... | +| [add-image-to-all-pdf-pages-dynamic-positioning](./add-image-to-all-pdf-pages-dynamic-positioning.cs) | Add Image to All PDF Pages with Dynamic Positioning | `Document`, `Page`, `PdfFileMend` | Loads a PDF, calculates image placement coordinates based on each page's dimensions, and inserts ... | +| [add-image-to-pdf-page](./add-image-to-pdf-page.cs) | Add Image to Specific PDF Page | `PdfFileMend`, `BindPdf`, `AddImage` | Demonstrates how to insert an image onto a chosen page of a PDF document at specified coordinates... | +| [add-image-to-pdf-with-format-validation](./add-image-to-pdf-with-format-validation.cs) | Add Image to PDF with Format Validation | `PdfFileMend`, `BindPdf`, `AddImage` | Demonstrates how to validate an image's file format before using Aspose.Pdf.Facades.PdfFileMend t... | +| [add-images-to-pdf-with-error-handling](./add-images-to-pdf-with-error-handling.cs) | Add Images to PDF with Error Handling | `PdfFileMend`, `AddImage`, `Close` | Demonstrates how to add multiple images to a PDF using Aspose.Pdf's PdfFileMend facade while hand... | +| [add-multi-line-text-custom-spacing-page-3](./add-multi-line-text-custom-spacing-page-3.cs) | Add Multi‑Line Text with Custom Line Spacing to Page 3 | `PdfFileMend`, `BindPdf`, `Pages` | Demonstrates how to use Aspose.Pdf Facades to insert a multi‑line text paragraph with custom line... | +| [add-png-image-to-pdf-page](./add-png-image-to-pdf-page.cs) | Add PNG Image to PDF Page Using PdfFileMend | `PdfFileMend`, `BindPdf`, `AddImage` | Demonstrates how to bind an existing PDF with PdfFileMend, insert a PNG image onto a specific pag... | +| [add-promotional-text-to-specific-pdf-pages](./add-promotional-text-to-specific-pdf-pages.cs) | Add Promotional Text to Specific PDF Pages | `PdfFileMend`, `BindPdf`, `AddText` | Shows how to insert the same promotional message on pages 3, 5, and 7 of a PDF using Aspose.Pdf.F... | +| [add-semi-transparent-image-text-watermark](./add-semi-transparent-image-text-watermark.cs) | Add Semi-Transparent Image and Text Watermark to PDF | `PdfFileStamp`, `Stamp`, `FormattedText` | Demonstrates how to combine an image stamp and a formatted text stamp using Aspose.Pdf.Facades to... | +| [add-tiff-image-to-last-pdf-page](./add-tiff-image-to-last-pdf-page.cs) | Add TIFF Image to Last PDF Page with PdfFileMend | `Document`, `Page`, `PdfFileMend` | Demonstrates using Aspose.Pdf's PdfFileMend to insert a TIFF image onto the last page of an exist... | +| [add-word-wrap-footer-to-pdf-pages](./add-word-wrap-footer-to-pdf-pages.cs) | Add Word‑Wrap Footer to All PDF Pages | `PdfFileMend`, `BindPdf`, `IsWordWrap` | Shows how to use PdfFileMend with FormattedText to add a word‑by‑word wrapped footer to every pag... | +| [add-word-wrapped-paragraph-to-pdf](./add-word-wrapped-paragraph-to-pdf.cs) | Add Word‑Wrapped Paragraph to PDF Using PdfFileMend | `Document`, `PdfFileMend`, `IsWordWrap` | Demonstrates how to enable the ByWords word‑wrap mode with PdfFileMend and add a long paragraph t... | +| [async-add-image-to-pdf](./async-add-image-to-pdf.cs) | Asynchronously Add Image to PDF Using PdfFileMend | `PdfFileMend`, `BindPdf`, `AddImage` | Shows how to modify a PDF on a background thread by adding an image to the first page with PdfFil... | +| [batch-add-company-logo-to-pdfs](./batch-add-company-logo-to-pdfs.cs) | Batch Add Company Logo to PDFs | `Document`, `PdfFileStamp`, `Stamp` | Demonstrates how to process a folder of PDF files and stamp a company logo PNG onto the top‑right... | +| [batch-extract-images-from-pdfs](./batch-extract-images-from-pdfs.cs) | Batch Extract Images from PDFs with Page and Index Naming | `Document`, `PdfExtractor`, `BindPdf` | Demonstrates how to iterate through multiple PDF files, extract all images per page, and save the... | +| [extract-images-from-pdf-pages](./extract-images-from-pdf-pages.cs) | Extract Images from Specific PDF Pages | `PdfExtractor`, `BindPdf`, `StartPage` | Shows how to extract images from pages 2 through 5 of a PDF and save them as PNG files in a tempo... | +| [extract-images-from-pdf-to-png](./extract-images-from-pdf-to-png.cs) | Extract Images from PDF to PNG | `PdfExtractor`, `BindPdf`, `ExtractImage` | Shows how to use Aspose.Pdf.Facades.PdfExtractor to extract all images from a PDF and save each a... | +| [insert-png-signature-on-every-pdf-page](./insert-png-signature-on-every-pdf-page.cs) | Insert PNG Signature on Every PDF Page | `Document`, `PdfFileMend`, `Count` | Demonstrates how to use PdfFileMend to add a PNG signature image to the bottom‑left corner of eac... | +| [overlay-semi-transparent-gif-onto-pdf](./overlay-semi-transparent-gif-onto-pdf.cs) | Overlay Semi-Transparent GIF onto PDF using CompositingParam... | `Document`, `PdfFileMend`, `CompositingParameters` | Shows how to place a semi‑transparent GIF over an existing PNG in a PDF by using PdfFileMend with... | +| [remove-all-images-from-pdf](./remove-all-images-from-pdf.cs) | Remove All Images from a PDF | `PdfContentEditor`, `BindPdf`, `DeleteImage` | Shows how to delete every image from a PDF using Aspose.Pdf's PdfContentEditor and save the modif... | +| [remove-image-from-pdf-page](./remove-image-from-pdf-page.cs) | Remove Image from Specific PDF Page | `PdfContentEditor`, `BindPdf`, `DeleteImage` | Demonstrates how to delete a particular image on page four of a PDF using Aspose.Pdf's PdfContent... | +| [replace-jpeg-with-bmp](./replace-jpeg-with-bmp.cs) | Replace JPEG Image with BMP Using PdfContentEditor | `Document`, `PdfContentEditor`, `BindPdf` | Shows how to replace an existing image on the first page of a PDF with a higher‑resolution BMP fi... | +| [replace-low-res-images-with-high-res-pngs](./replace-low-res-images-with-high-res-pngs.cs) | Replace Low-Resolution Images with High-Resolution PNGs in P... | `PdfContentEditor`, `BindPdf`, `ReplaceImage` | Shows how to loop through PDF pages and images using Aspose.Pdf.Facades and replace each low‑reso... | +| [verify-pdf-size-increase-after-adding-image](./verify-pdf-size-increase-after-adding-image.cs) | Verify PDF Size Increase After Adding Image | `Document`, `PdfFileMend`, `AddImage` | The example creates a blank PDF, adds a PNG image to the first page using Aspose.Pdf.Facades.PdfF... | + +## Category Statistics +- Total examples: 27 + +## Category-Specific Tips + +### Key API Surface +- `Aspose.Pdf.CgmImportOptions` +- `Aspose.Pdf.Facades.ExtractImageMode` +- `Aspose.Pdf.Facades.ImportFormat` +- `Aspose.Pdf.Facades.PdfContentEditor` +- `Aspose.Pdf.Facades.PdfContentEditor.BindPdf(string)` +- `Aspose.Pdf.Facades.PdfContentEditor.DeleteImage()` +- `Aspose.Pdf.Facades.PdfContentEditor.DeleteImage(int, int[])` +- `Aspose.Pdf.Facades.PdfContentEditor.Save(string)` +- `Aspose.Pdf.Facades.PdfConverter` +- `Aspose.Pdf.Facades.PdfExtractor` +- `Aspose.Pdf.Facades.PdfFileMend` +- `Aspose.Pdf.Facades.PdfPageEditor` +- `Aspose.Pdf.Facades.PdfProducer` + +### Rules +- Bind a PDF file to a PdfConverter with BindPdf({input_pdf}) before any conversion. +- Invoke DoConvert() on the PdfConverter to initialize the conversion process. +- Export the bound PDF to a TIFF image using SaveAsTIFF({output_tiff}) after DoConvert() has been called. +- Always release resources by calling Close() on the PdfConverter when finished. +- Bind the PDF document to a PdfExtractor instance using BindPdf({input_pdf}) before any extraction operation. + +### Warnings +- PdfConverter belongs to the Aspose.Pdf.Facades namespace, which may be considered legacy in newer SDK versions; verify compatibility. +- The example uses System.Drawing.Imaging.ImageFormat for the output format, which may require additional NuGet packages (e.g., System.Drawing.Common) on non‑Windows platforms. +- GetNextImage overwrites files if the generated {output_image_path} collides; ensure unique filenames. +- GetNextImage writes the image data to the provided stream; the stream should be positioned appropriately before further use. +- The example writes images to files using DateTime.Now.Ticks for naming, which may cause naming collisions in rapid successive runs. + +## 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 facades-texts-and-images patterns + + +Updated: 2026-05-08 | Run: `20260508_144637_f72c91` + diff --git a/facades-texts-and-images/async-add-image-to-pdf.cs b/facades-texts-and-images/async-add-image-to-pdf.cs new file mode 100644 index 00000000..30ad945b --- /dev/null +++ b/facades-texts-and-images/async-add-image-to-pdf.cs @@ -0,0 +1,73 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Aspose.Pdf.Facades; + +public static class PdfModificationHelper +{ + /// + /// Asynchronously modifies a PDF by adding an image to the first page. + /// The modification is performed on a background thread using Task.Run to avoid blocking the caller. + /// + /// Path to the source PDF file. + /// Path to the image file to be added. + /// Path where the modified PDF will be saved. + /// Optional cancellation token. + /// A task representing the asynchronous operation. + public static async Task AddImageAsync( + string inputPdfPath, + string imagePath, + string outputPdfPath, + CancellationToken cancellationToken = default) + { + // Validate input arguments early. + if (string.IsNullOrWhiteSpace(inputPdfPath)) + throw new ArgumentException("Input PDF path must be provided.", nameof(inputPdfPath)); + if (string.IsNullOrWhiteSpace(imagePath)) + throw new ArgumentException("Image path must be provided.", nameof(imagePath)); + if (string.IsNullOrWhiteSpace(outputPdfPath)) + throw new ArgumentException("Output PDF path must be provided.", nameof(outputPdfPath)); + if (!File.Exists(inputPdfPath)) + throw new FileNotFoundException("Input PDF file not found.", inputPdfPath); + if (!File.Exists(imagePath)) + throw new FileNotFoundException("Image file not found.", imagePath); + + // Run the PDF modification on a thread‑pool thread. + await Task.Run(() => + { + // The cancellation token is checked before starting the operation. + cancellationToken.ThrowIfCancellationRequested(); + + // PdfFileMend implements IDisposable, so we use a using block for deterministic cleanup. + using (PdfFileMend mend = new PdfFileMend()) + { + // Bind the source PDF file. + mend.BindPdf(inputPdfPath); + + // Add the image to page 1. Coordinates are in default PDF units (points). + // Example places the image at (100, 500) with a width of 200 and height of 150. + int pageNumber = 1; // 1‑based page index + float llx = 100f; // lower‑left X + float lly = 500f; // lower‑left Y + float urx = llx + 200f; // upper‑right X + float ury = lly + 150f; // upper‑right Y + + mend.AddImage(imagePath, pageNumber, llx, lly, urx, ury); + + // Save the modified document. Save(string) writes a PDF regardless of extension. + mend.Save(outputPdfPath); + } + }, cancellationToken).ConfigureAwait(false); + } +} + +public class Program +{ + // Entry point required for a console‑type project. It can be left empty or used for quick testing. + public static async Task Main(string[] args) + { + // Example usage (uncomment and adjust paths to test): + // await PdfModificationHelper.AddImageAsync("input.pdf", "image.png", "output.pdf"); + } +} diff --git a/facades-texts-and-images/batch-add-company-logo-to-pdfs.cs b/facades-texts-and-images/batch-add-company-logo-to-pdfs.cs new file mode 100644 index 00000000..a4657af6 --- /dev/null +++ b/facades-texts-and-images/batch-add-company-logo-to-pdfs.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Facades; + +class BatchLogoAdder +{ + // Resolve paths relative to the executable location to work on any OS. + private static readonly string BaseDirectory = AppDomain.CurrentDomain.BaseDirectory; + private static readonly string InputFolder = Path.Combine(BaseDirectory, "PdfInput"); + private static readonly string OutputFolder = Path.Combine(BaseDirectory, "PdfOutput"); + private static readonly string LogoPath = Path.Combine(BaseDirectory, "company_logo.png"); + + static void Main() + { + // Ensure input, output and logo directories/files exist. + if (!Directory.Exists(InputFolder)) + { + Console.WriteLine($"Input folder not found: {InputFolder}"); + return; + } + if (!File.Exists(LogoPath)) + { + Console.WriteLine($"Logo file not found: {LogoPath}"); + return; + } + Directory.CreateDirectory(OutputFolder); + + // Get all PDF files in the input folder + string[] pdfFiles = Directory.GetFiles(InputFolder, "*.pdf", SearchOption.TopDirectoryOnly); + + foreach (string inputPdfPath in pdfFiles) + { + // Build output file path (same name, different folder) + string outputPdfPath = Path.Combine(OutputFolder, Path.GetFileName(inputPdfPath)); + + // Process each PDF using the Facades API + AddLogoToPdf(inputPdfPath, outputPdfPath); + Console.WriteLine($"Processed: {Path.GetFileName(inputPdfPath)}"); + } + + Console.WriteLine("Batch processing completed."); + } + + private static void AddLogoToPdf(string sourcePdf, string destinationPdf) + { + // Retrieve the dimensions of the first page using the Document API. + // This avoids the non‑existent GetPageInfo method on PdfFileStamp. + var doc = new Document(sourcePdf); + var firstPageInfo = doc.Pages[1].PageInfo; + float pageWidth = (float)firstPageInfo.Width; // Cast double to float + float pageHeight = (float)firstPageInfo.Height; // Cast double to float + + // PdfFileStamp is a facade for adding stamps (images, text, etc.) to a PDF. + // It implements IDisposable, so we wrap it in a using block. + using (PdfFileStamp stampFacade = new PdfFileStamp()) + { + // Bind the source PDF file to the facade. + stampFacade.BindPdf(sourcePdf); + + // Create a Stamp object that will hold the logo image. + Aspose.Pdf.Facades.Stamp logoStamp = new Aspose.Pdf.Facades.Stamp(); + + // Bind the logo image file to the stamp. + logoStamp.BindImage(LogoPath); + + // Optionally set the size of the logo (width, height in points). + logoStamp.SetImageSize(80, 40); // 80pt wide, 40pt high + + // Position the logo at the top‑right corner with a 20‑point margin. + float x = pageWidth - 20 - 80; // page width - right margin - logo width + float y = pageHeight - 20 - 40; // page height - top margin - logo height + logoStamp.SetOrigin(x, y); + + // Add the stamp to all pages of the document. + stampFacade.AddStamp(logoStamp); + + // Save the modified PDF to the destination path. + stampFacade.Save(destinationPdf); + } + } +} diff --git a/facades-texts-and-images/batch-extract-images-from-pdfs.cs b/facades-texts-and-images/batch-extract-images-from-pdfs.cs new file mode 100644 index 00000000..2ed4acd8 --- /dev/null +++ b/facades-texts-and-images/batch-extract-images-from-pdfs.cs @@ -0,0 +1,69 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Facades; + +class BatchImageExtractor +{ + static void Main() + { + // Use platform‑agnostic paths (relative to the current working directory) + string inputFolder = Path.Combine(Directory.GetCurrentDirectory(), "InputPdfs"); + string outputFolder = Path.Combine(Directory.GetCurrentDirectory(), "ExtractedImages"); + + // Ensure the directories exist (create if missing) + Directory.CreateDirectory(inputFolder); + Directory.CreateDirectory(outputFolder); + + // Process each PDF file in the input folder + foreach (string pdfPath in Directory.GetFiles(inputFolder, "*.pdf")) + { + // Base name of the PDF (without extension) for naming output files + string pdfBaseName = Path.GetFileNameWithoutExtension(pdfPath); + + // Get page count using Document (required for per‑page extraction) + int pageCount; + using (Document doc = new Document(pdfPath)) + { + pageCount = doc.Pages.Count; // 1‑based indexing + } + + // Create a PdfExtractor for the current PDF + using (PdfExtractor extractor = new PdfExtractor()) + { + // Bind the PDF file to the extractor + extractor.BindPdf(pdfPath); + + // Iterate over each page to extract images with page number context + for (int page = 1; page <= pageCount; page++) + { + // Restrict extraction to a single page + extractor.StartPage = page; + extractor.EndPage = page; + + // Perform image extraction for the specified page + extractor.ExtractImage(); + + int imageIndex = 1; + // Retrieve all images found on this page + while (extractor.HasNextImage()) + { + // Build output file name: _page_img.png + string outputFile = Path.Combine( + outputFolder, + $"{pdfBaseName}_page{page}_img{imageIndex}.png"); + + // Save the image using the overload that does not require System.Drawing.ImageFormat + // This avoids the CA1416 platform‑specific warning. + extractor.GetNextImage(outputFile); + imageIndex++; + } + } + } + + Console.WriteLine($"Images extracted from '{pdfPath}'."); + } + + Console.WriteLine("Batch extraction completed."); + } +} diff --git a/facades-texts-and-images/extract-images-from-pdf-pages.cs b/facades-texts-and-images/extract-images-from-pdf-pages.cs new file mode 100644 index 00000000..118198cb --- /dev/null +++ b/facades-texts-and-images/extract-images-from-pdf-pages.cs @@ -0,0 +1,49 @@ +using System; +using System.IO; +using Aspose.Pdf.Facades; +using System.Drawing.Imaging; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input file not found: {inputPdf}"); + return; + } + + // Create a unique temporary directory for the extracted images + string tempDir = Path.Combine(Path.GetTempPath(), "AsposePdfImages_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + + // Use PdfExtractor (Facade) to extract images from pages 2‑5 + using (PdfExtractor extractor = new PdfExtractor()) + { + // Bind the source PDF file + extractor.BindPdf(inputPdf); + + // Set the page range (Aspose.Pdf uses 1‑based indexing) + extractor.StartPage = 2; + extractor.EndPage = 5; + + // Perform the image extraction + extractor.ExtractImage(); + + int imageIndex = 1; + while (extractor.HasNextImage()) + { + // Build the output file path (PNG format) + string outFile = Path.Combine(tempDir, $"image_{imageIndex}.png"); + + // Save the next image; GetNextImage returns a bool indicating success + extractor.GetNextImage(outFile, ImageFormat.Png); + imageIndex++; + } + } + + Console.WriteLine($"Images extracted to temporary folder: {tempDir}"); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/extract-images-from-pdf-to-png.cs b/facades-texts-and-images/extract-images-from-pdf-to-png.cs new file mode 100644 index 00000000..24b3d9c4 --- /dev/null +++ b/facades-texts-and-images/extract-images-from-pdf-to-png.cs @@ -0,0 +1,51 @@ +using System; +using System.IO; +using System.Drawing.Imaging; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; + const string outputFolder = "ExtractedImages"; + + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input file not found: {inputPdfPath}"); + return; + } + + // Ensure the output directory exists + Directory.CreateDirectory(outputFolder); + + // Use PdfExtractor (implements IDisposable) inside a using block + using (PdfExtractor extractor = new PdfExtractor()) + { + // Bind the source PDF file + extractor.BindPdf(inputPdfPath); + + // Extract images from the PDF + extractor.ExtractImage(); + + int imageIndex = 1; + // Iterate through all extracted images + while (extractor.HasNextImage()) + { + // Build the output file name (PNG format) + string outputPath = Path.Combine(outputFolder, $"image-{imageIndex}.png"); + + // Save the current image as PNG + bool success = extractor.GetNextImage(outputPath, ImageFormat.Png); + if (!success) + { + Console.Error.WriteLine($"Failed to extract image #{imageIndex}"); + } + + imageIndex++; + } + } + + Console.WriteLine("Image extraction completed."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/index.json b/facades-texts-and-images/index.json new file mode 100644 index 00000000..d6661c8e --- /dev/null +++ b/facades-texts-and-images/index.json @@ -0,0 +1,620 @@ +{ + "category": "facades-texts-and-images", + "nuget_version": "26.4.0", + "last_updated": "2026-05-08T09:47:41Z", + "examples": { + "add-png-image-to-pdf-page": { + "title": "Add PNG Image to PDF Page Using PdfFileMend", + "filename": "add-png-image-to-pdf-page.cs", + "description": "Demonstrates how to bind an existing PDF with PdfFileMend, insert a PNG image onto a specific page at given coordinates, and save the result as a new PDF.", + "tags": [ + "pdf", + "image", + "add-image", + "PdfFileMend", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfFileMend", + "Aspose.Pdf.Facades.PdfFileMend.BindPdf", + "Aspose.Pdf.Facades.PdfFileMend.AddImage", + "Aspose.Pdf.Facades.PdfFileMend.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "replace-jpeg-with-bmp": { + "title": "Replace JPEG Image with BMP Using PdfContentEditor", + "filename": "replace-jpeg-with-bmp.cs", + "description": "Shows how to replace an existing image on the first page of a PDF with a higher‑resolution BMP file using Aspose.Pdf.Facades.PdfContentEditor.", + "tags": [ + "image-replacement", + "pdf", + "bmp", + "Aspose.Pdf", + "PdfContentEditor" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Facades.PdfContentEditor", + "Aspose.Pdf.Facades.PdfContentEditor.BindPdf", + "Aspose.Pdf.Facades.PdfContentEditor.ReplaceImage", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "overlay-semi-transparent-gif-onto-pdf": { + "title": "Overlay Semi-Transparent GIF onto PDF using CompositingParameters", + "filename": "overlay-semi-transparent-gif-onto-pdf.cs", + "description": "Shows how to place a semi‑transparent GIF over an existing PNG in a PDF by using PdfFileMend with CompositingParameters and a blend mode.", + "tags": [ + "overlay", + "gif", + "compositing", + "pdf", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Facades.PdfFileMend", + "Aspose.Pdf.Facades.CompositingParameters", + "Aspose.Pdf.Devices.BlendMode", + "Aspose.Pdf.Facades.PdfFileMend.AddImage" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-word-wrap-footer-to-pdf-pages": { + "title": "Add Word‑Wrap Footer to All PDF Pages", + "filename": "add-word-wrap-footer-to-pdf-pages.cs", + "description": "Shows how to use PdfFileMend with FormattedText to add a word‑by‑word wrapped footer to every page of a PDF document.", + "tags": [ + "footer", + "word-wrap", + "pdf", + "Aspose.Pdf", + "PdfFileMend" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfFileMend", + "Aspose.Pdf.Facades.PdfFileMend.BindPdf", + "Aspose.Pdf.Facades.PdfFileMend.IsWordWrap", + "Aspose.Pdf.Facades.PdfFileMend.AddText", + "Aspose.Pdf.Text.FormattedText", + "Aspose.Pdf.Document" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-promotional-text-to-specific-pdf-pages": { + "title": "Add Promotional Text to Specific PDF Pages", + "filename": "add-promotional-text-to-specific-pdf-pages.cs", + "description": "Shows how to insert the same promotional message on pages 3, 5, and 7 of a PDF using Aspose.Pdf.Facades.PdfFileMend.AddText with an array of page numbers.", + "tags": [ + "pdf", + "text", + "addtext", + "page-range", + "aspose-pdf" + ], + "apis_used": [ + "PdfFileMend", + "PdfFileMend.BindPdf", + "PdfFileMend.AddText", + "PdfFileMend.Save", + "PdfFileMend.Close", + "FormattedText", + "EncodingType" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-multi-line-text-custom-spacing-page-3": { + "title": "Add Multi‑Line Text with Custom Line Spacing to Page 3", + "filename": "add-multi-line-text-custom-spacing-page-3.cs", + "description": "Demonstrates how to use Aspose.Pdf Facades to insert a multi‑line text paragraph with custom line spacing into the left margin of the third page of a PDF document.", + "tags": [ + "text", + "paragraph", + "line-spacing", + "facade", + "pdf" + ], + "apis_used": [ + "PdfFileMend", + "PdfFileMend.BindPdf", + "Document.Pages", + "TextParagraph", + "TextParagraph.AppendLine", + "TextBuilder", + "TextBuilder.AppendParagraph", + "PdfFileMend.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-semi-transparent-image-text-watermark": { + "title": "Add Semi-Transparent Image and Text Watermark to PDF", + "filename": "add-semi-transparent-image-text-watermark.cs", + "description": "Demonstrates how to combine an image stamp and a formatted text stamp using Aspose.Pdf.Facades to create a semi‑transparent watermark over each page of a PDF.", + "tags": [ + "watermark", + "image", + "text", + "pdf", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfFileStamp", + "Aspose.Pdf.Facades.Stamp", + "Aspose.Pdf.Facades.FormattedText", + "PdfFileStamp.BindPdf", + "Stamp.BindImage", + "Stamp.BindLogo", + "PdfFileStamp.AddStamp", + "PdfFileStamp.Close" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-background-image-to-all-pdf-pages": { + "title": "Add Background Image to All PDF Pages", + "filename": "add-background-image-to-all-pdf-pages.cs", + "description": "Shows how to overlay a PNG background image on every page of a PDF by retrieving page dimensions and using the PdfFileMend facade to add the image.", + "tags": [ + "pdf", + "background-image", + "Aspose.Pdf", + "facade", + "page-manipulation" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Facades.PdfFileMend", + "Aspose.Pdf.Facades.PdfFileMend.BindPdf", + "Aspose.Pdf.Facades.PdfFileMend.AddImage", + "Aspose.Pdf.Facades.PdfFileMend.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-header-image-to-pdf": { + "title": "Add Header Image to PDF Files", + "filename": "add-header-image-to-pdf.cs", + "description": "Shows how to use Aspose.Pdf.Facades.PdfFileStamp in a console app to insert a header image into one or more PDF documents.", + "tags": [ + "pdf", + "header", + "image", + "facade", + "console" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfFileStamp", + "Aspose.Pdf.Facades.PdfFileStamp.BindPdf", + "Aspose.Pdf.Facades.PdfFileStamp.AddHeader", + "Aspose.Pdf.Facades.PdfFileStamp.Save", + "Aspose.Pdf.Facades.PdfFileStamp.Close" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "batch-add-company-logo-to-pdfs": { + "title": "Batch Add Company Logo to PDFs", + "filename": "batch-add-company-logo-to-pdfs.cs", + "description": "Demonstrates how to process a folder of PDF files and stamp a company logo PNG onto the top‑right corner of each document using Aspose.Pdf facades.", + "tags": [ + "pdf", + "logo", + "batch", + "stamp", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Facades.PdfFileStamp", + "Aspose.Pdf.Facades.Stamp", + "Aspose.Pdf.Facades.Stamp.BindImage", + "Aspose.Pdf.Facades.Stamp.SetImageSize", + "Aspose.Pdf.Facades.Stamp.SetOrigin", + "Aspose.Pdf.Facades.PdfFileStamp.AddStamp", + "Aspose.Pdf.Facades.PdfFileStamp.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "insert-png-signature-on-every-pdf-page": { + "title": "Insert PNG Signature on Every PDF Page", + "filename": "insert-png-signature-on-every-pdf-page.cs", + "description": "Demonstrates how to use PdfFileMend to add a PNG signature image to the bottom‑left corner of each page in a PDF document.", + "tags": [ + "pdf", + "signature", + "image", + "Aspose.Pdf", + "PdfFileMend" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Facades.PdfFileMend", + "Aspose.Pdf.Document.Pages.Count", + "Aspose.Pdf.Facades.PdfFileMend.BindPdf", + "Aspose.Pdf.Facades.PdfFileMend.AddImage", + "Aspose.Pdf.Facades.PdfFileMend.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-tiff-image-to-last-pdf-page": { + "title": "Add TIFF Image to Last PDF Page with PdfFileMend", + "filename": "add-tiff-image-to-last-pdf-page.cs", + "description": "Demonstrates using Aspose.Pdf's PdfFileMend to insert a TIFF image onto the last page of an existing PDF without altering the original page content.", + "tags": [ + "tiff", + "image", + "pdf", + "pdffilemend", + "aspose" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Facades.PdfFileMend", + "Aspose.Pdf.Facades.PdfFileMend.BindPdf", + "Aspose.Pdf.Facades.PdfFileMend.AddImage", + "Aspose.Pdf.Facades.PdfFileMend.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-image-to-all-pdf-pages-dynamic-positioning": { + "title": "Add Image to All PDF Pages with Dynamic Positioning", + "filename": "add-image-to-all-pdf-pages-dynamic-positioning.cs", + "description": "Loads a PDF, calculates image placement coordinates based on each page's dimensions, and inserts the image into the bottom‑right corner of every page using the PdfFileMend facade.", + "tags": [ + "image", + "pdf", + "placement", + "facade", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Facades.PdfFileMend", + "Aspose.Pdf.Facades.PdfFileMend.AddImage", + "Aspose.Pdf.Facades.PdfFileMend.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-image-to-pdf-with-format-validation": { + "title": "Add Image to PDF with Format Validation", + "filename": "add-image-to-pdf-with-format-validation.cs", + "description": "Demonstrates how to validate an image's file format before using Aspose.Pdf.Facades.PdfFileMend to insert the image into a PDF page.", + "tags": [ + "pdf", + "image", + "validation", + "aspose", + "facade" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfFileMend", + "Aspose.Pdf.Facades.PdfFileMend.BindPdf", + "Aspose.Pdf.Facades.PdfFileMend.AddImage", + "Aspose.Pdf.Facades.PdfFileMend.Save", + "Aspose.Pdf.Facades.PdfFileMend.Close" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-image-stamp-to-pdf-with-cleanup": { + "title": "Add Image Stamp to PDF with Proper Resource Cleanup", + "filename": "add-image-stamp-to-pdf-with-cleanup.cs", + "description": "Demonstrates how to bind a PDF, add an image stamp to a page, save the changes, and guarantee resource release using a try‑finally block that calls Close() on PdfFileMend.", + "tags": [ + "pdf", + "image", + "stamp", + "resource-management", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfFileMend", + "PdfFileMend.BindPdf", + "PdfFileMend.AddImage", + "PdfFileMend.Save", + "PdfFileMend.Close" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-images-to-pdf-with-error-handling": { + "title": "Add Images to PDF with Error Handling", + "filename": "add-images-to-pdf-with-error-handling.cs", + "description": "Demonstrates how to add multiple images to a PDF using Aspose.Pdf's PdfFileMend facade while handling missing files and exceptions for each image.", + "tags": [ + "pdf", + "image", + "add-image", + "error-handling", + "Aspose.Pdf" + ], + "apis_used": [ + "PdfFileMend", + "PdfFileMend.AddImage", + "PdfFileMend.Close", + "PdfFileMend.Dispose", + "PdfFileMend.SaveableFacade" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-image-and-text-to-pdf-with-logging": { + "title": "Add Image and Text to PDF with Audit Logging", + "filename": "add-image-and-text-to-pdf-with-logging.cs", + "description": "Shows how to use Aspose.Pdf.Facades.PdfFileMend to insert an image and formatted text onto specific PDF pages and log each operation with timestamps for auditing.", + "tags": [ + "pdf", + "image", + "text", + "logging", + "aspose-pdf" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfFileMend", + "Aspose.Pdf.Facades.PdfFileMend.BindPdf", + "Aspose.Pdf.Facades.PdfFileMend.AddImage", + "Aspose.Pdf.Facades.PdfFileMend.AddText", + "Aspose.Pdf.Facades.PdfFileMend.Save", + "Aspose.Pdf.FormattedText", + "Aspose.Pdf.EncodingType" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-word-wrapped-paragraph-to-pdf": { + "title": "Add Word‑Wrapped Paragraph to PDF Using PdfFileMend", + "filename": "add-word-wrapped-paragraph-to-pdf.cs", + "description": "Demonstrates how to enable the ByWords word‑wrap mode with PdfFileMend and add a long paragraph that automatically wraps within a defined rectangle in a PDF document.", + "tags": [ + "word-wrap", + "pdf-text", + "formatted-text", + "PdfFileMend", + "Aspose.Pdf" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Facades.PdfFileMend", + "Aspose.Pdf.Facades.PdfFileMend.IsWordWrap", + "Aspose.Pdf.Facades.PdfFileMend.WrapMode", + "Aspose.Pdf.Text.FormattedText", + "Aspose.Pdf.Facades.PdfFileMend.AddText", + "Aspose.Pdf.Facades.PdfFileMend.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "add-image-to-pdf-page": { + "title": "Add Image to Specific PDF Page", + "filename": "add-image-to-pdf-page.cs", + "description": "Demonstrates how to insert an image onto a chosen page of a PDF document at specified coordinates using Aspose.Pdf.Facades.", + "tags": [ + "image", + "pdf", + "aspose", + "facade", + "add-image" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfFileMend", + "PdfFileMend.BindPdf", + "PdfFileMend.AddImage", + "PdfFileMend.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "async-add-image-to-pdf": { + "title": "Asynchronously Add Image to PDF Using PdfFileMend", + "filename": "async-add-image-to-pdf.cs", + "description": "Shows how to modify a PDF on a background thread by adding an image to the first page with PdfFileMend wrapped in Task.Run for non‑blocking execution.", + "tags": [ + "pdf", + "asynchronous", + "image", + "aspose", + "pdf-modification" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfFileMend", + "PdfFileMend.BindPdf", + "PdfFileMend.AddImage", + "PdfFileMend.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "extract-images-from-pdf-to-png": { + "title": "Extract Images from PDF to PNG", + "filename": "extract-images-from-pdf-to-png.cs", + "description": "Shows how to use Aspose.Pdf.Facades.PdfExtractor to extract all images from a PDF and save each as an individual PNG file.", + "tags": [ + "pdf", + "image-extraction", + "png", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfExtractor", + "Aspose.Pdf.Facades.PdfExtractor.BindPdf", + "Aspose.Pdf.Facades.PdfExtractor.ExtractImage", + "Aspose.Pdf.Facades.PdfExtractor.HasNextImage", + "Aspose.Pdf.Facades.PdfExtractor.GetNextImage" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "extract-images-from-pdf-pages": { + "title": "Extract Images from Specific PDF Pages", + "filename": "extract-images-from-pdf-pages.cs", + "description": "Shows how to extract images from pages 2 through 5 of a PDF and save them as PNG files in a temporary directory using Aspose.Pdf.Facades.", + "tags": [ + "pdf", + "image-extraction", + "aspose-pdf", + "facade", + "temp-directory" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfExtractor", + "PdfExtractor.BindPdf", + "PdfExtractor.StartPage", + "PdfExtractor.EndPage", + "PdfExtractor.ExtractImage", + "PdfExtractor.HasNextImage", + "PdfExtractor.GetNextImage" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "batch-extract-images-from-pdfs": { + "title": "Batch Extract Images from PDFs with Page and Index Naming", + "filename": "batch-extract-images-from-pdfs.cs", + "description": "Demonstrates how to iterate through multiple PDF files, extract all images per page, and save them with filenames that include the original PDF name, page number, and image index.", + "tags": [ + "pdf", + "image-extraction", + "batch-processing", + "aspose-pdf", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Facades.PdfExtractor", + "Aspose.Pdf.Facades.PdfExtractor.BindPdf", + "Aspose.Pdf.Facades.PdfExtractor.ExtractImage", + "Aspose.Pdf.Facades.PdfExtractor.HasNextImage", + "Aspose.Pdf.Facades.PdfExtractor.GetNextImage" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "remove-image-from-pdf-page": { + "title": "Remove Image from Specific PDF Page", + "filename": "remove-image-from-pdf-page.cs", + "description": "Demonstrates how to delete a particular image on page four of a PDF using Aspose.Pdf's PdfContentEditor. The example loads a PDF, removes the image by its index, and saves the result.", + "tags": [ + "pdf", + "image", + "remove", + "aspose", + "csharp" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfContentEditor", + "Aspose.Pdf.Facades.PdfContentEditor.BindPdf", + "Aspose.Pdf.Facades.PdfContentEditor.DeleteImage", + "Aspose.Pdf.Facades.PdfContentEditor.Save", + "Aspose.Pdf.Facades.PdfContentEditor.Dispose" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "remove-all-images-from-pdf": { + "title": "Remove All Images from a PDF", + "filename": "remove-all-images-from-pdf.cs", + "description": "Shows how to delete every image from a PDF using Aspose.Pdf's PdfContentEditor and save the modified document to a new file.", + "tags": [ + "pdf", + "image-removal", + "aspose-pdf", + "csharp", + "facade" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfContentEditor", + "Aspose.Pdf.Facades.PdfContentEditor.BindPdf", + "Aspose.Pdf.Facades.PdfContentEditor.DeleteImage", + "Aspose.Pdf.Facades.PdfContentEditor.Save" + ], + "difficulty": "beginner", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "replace-low-res-images-with-high-res-pngs": { + "title": "Replace Low-Resolution Images with High-Resolution PNGs in PDF", + "filename": "replace-low-res-images-with-high-res-pngs.cs", + "description": "Shows how to loop through PDF pages and images using Aspose.Pdf.Facades and replace each low‑resolution image with a corresponding high‑resolution PNG file.", + "tags": [ + "pdf", + "image-replacement", + "aspose", + "csharp", + "facade" + ], + "apis_used": [ + "Aspose.Pdf.Facades.PdfContentEditor", + "Aspose.Pdf.Facades.PdfContentEditor.BindPdf", + "Aspose.Pdf.Facades.PdfContentEditor.ReplaceImage", + "Aspose.Pdf.Facades.PdfContentEditor.Save", + "Aspose.Pdf.Document", + "Aspose.Pdf.Page", + "Aspose.Pdf.Resources.ImageCollection" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + }, + "verify-pdf-size-increase-after-adding-image": { + "title": "Verify PDF Size Increase After Adding Image", + "filename": "verify-pdf-size-increase-after-adding-image.cs", + "description": "The example creates a blank PDF, adds a PNG image to the first page using Aspose.Pdf.Facades.PdfFileMend, and asserts that the PDF byte size grows, demonstrating how to validate image insertion with unit tests.", + "tags": [ + "pdf", + "image", + "unit-test", + "aspose", + "size" + ], + "apis_used": [ + "Aspose.Pdf.Document", + "Aspose.Pdf.Facades.PdfFileMend", + "Aspose.Pdf.Facades.PdfFileMend.AddImage", + "Aspose.Pdf.Facades.PdfFileMend.Close", + "Aspose.Pdf.Document.Save" + ], + "difficulty": "intermediate", + "generated_at": "2026-05-08T09:47:41Z", + "status": "verified" + } + } +} \ No newline at end of file diff --git a/facades-texts-and-images/insert-png-signature-on-every-pdf-page.cs b/facades-texts-and-images/insert-png-signature-on-every-pdf-page.cs new file mode 100644 index 00000000..f03ad20f --- /dev/null +++ b/facades-texts-and-images/insert-png-signature-on-every-pdf-page.cs @@ -0,0 +1,62 @@ +using System; +using System.IO; +using System.Linq; +using Aspose.Pdf; // Document class for page count +using Aspose.Pdf.Facades; // PdfFileMend class + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; // source PDF + const string outputPdf = "output_signed.pdf"; // result PDF + const string signatureImg = "signature.png"; // PNG to place on each page + + // Ensure the source files exist + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdf}"); + return; + } + if (!File.Exists(signatureImg)) + { + Console.Error.WriteLine($"Signature image not found: {signatureImg}"); + return; + } + + // Determine how many pages the document has (required for PdfFileMend) + int pageCount; + using (Document doc = new Document(inputPdf)) + { + pageCount = doc.Pages.Count; // Aspose.Pdf uses 1‑based indexing + } + + // Build an array with all page numbers (1 … pageCount) + int[] allPages = Enumerable.Range(1, pageCount).ToArray(); + + // Create PdfFileMend, bind the source PDF, add the image to every page, + // then save the modified document. + PdfFileMend mend = new PdfFileMend(); + mend.BindPdf(inputPdf); + + // Coordinates for the bottom‑left corner. + // lowerLeftX = 0, lowerLeftY = 0 (origin is bottom‑left of the page) + // upperRightX/Y define the size of the image (e.g., 100×50 points) + const float lowerLeftX = 0f; + const float lowerLeftY = 0f; + const float upperRightX = 100f; + const float upperRightY = 50f; + + bool success = mend.AddImage(signatureImg, allPages, lowerLeftX, lowerLeftY, upperRightX, upperRightY); + if (!success) + { + Console.Error.WriteLine("Failed to add the signature image to the PDF."); + } + + // Save the result and release resources. + mend.Save(outputPdf); + mend.Close(); + + Console.WriteLine($"Signature image added to all pages. Output saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/overlay-semi-transparent-gif-onto-pdf.cs b/facades-texts-and-images/overlay-semi-transparent-gif-onto-pdf.cs new file mode 100644 index 00000000..08f386ca --- /dev/null +++ b/facades-texts-and-images/overlay-semi-transparent-gif-onto-pdf.cs @@ -0,0 +1,57 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Facades; +using Aspose.Pdf.Devices; // for BlendMode enum + +class Program +{ + static void Main() + { + // Paths – adjust as needed + const string inputPdfPath = "input.pdf"; // PDF that already contains a PNG image + const string outputPdfPath = "output.pdf"; // Resulting PDF with GIF overlay + const string overlayGifPath = "overlay.gif"; // Semi‑transparent GIF to overlay + + // Verify files exist + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + if (!File.Exists(overlayGifPath)) + { + Console.Error.WriteLine($"Overlay GIF not found: {overlayGifPath}"); + return; + } + + // Load the existing PDF inside a using block for deterministic disposal + using (Document pdfDoc = new Document(inputPdfPath)) + { + // Create a PdfFileMend facade bound to the loaded document + PdfFileMend mender = new PdfFileMend(pdfDoc); + + // Define compositing parameters – using Multiply blend mode for semi‑transparent effect + CompositingParameters compParams = new CompositingParameters(BlendMode.Multiply); + + // Define the rectangle where the GIF will be placed (coordinates are in points) + // Example: lower‑left (50, 400), upper‑right (250, 600) + float lowerLeftX = 50f; + float lowerLeftY = 400f; + float upperRightX = 250f; + float upperRightY = 600f; + + // Add the GIF image to page 1 with the compositing parameters + // This overlays the GIF on top of any existing content (e.g., the PNG) + mender.AddImage(overlayGifPath, 1, lowerLeftX, lowerLeftY, upperRightX, upperRightY, compParams); + + // Save the modified PDF – no extra save options needed + pdfDoc.Save(outputPdfPath); + + // Close the facade (releases internal resources) + mender.Close(); + } + + Console.WriteLine($"Overlay completed. Output saved to '{outputPdfPath}'."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/remove-all-images-from-pdf.cs b/facades-texts-and-images/remove-all-images-from-pdf.cs new file mode 100644 index 00000000..2c41544c --- /dev/null +++ b/facades-texts-and-images/remove-all-images-from-pdf.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using Aspose.Pdf.Facades; + +public static class PdfImageRemover +{ + /// + /// Removes all images from the specified PDF file and saves the result to a new file. + /// + /// Path to the source PDF. + /// Path where the image‑free PDF will be saved. + public static void RemoveAllImages(string inputPath, string outputPath) + { + // Validate input file existence. + if (!File.Exists(inputPath)) + throw new FileNotFoundException($"Input PDF not found: {inputPath}"); + + // PdfContentEditor implements IDisposable, so wrap it in a using block. + using (PdfContentEditor editor = new PdfContentEditor()) + { + // Bind the source PDF to the editor. + editor.BindPdf(inputPath); + + // Delete every image from the document. + editor.DeleteImage(); + + // Save the modified document to the desired output path. + editor.Save(outputPath); + } + } +} + +public class Program +{ + /// + /// Entry point required for a console‑style build. Demonstrates the image‑removal utility. + /// + public static void Main(string[] args) + { + if (args.Length != 2) + { + Console.WriteLine("Usage: PdfImageRemover "); + return; + } + + string inputPath = args[0]; + string outputPath = args[1]; + + try + { + PdfImageRemover.RemoveAllImages(inputPath, outputPath); + Console.WriteLine($"All images removed. Output saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } +} \ No newline at end of file diff --git a/facades-texts-and-images/remove-image-from-pdf-page.cs b/facades-texts-and-images/remove-image-from-pdf-page.cs new file mode 100644 index 00000000..4c6db621 --- /dev/null +++ b/facades-texts-and-images/remove-image-from-pdf-page.cs @@ -0,0 +1,35 @@ +using System; +using System.IO; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main() + { + const string inputPath = "input.pdf"; + const string outputPath = "output.pdf"; + const int pageNumber = 4; // Target page (1‑based indexing) + int[] imageIndexes = new int[] { 2 }; // Index of the image to remove on page 4 (replace with actual index) + + if (!File.Exists(inputPath)) + { + Console.Error.WriteLine($"File not found: {inputPath}"); + return; + } + + // PdfContentEditor implements IDisposable, so wrap it in a using block + using (PdfContentEditor editor = new PdfContentEditor()) + { + // Load the PDF document + editor.BindPdf(inputPath); + + // Delete the specified image(s) from page 4 + editor.DeleteImage(pageNumber, imageIndexes); + + // Save the modified PDF + editor.Save(outputPath); + } + + Console.WriteLine($"Specified image removed. Output saved to '{outputPath}'."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/replace-jpeg-with-bmp.cs b/facades-texts-and-images/replace-jpeg-with-bmp.cs new file mode 100644 index 00000000..7515764f --- /dev/null +++ b/facades-texts-and-images/replace-jpeg-with-bmp.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main() + { + const string inputPdfPath = "input.pdf"; // source PDF containing the JPEG image + const string outputPdfPath = "output.pdf"; // PDF after replacement + const string bmpImagePath = "highres.bmp"; // path to the high‑resolution BMP file + + // Verify input files exist + if (!File.Exists(inputPdfPath)) + { + Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}"); + return; + } + if (!File.Exists(bmpImagePath)) + { + Console.Error.WriteLine($"BMP image not found: {bmpImagePath}"); + return; + } + + // Load the PDF document inside a using block for deterministic disposal + using (Document pdfDoc = new Document(inputPdfPath)) + { + // Bind the document to PdfContentEditor (facade) also within a using block + using (PdfContentEditor editor = new PdfContentEditor()) + { + editor.BindPdf(pdfDoc); + + // Replace the first image (index = 1) on page 1 with the BMP file. + // PdfContentEditor.ReplaceImage expects a file path, so we provide the BMP path directly. + editor.ReplaceImage(pageNumber: 1, index: 1, imageFile: bmpImagePath); + } + + // Save the modified document + pdfDoc.Save(outputPdfPath); + } + + Console.WriteLine($"Image replaced successfully. Output saved to '{outputPdfPath}'."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/replace-low-res-images-with-high-res-pngs.cs b/facades-texts-and-images/replace-low-res-images-with-high-res-pngs.cs new file mode 100644 index 00000000..a460e900 --- /dev/null +++ b/facades-texts-and-images/replace-low-res-images-with-high-res-pngs.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; +using Aspose.Pdf.Facades; + +class Program +{ + static void Main() + { + const string inputPdf = "input.pdf"; + const string outputPdf = "output.pdf"; + const string highResDir = "HighResImages"; // folder containing high‑resolution PNGs + + if (!File.Exists(inputPdf)) + { + Console.Error.WriteLine($"Input file not found: {inputPdf}"); + return; + } + + // Bind the PDF to the editor (facade) and work within a using block for deterministic disposal + using (PdfContentEditor editor = new PdfContentEditor()) + { + editor.BindPdf(inputPdf); + + // Get total number of pages (1‑based indexing) + int pageCount = editor.Document.Pages.Count; + + // Loop through each page + for (int pageNum = 1; pageNum <= pageCount; pageNum++) + { + // Number of images on the current page (1‑based indexing) + int imageCount = editor.Document.Pages[pageNum].Resources.Images.Count; + + // Loop through each image on the page + for (int imgIdx = 1; imgIdx <= imageCount; imgIdx++) + { + // Build the expected high‑resolution PNG file name. + // Example naming convention: page1_img1.png, page2_img3.png, etc. + string highResPath = Path.Combine(highResDir, $"page{pageNum}_img{imgIdx}.png"); + + // Replace only if the high‑resolution image exists + if (File.Exists(highResPath)) + { + // Replace the low‑resolution image with the high‑resolution PNG + editor.ReplaceImage(pageNum, imgIdx, highResPath); + } + } + } + + // Save the modified PDF + editor.Save(outputPdf); + } + + Console.WriteLine($"All images replaced. Output saved to '{outputPdf}'."); + } +} \ No newline at end of file diff --git a/facades-texts-and-images/verify-pdf-size-increase-after-adding-image.cs b/facades-texts-and-images/verify-pdf-size-increase-after-adding-image.cs new file mode 100644 index 00000000..19c6a0ac --- /dev/null +++ b/facades-texts-and-images/verify-pdf-size-increase-after-adding-image.cs @@ -0,0 +1,154 @@ +using System; +using System.IO; +using Aspose.Pdf; +using Aspose.Pdf.Facades; +using NUnit.Framework; + +// Minimal NUnit stubs to allow compilation without the real NUnit package +namespace NUnit.Framework +{ + [AttributeUsage(AttributeTargets.Class)] + public sealed class TestFixtureAttribute : Attribute { } + + [AttributeUsage(AttributeTargets.Method)] + public sealed class TestAttribute : Attribute { } + + [AttributeUsage(AttributeTargets.Method)] + public sealed class SetUpAttribute : Attribute { } + + [AttributeUsage(AttributeTargets.Method)] + public sealed class TearDownAttribute : Attribute { } + + public static class Assert + { + public static void IsTrue(bool condition, string? message = null) + { + if (!condition) + throw new Exception(message ?? "Assert.IsTrue failed."); + } + + public static void AreNotEqual(T notExpected, T actual, string? message = null) + { + if (object.Equals(notExpected, actual)) + throw new Exception(message ?? $"Assert.AreNotEqual failed. Both are <{actual}>."); + } + + public static void Greater(long actual, long expected, string? message = null) + { + if (actual <= expected) + throw new Exception(message ?? $"Assert.Greater failed. Actual:{actual} Expected greater than:{expected}."); + } + } +} + +namespace AsposePdfTests +{ + [TestFixture] + public class PdfImageModificationTests + { + // Minimal PNG (1x1 pixel, transparent) byte array + private static readonly byte[] MinimalPng = new byte[] + { + 0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A, + 0x00,0x00,0x00,0x0D,0x49,0x48,0x44,0x52, + 0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01, + 0x08,0x06,0x00,0x00,0x00,0x1F,0x15,0xC4, + 0x89,0x00,0x00,0x00,0x0A,0x49,0x44,0x41, + 0x54,0x78,0x9C,0x63,0x60,0x00,0x00,0x00, + 0x02,0x00,0x01,0xE2,0x21,0xBC,0x33,0x00, + 0x00,0x00,0x00,0x49,0x45,0x4E,0x44,0xAE, + 0x42,0x60,0x82 + }; + + private string? _tempDirectory; + private string? _originalPdfPath; + private string? _imagePath; + private string? _modifiedPdfPath; + + [SetUp] + public void SetUp() + { + // Create a temporary directory for test files + _tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(_tempDirectory!); + + // Paths for files + _originalPdfPath = Path.Combine(_tempDirectory, "original.pdf"); + _imagePath = Path.Combine(_tempDirectory, "test.png"); + _modifiedPdfPath = Path.Combine(_tempDirectory, "modified.pdf"); + + // Write the minimal PNG to disk + File.WriteAllBytes(_imagePath, MinimalPng); + + // Create a blank PDF with a single page and save it + using (Document doc = new Document()) + { + doc.Pages.Add(); // 1‑based indexing + doc.Save(_originalPdfPath); + } + } + + [TearDown] + public void TearDown() + { + // Clean up temporary files and directory + try + { + if (!string.IsNullOrEmpty(_tempDirectory) && Directory.Exists(_tempDirectory)) + { + Directory.Delete(_tempDirectory, true); + } + } + catch + { + // Ignored – best effort cleanup + } + } + + [Test] + public void AddingImageIncreasesPdfByteSize() + { + // Load original PDF into a Document instance + using (Document originalDoc = new Document(_originalPdfPath!)) + { + // Record original size + long originalSize; + using (MemoryStream ms = new MemoryStream()) + { + originalDoc.Save(ms); + originalSize = ms.Length; + } + + // Use PdfFileMend to add an image to page 1 + using (PdfFileMend mender = new PdfFileMend(originalDoc)) + { + // Add the PNG image at coordinates (10,10) to (100,100) + bool added = mender.AddImage(_imagePath!, 1, 10f, 10f, 100f, 100f); + Assert.IsTrue(added, "Image should be added successfully."); + mender.Close(); // Ensure changes are flushed + } + + // Save the modified document + originalDoc.Save(_modifiedPdfPath!); + + // Get modified size + long modifiedSize; + using (MemoryStream ms = new MemoryStream()) + { + originalDoc.Save(ms); + modifiedSize = ms.Length; + } + + // Verify that the size has increased + Assert.AreNotEqual(originalSize, modifiedSize, "PDF size should change after adding an image."); + Assert.Greater(modifiedSize, originalSize, "Modified PDF should be larger than the original."); + } + } + } + + // Dummy entry point to satisfy the compiler when the project is built as an executable. + public static class Program + { + public static void Main() { /* No‑op */ } + } +}