Posts tagged C#

Merge pdf files using C#

27

Recently I had to create an assembly component using C# to merge multiple PDF files into one file. The specification was pretty straight forward:
1) Merge two of more PDF document into a single output PDF File.
2) Used on an ASP.NET Page

After a few minutes of GOOG, I came up to this “ITextSharp

iText# (iTextSharp) is a port of the iText open source java library written entirely in C# for the .NET platform. iText# is a library that allows you to generate PDF files on the fly. It is implemented as an assembly.

It must be noted that the assembly is coded and compiled using the .NET Framework 1.1. You might want to migrate to the version 2.0 or 3.5 of the .NET Framework.

With a some more research on PDF merging. I was able to create a class that will make use of the ITextSharp assembly and perform as the merge pdf operation as needed.

Here is the code:

using iTextSharp.text;
using iTextSharp.text.pdf;

public class MergeEx
{
#region Fields
private string sourcefolder;
private string destinationfile;
private IList fileList = new ArrayList();
#endregion

#region Public Methods
///
/// Add a new file, together with a given docname to the fileList and namelist collection
///
public void AddFile(string pathnname)
{
fileList.Add(pathnname);
}

///
/// Generate the merged PDF
///
public void Execute()
{
MergeDocs();
}
#endregion

#region Private Methods
///
/// Merges the Docs and renders the destinationFile
///
private void MergeDocs()
{

//Step 1: Create a Docuement-Object
Document document = new Document();
try
{
//Step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationfile, FileMode.Create));

//Step 3: Open the document
document.Open();

PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;

int n = 0;
int rotation = 0;

//Loops for each file that has been listed
foreach (string filename in fileList)
{
//The current file path
string filePath = sourcefolder + filename;

// we create a reader for the document
PdfReader reader = new PdfReader(filePath);

//Gets the number of pages to process
n = reader.NumberOfPages;

int i = 0;
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(1));
document.NewPage();

//Insert to Destination on the first page
if (i == 1)
{
Chunk fileRef = new Chunk(" ");
fileRef.SetLocalDestination(filename);
document.Add(fileRef);
}

page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
}
}
catch (Exception e) { throw e; }
finally { document.Close(); }
}
#endregion

#region Properties
///
/// Gets or Sets the SourceFolder
///
public string SourceFolder
{
get { return sourcefolder; }
set {sourcefolder = value; }
}

///
/// Gets or Sets the DestinationFile
///
public string DestinationFile
{
get { return destinationfile; }
set { destinationfile = value; }
}
#endregion
}

To use the MergeEx class:
1) Initialize the class
2) Set the SourceFolder and DestinationFile properties
3) Using the AddFile method, add the source file names that need to be merged (Filename only since the SourceFolder has already been set)
4) Call the Execute Method

If everything works fine you will find your Merged PDF Document at your stated destination file.

The code is pretty much self decribed. If there is any question, i can always be contacted via this post.

Copy-Clone custom object in C#

1

This post relates how to Copy/Clone custom object in C# (Deep and Shallow Clone).

In this example I will be having a base class that all my custom object will be inheriting from.

Updates: After quiet some research on the subject i recently found some interesting articles on this subject and wanted to share them on this post.

Object Cloning Using IL in C#

This subject is inspired on a session I followed on the TechDays 2008,
that addressed the fact that IL (Intermediate Language) can be used to clone objects, among other things, and that it’s not evil at all, and it can be pretty performant also.

You only have to see that you don’t overuse it tho, because otherwise the readability of your code is reduced, which is not a good thing for the maintenance.
And wrong usage of reflection (what IL is, or at least uses) can also result in poor performance.

Read more:
http://whizzodev.blogspot.com/2008/03/object-cloning-using-il-in-c.html

C# Class For Making a Deep Copy Clone of an Arbitrary Object

Here is a C# class that can create a deep copy clone of an arbitrary object. The thing that’s special about it is that it should work for any class that extends it, so that you don’t need to re-write a custom clone() function for every child class (as it seems the C# framework creators would like). This does a deep copy so be careful about members that recursively include one another.

Another way of doing this would be to use serialization . . . I just personally thought the reflection package would be more elegant.

Read more:
http://www.thomashapp.com/node/106

C# Object Clone Wars

Cloning C# objects is one of those things that appears easy but is actually quite complicated with many “gotchas.” This article describes the most common ways to clone a C# object.

Shallow vs. Deep Cloning

There are two types of object cloning: shallow and deep. A shallow clone copies the references but not the referenced objects. A deep clone copies the referenced objects as well.

hallow vs Deep Cloning

shallow vs Deep Cloning

Read more:
http://www.csharp411.com/c-object-clone-wars/

Clone C# Object using Serialization and De-serialization (Deep Clone)

