Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions facades-texts-and-images/add-background-image-to-all-pdf-pages.cs
Original file line number Diff line number Diff line change
@@ -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}'.");
}
}
65 changes: 65 additions & 0 deletions facades-texts-and-images/add-header-image-to-pdf.cs
Original file line number Diff line number Diff line change
@@ -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: <headerImagePath> <pdfPath1> [<pdfPath2> ...]");
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}");
}
}
}
}
72 changes: 72 additions & 0 deletions facades-texts-and-images/add-image-and-text-to-pdf-with-logging.cs
Original file line number Diff line number Diff line change
@@ -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}'.");
}
}
47 changes: 47 additions & 0 deletions facades-texts-and-images/add-image-stamp-to-pdf-with-cleanup.cs
Original file line number Diff line number Diff line change
@@ -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}'.");
}
}
Original file line number Diff line number Diff line change
@@ -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}'.");
}
}
59 changes: 59 additions & 0 deletions facades-texts-and-images/add-image-to-pdf-page.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System;
using System.IO;
using Aspose.Pdf.Facades;

public static class PdfHelper
{
/// <summary>
/// Adds an image to a specific page of a PDF file at the given rectangle coordinates.
/// </summary>
/// <param name="inputPdfPath">Path to the source PDF.</param>
/// <param name="outputPdfPath">Path where the modified PDF will be saved.</param>
/// <param name="imagePath">Path to the image file to be added.</param>
/// <param name="pageNumber">1‑based page number where the image will be placed.</param>
/// <param name="lowerLeftX">Lower‑left X coordinate of the image rectangle.</param>
/// <param name="lowerLeftY">Lower‑left Y coordinate of the image rectangle.</param>
/// <param name="upperRightX">Upper‑right X coordinate of the image rectangle.</param>
/// <param name="upperRightY">Upper‑right Y coordinate of the image rectangle.</param>
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.
}
}
Loading
Loading