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
43 changes: 43 additions & 0 deletions working-with-attachments/add-attachment-to-protected-pdf.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.IO;
using Aspose.Pdf;

class Program
{
static void Main()
{
// Paths and credentials
const string inputPdf = "protected.pdf";
const string outputPdf = "protected_with_attachment.pdf";
const string userPassword = "user123";
const string attachmentFile = "attachment.txt";
const string attachmentDescription = "Sample attachment";

// Validate input files
if (!File.Exists(inputPdf))
{
Console.Error.WriteLine($"Input PDF not found: {inputPdf}");
return;
}
if (!File.Exists(attachmentFile))
{
Console.Error.WriteLine($"Attachment file not found: {attachmentFile}");
return;
}

// Open the encrypted PDF using the correct password
using (Document doc = new Document(inputPdf, userPassword))
{
// Create a FileSpecification for the attachment
FileSpecification fileSpec = new FileSpecification(attachmentFile, attachmentDescription);

// Add the attachment to the document's EmbeddedFiles collection
doc.EmbeddedFiles.Add(fileSpec);

// Save the updated PDF (encryption is preserved)
doc.Save(outputPdf);
}

Console.WriteLine($"Attachment added and saved to '{outputPdf}'.");
}
}
54 changes: 54 additions & 0 deletions working-with-attachments/add-attachments-to-pdf-save-output.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System;
using System.IO;
using Aspose.Pdf;

class Program
{
static void Main()
{
// Input PDF file
const string inputPdfPath = "input.pdf";

// Directory where the output PDF will be saved
const string outputDirectory = "output";

// Files to be added as attachments to the PDF
string[] attachmentFiles = { "attach1.txt", "attach2.jpg" };

// Ensure the input PDF exists
if (!File.Exists(inputPdfPath))
{
Console.Error.WriteLine($"Input PDF not found: {inputPdfPath}");
return;
}

// Load the PDF document (using statement ensures proper disposal)
using (Document pdfDocument = new Document(inputPdfPath))
{
// Add each existing file as an embedded file (attachment)
foreach (string filePath in attachmentFiles)
{
if (!File.Exists(filePath))
{
Console.Error.WriteLine($"Attachment file not found: {filePath}");
continue;
}

// Create a FileSpecification for the attachment and add it to the document's EmbeddedFiles collection
FileSpecification attachment = new FileSpecification(filePath);
pdfDocument.EmbeddedFiles.Add(attachment);
}

// Ensure the output directory exists
Directory.CreateDirectory(outputDirectory);

// Build the full output file path
string outputPdfPath = Path.Combine(outputDirectory, "output_with_attachments.pdf");

// Save the modified PDF to the specified location
pdfDocument.Save(outputPdfPath);
}

Console.WriteLine("PDF saved with attachments.");
}
}
58 changes: 58 additions & 0 deletions working-with-attachments/add-file-attachment-to-pdf.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using System;
using System.IO;
using Aspose.Pdf;
using Aspose.Pdf.Annotations;

class Program
{
static void Main()
{
const string inputPdf = "input.pdf";
const string outputPdf = "output.pdf";
const string attachmentFile = "attachment.txt";

if (!File.Exists(inputPdf))
{
Console.Error.WriteLine($"Input PDF not found: {inputPdf}");
return;
}

if (!File.Exists(attachmentFile))
{
Console.Error.WriteLine($"Attachment file not found: {attachmentFile}");
return;
}

// Load the existing PDF document
using (Document doc = new Document(inputPdf))
{
// Create a FileSpecification for the attachment
FileSpecification fileSpec = new FileSpecification(attachmentFile);

// Add the file specification to the document's embedded files collection
doc.EmbeddedFiles.Add(fileSpec);

// Select the page where the annotation will be placed (first page)
Page page = doc.Pages[1];

// Define the rectangle that bounds the annotation
Aspose.Pdf.Rectangle rect = new Aspose.Pdf.Rectangle(100, 500, 200, 550);

// Create the file attachment annotation using the page, rectangle, and file specification
FileAttachmentAnnotation attachment = new FileAttachmentAnnotation(page, rect, fileSpec)
{
// Optional visual properties
Contents = "Attached file",
Color = Aspose.Pdf.Color.Blue
};

// Add the annotation to the page's annotation collection
page.Annotations.Add(attachment);

// Save the modified PDF to a new file
doc.Save(outputPdf);
}

Console.WriteLine($"File attachment added and saved to '{outputPdf}'.");
}
}
76 changes: 76 additions & 0 deletions working-with-attachments/add-file-attachment-to-pdf__v2.cs
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.Annotations;