In this example i’ll be using Serialization and De-Serialization to make a deep clone of the Person Class.

You must import the following namespaces to start with.

using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.IO;

Let’s create a base class Person that all our other classes with inherit from. It will contain the following methods:

  • ToXMLString() : Returns an XML version of the current object
  • Deserialize(XmlDocument xml, Type type) : De-serialize the current XMLDocument cast it to the current type
  • Serialize(object o) : Serialize the current object and outputs an XMLDocument
  • Clone(): Runs a Serialization and De-serialization and returns a clone of the current Object
[Serializable()]
public abstract class Person
{
/// <summary>
/// To XML string.
/// </summary>
/// <returns></returns>
public string ToXMLString()
{
XmlSerializer serializer = new XmlSerializer(this.GetType());
MemoryStream dataStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(dataStream, Encoding.UTF8);
serializer.Serialize(dataStream, this);
return writer.ToString();
}

/// <summary>
/// Deserializes an xml document back into an object
/// </summary>
/// <param name="xml">The xml data to deserialize</param>
/// <param name="type">The type of the object being deserialized</param>
/// <returns>A deserialized object</returns>
public static object Deserialize(XmlDocument xml, Type type)
{
XmlSerializer s = new XmlSerializer(type);
string xmlString = xml.OuterXml.ToString();
byte[] buffer = ASCIIEncoding.UTF8.GetBytes(xmlString);
MemoryStream ms = new MemoryStream(buffer);
XmlReader reader = new XmlTextReader(ms);
Exception caught = null;

try
{
object o = s.Deserialize(reader);
return o;
}

catch (Exception e)
{
caught = e;
}
finally
{
reader.Close();

if (caught != null)
throw caught;
}
return null;
}

/// <summary>
/// Serializes an object into an Xml Document
/// </summary>
/// <param name="o">The object to serialize</param>
/// <returns>An Xml Document consisting of said object's data</returns>
public static XmlDocument Serialize(object o)
{
XmlSerializer s = new XmlSerializer(o.GetType());

MemoryStream ms = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(ms, new UTF8Encoding());
writer.Formatting = Formatting.Indented;
writer.IndentChar = ' ';
writer.Indentation = 5;
Exception caught = null;

try
{
s.Serialize(writer, o);
XmlDocument xml = new XmlDocument();
string xmlString = ASCIIEncoding.UTF8.GetString(ms.ToArray());
xml.LoadXml(xmlString);
return xml;
}
catch (Exception e)
{
caught = e;
}
finally
{
writer.Close();
ms.Close();

if (caught != null)
throw caught;
}
return null;
}

/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public object Clone()
{
return Deserialize(Serialize(this), this.GetType());
}
}

Here are sample classes that herits from the abstract base class and clone operation are performed upon them.


public class Clerk: Person
{
private string position;

/// <summary>
/// Gets or sets the position.
/// </summary>
/// <value>The position.</value>
public string Position
{
get { return position; }
set { position = value; }
}
}

public class Developer: Person
{
private string skill;

/// <summary>
/// Gets or sets the skill.
/// </summary>
/// <value>The skill.</value>
public string Skill
{
get { return skill; }
set { skill= value; }
}
}

Using clone method.


public void UpdateSkills()
{
IList<clerk> clerkList = new ArrayList();
IList<clerk> newClerkList = new ArrayList();

foreach (Clerk clerk in clerkList)
{
newClerkList.Add((Clerk)clerk.Clone());
}
}

Exception: Collection was modified; enumeration operation may not execute.

0

It’s been a while that i didn’t get this Exception, while working, and yesterday, while I was performing some test on a new module that I implemented i got this exception. I knew i did get it sometimes back last year, and managed to solve it. So here is one solution when you are dealing with this kind of issue:


IList<Product> productList = new List<Product>();
productList.Add(new Product("Some product 1");
productList.Add(new Product("Some product 2");
productList.Add(new Product("Some product 3");
productList.Add(new Product("Some product 4");


for(int i=(productList.Count -1); i >= 0; i--)
{
//Perform Edit, Update, Delete Operation using for .. i loop in reverse order
}

There is a list of other solutions that can be found on the following websites:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=372532&SiteID=1
http://forums.asp.net/p/1147145/1861164.aspx
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/ASP_DOT_NET/Q_21585534.html

Copy custom object in C#

0

There are several ways to clone custom object in .NET.

  • Using reflection to get information about each field and properties in the custom class, create a new instance and assign the proper value.
  • Manually implementing the clone method and assign each field and method and then return a new object
  • Using serialization and deserialization.

I have tried the third method, that can be found here, it seems to be working fine for the time being, more test need to be done for performance overhead.

Go to Top