class Program
{
static void Main()
{
const string pdfPath = "input.pdf";
const string attachmentPath = "attachment.txt";
const string outputPath = "output.pdf";

// Verify the source PDF exists
if (!File.Exists(pdfPath))
{
Console.Error.WriteLine($"PDF file not found: {pdfPath}");
return;
}

try
{
// Load the PDF (lifecycle: using block ensures disposal)
using (Document doc = new Document(pdfPath))
{
// Use the first page for the attachment annotation
Page page = doc.Pages[1];

// Define the rectangle for the attachment icon (fully qualified to avoid ambiguity)
Aspose.Pdf.Rectangle rect = new Aspose.Pdf.Rectangle(100, 500, 120, 520);

// Check that the file to be attached exists
if (!File.Exists(attachmentPath))
{
Console.Error.WriteLine($"Attachment file not found: {attachmentPath}");
}
else
{
// Create a file specification for the attachment
FileSpecification fileSpec = new FileSpecification(attachmentPath);

// Create the file attachment annotation
FileAttachmentAnnotation attachment = new FileAttachmentAnnotation(page, rect, fileSpec)
{
// Use the correct enum for the icon
Icon = FileIcon.Paperclip,
Contents = "Attached file",
Title = "Attachment"
};

// Add the annotation to the page
page.Annotations.Add(attachment);
}

// Save the modified PDF (lifecycle: save inside using block)
doc.Save(outputPath);
Console.WriteLine($"PDF saved to '{outputPath}'.");
}
}
catch (FileNotFoundException ex)
{
// Handles missing files for both PDF and attachment
Console.Error.WriteLine($"File not found: {ex.FileName}");
}
catch (PdfException ex)
{
// Handles errors specific to Aspose.Pdf operations
Console.Error.WriteLine($"PDF error: {ex.Message}");
}
catch (Exception ex)
{
// Catch‑all for any other unexpected errors
Console.Error.WriteLine($"Unexpected error: {ex.Message}");
}
}
}
98 changes: 98 additions & 0 deletions working-with-attachments/add-file-attachment-with-retry.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System;
using System.IO;
using System.Threading;
using Aspose.Pdf;
using Aspose.Pdf.Annotations;

class PdfAttachmentHelper
{
// Adds a file attachment to the first page of a PDF.
// Retries the whole operation if a transient I/O error occurs.
public static void AddAttachmentWithRetry(
string pdfPath,
string attachmentFilePath,
string outputPath,
int maxRetries = 3,
int initialDelayMs = 500)
{
if (!File.Exists(pdfPath))
throw new FileNotFoundException($"PDF not found: {pdfPath}");

if (!File.Exists(attachmentFilePath))
throw new FileNotFoundException($"Attachment not found: {attachmentFilePath}");

int attempt = 0;
int delay = initialDelayMs;

while (true)
{
try
{
// Load the PDF (lifecycle rule: use Document constructor)
using (Document doc = new Document(pdfPath))
{
// Create a file specification for the attachment
FileSpecification fileSpec = new FileSpecification(attachmentFilePath);

// Define the rectangle where the attachment icon will appear
Aspose.Pdf.Rectangle rect = new Aspose.Pdf.Rectangle(100, 100, 200, 200);

// Get the first page (Aspose.Pdf uses 1‑based indexing)
Page page = doc.Pages[1];

// Create the attachment annotation and add it to the page
FileAttachmentAnnotation attachment = new FileAttachmentAnnotation(page, rect, fileSpec);
page.Annotations.Add(attachment);

// Save the modified PDF (lifecycle rule: use Document.Save)
doc.Save(outputPath);
}

// If we reach this point the operation succeeded
break;
}
catch (IOException ex) when (attempt < maxRetries)
{
// Transient I/O error – wait and retry
attempt++;
Console.Error.WriteLine($"I/O error on attempt {attempt}: {ex.Message}. Retrying in {delay} ms...");
Thread.Sleep(delay);
delay *= 2; // exponential back‑off
}
catch (UnauthorizedAccessException ex) when (attempt < maxRetries)
{
// Access issue – also retry (e.g., temporary lock on network share)
attempt++;
Console.Error.WriteLine($"Access error on attempt {attempt}: {ex.Message}. Retrying in {delay} ms...");
Thread.Sleep(delay);
delay *= 2;
}
catch
{
// Non‑recoverable exception – rethrow
throw;
}
}
}
}

// Example usage
class Program
{
static void Main()
{
const string networkPdf = @"\\fileserver\share\documents\sample.pdf";
const string attachment = @"C:\Temp\info.txt";
const string outputPdf = @"\\fileserver\share\documents\sample_with_attachment.pdf";

try
{
PdfAttachmentHelper.AddAttachmentWithRetry(networkPdf, attachment, outputPdf);
Console.WriteLine("Attachment added successfully.");
}
catch (Exception ex)
{
Console.Error.WriteLine($"Failed to add attachment: {ex.Message}");
}
}
}
47 changes: 47 additions & 0 deletions working-with-attachments/add-in-memory-attachment-to-pdf.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.IO;
using Aspose.Pdf; // Core PDF API
using Aspose.Pdf.Tagged; // For ITaggedContent if needed (not used here)

class Program
{
static void Main()
{
// Path to the source PDF (must exist)
const string inputPdfPath = "input.pdf";
// Path where the resulting PDF with the attachment will be saved
const string outputPdfPath = "output_with_attachment.pdf";

if (!File.Exists(inputPdfPath))
{
Console.Error.WriteLine($"Source PDF not found: {inputPdfPath}");
return;
}

// Create a memory stream containing the data to be attached.
// Here we embed a simple text file; replace the content as needed.
byte[] attachmentData = System.Text.Encoding.UTF8.GetBytes("This is the content of the in‑memory attachment.");
using (MemoryStream attachmentStream = new MemoryStream(attachmentData))
{
// Ensure the stream position is at the beginning before using it.
attachmentStream.Position = 0;

// Open the existing PDF inside a using block for deterministic disposal.
using (Document doc = new Document(inputPdfPath))
{
// The FileSpecification constructor expects (Stream, string).
// The first argument is the stream containing the file data,
// the second argument is the name that will appear in the PDF attachment list.
FileSpecification fileSpec = new FileSpecification(attachmentStream, "SampleAttachment.txt");

// Add the file specification to the document's embedded files collection.
doc.EmbeddedFiles.Add(fileSpec);

// Save the modified PDF to the desired output path.
doc.Save(outputPdfPath);
}
}

Console.WriteLine($"PDF saved with in‑memory attachment: {outputPdfPath}");
}
}
Loading
Loading