Click here to Skip to main content
15,884,237 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hi Everyone,

What I'm doing is that, I'm opening a template PDF file, adding my required changes and saving this new file. I'm making use of Itextsharp to read from the template file and to modify the new file.

The first time I generate the file, all goes well. However, if I try to generate again this file in succession, I see an error message stating that the new file is being used by another process. However, if I refresh the page and try again, this will succeed.

I know that I should release all objects, however I believe that either this is not enough or I'm doing something wrong. Any help would be greatly appreciated!

C#
string fileName = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("data"), company.ID.ToString(), "myNewFile.PDF");
string templateFile = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("data\\templates"), "template.pdf");

using (var ms = new FileStream(fileName, FileMode.Create))
{
	using (var doc = new Document())
	{
		using (var copy = new PdfCopy(doc, ms))
		{
			doc.Open();
			PdfReader reader = null;
			
			try
			{
				reader = new PdfReader(templateFile);
				var pages = 2;// reader.NumberOfPages;

				for (int pageNumber = 1; pageNumber <= pages; ++pageNumber)
				{
					var page = copy.GetImportedPage(reader, pageNumber);
					var stamp = copy.CreatePageStamp(page);

					var f = new Font(Font.FontFamily.TIMES_ROMAN, 9f);
					f.Color = BaseColor.BLACK;
					var p = new Phrase();

					switch (pageNumber)
					{

						case 1:
							//code to make changes on page one
							break;

						case 2:
							//code to make changes on page two
							break;
					}

					stamp.AlterContents();
					copy.AddPage(page);
				}
			}
			catch (Exception ex)
			{
				_log.Error("Error while SUFGenerateFSkattDocument. Error Message: " + ex.Message);
				_log.Error("Full Error Details: " + ex.ToString());
			}
			finally
			{
				if (reader != null)
					reader.Close();
			}
			
			doc.CloseDocument();
			doc.Close();
			doc.Dispose();

			copy.Close();
			copy.Dispose();
		}
	}
	ms.Close();
	ms.Dispose();
}


Full Code Listing:
C#
string fileName = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("data"), company.ID.ToString(), FSkattDocument);
            string templateFile = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("data\\templates"), FSkattDocument);

            PdfReader.unethicalreading = true;

            if (File.Exists(fileName))
                File.Delete(fileName);

            CheckFolderExists(fileName);

            using (var ms = new FileStream(fileName, FileMode.Create))
            {
                using (var doc = new Document())
                {
                    using (var copy = new PdfCopy(doc, ms))
                    {
                        doc.Open();
                        PdfReader reader = null;

                        try
                        {
                            reader = new PdfReader(templateFile);
                            var pages = 2;// reader.NumberOfPages;

                            for (int pageNumber = 1; pageNumber <= pages; ++pageNumber)
                            {
                                var page = copy.GetImportedPage(reader, pageNumber);
                                var stamp = copy.CreatePageStamp(page);

                                var f = new Font(Font.FontFamily.TIMES_ROMAN, 9f);
                                f.Color = BaseColor.BLACK;
                                var p = new Phrase();

                                switch (pageNumber)
                                {

                                    case 1:
                                        #region Page 1

                                        float xPoint = 68f;

                                        if ((fskatt.FSkattType & 1) != 0)
                                        {
                                            p = new Phrase("X", f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 68f, 740f, 0f);
                                        }
                                        if ((fskatt.FSkattType & 2) != 0)
                                        {
                                            p = new Phrase("X", f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 161f, 740f, 0f);
                                        }
                                        if ((fskatt.FSkattType & 4) != 0)
                                        {
                                            p = new Phrase("X", f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 261f, 740f, 0f);
                                        }
                                        if ((fskatt.FSkattType & 8) != 0)
                                        {
                                            p = new Phrase("X", f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 455f, 740f, 0f);
                                        }

                                        p = new Phrase(company.Name.ToUpperInvariant(), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 70f, 695f, 0f);

                                        p = new Phrase(ceo.SocialSecurityNumber, f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 455f, 695f, 0f);

                                        p = new Phrase(company.Address.ToUpperInvariant(), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 70f, 671f, 0f);

                                        p = new Phrase(company.ZipCode.ToUpperInvariant(), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 70f, 658f, 0f);

                                        p = new Phrase(company.City.ToUpperInvariant(), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 70f, 645f, 0f);

                                        p = new Phrase("X", f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 261f, 596f, 0f);

                                        p = new Phrase(String.Format("1/1-{0}-31/12-{0}", DateTime.Today.Year), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 455f, 575f, 0f);

                                        p = new Phrase(company.Address.ToUpperInvariant(), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 70f, 550f, 0f);

                                        p = new Phrase(company.ZipCode.ToUpperInvariant() + " " + company.City.ToUpperInvariant(), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 70f, 537f, 0f);

                                        p = new Phrase(fskatt.ActivityDesc1, f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 70f, 430f, 0f);

                                        p = new Phrase(fskatt.ActivityPct1.ToString(), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 455f, 430f, 0f);

                                        p = new Phrase(fskatt.ActivityDesc2, f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 70f, 407f, 0f);

                                        p = new Phrase(fskatt.ActivityPct2.ToString(), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 455f, 407f, 0f);

                                        p = new Phrase(fskatt.ActivityDesc3, f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 70f, 382f, 0f);

                                        p = new Phrase(fskatt.ActivityPct3.ToString(), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 455f, 382f, 0f);

                                        var lines = App_Code.CHelper.FormatString(company.Description, 140);
                                        float yPoint = 285;

                                        foreach (var line in lines)
                                        {
                                            p = new Phrase(line, f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 70f, yPoint, 0f);

                                            yPoint -= 11f;
                                        }

                                        yPoint = 118f;

                                        foreach (var sh in personShareHolders)
                                        {
                                            p = new Phrase(sh.Name, f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 70f, yPoint, 0f);

                                            p = new Phrase(sh.SocialSecurityNumber, f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 390f, yPoint, 0f);

                                            var shareAmount = sharesPerHolder.First(x => x.ShareHolderID == sh.ID).Shares.ToString();

                                            p = new Phrase(shareAmount, f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 520f, yPoint, 0f);

                                            yPoint -= 24f;
                                        }

                                        foreach (var sh in companyShareHolders)
                                        {
                                            p = new Phrase(sh.Name, f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 70f, yPoint, 0f);

                                            p = new Phrase(sh.CompanyNumber, f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 390f, yPoint, 0f);

                                            var shareAmount = sharesPerHolder.First(x => x.ShareHolderID == sh.ID).Shares.ToString();

                                            p = new Phrase(shareAmount, f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 520f, yPoint, 0f);

                                            yPoint -= 24f;
                                        }

                                        #endregion
                                        break;

                                    case 2:
                                        #region Page 2

                                        if ((fskatt.FSkattType & 4) != 0) //fill section F
                                        {
                                            p = new Phrase(fskatt.FirstSalary.ToString(), f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 70f, 812f, 0f);

                                            p = new Phrase("12", f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 70f, 787f, 0f);

                                            p = new Phrase(fskatt.AmountOfEmployees.ToString(), f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 250f, 787f, 0f);

                                            p = new Phrase(fskatt.SalaryAmount.ToString(), f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 422f, 787f, 0f);
                                        }

                                        if ((fskatt.FSkattType & 8) != 0) //fill section G
                                        {
                                            p = new Phrase(fskatt.VatStartDate.Value.ToString("dd/MM/yyyy"), f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 70f, 695f, 0f);

                                            p = new Phrase(fskatt.Turnover.ToString(), f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 205f, 695f, 0f);

                                            xPoint = 69f;

                                            if (fskatt.AccountingPeriod == 1)
                                                xPoint = 140f;
                                            else if (fskatt.AccountingPeriod == 2)
                                                xPoint = 219f;

                                            p = new Phrase("X", f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, xPoint, 655f, 0f);

                                            ColumnText.ShowTextAligned(
                                                stamp.GetOverContent(), Element.ALIGN_LEFT,
                                                p, 69f, 620f, 0f);
                                        }

                                        p = new Phrase(fskatt.Profit.ToString(), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 70f, 513f, 0f);

                                        p = new Phrase(ceo.Name.ToUpperInvariant(), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 70f, 178f, 0f);

                                        p = new Phrase(ceo.Telephone, f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 350f, 200f, 0f);

                                        p = new Phrase(ceo.Email, f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 350f, 178f, 0f);

                                        p = new Phrase(DateTime.Today.ToString("dd/MM/yyyy"), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 70f, 45f, 0f);

                                        p = new Phrase(ceo.Name.ToUpperInvariant(), f);

                                        ColumnText.ShowTextAligned(
                                            stamp.GetOverContent(), Element.ALIGN_LEFT,
                                            p, 162f, 45f, 0f);

                                        #endregion
                                        break;
                                }

                                stamp.AlterContents();
                                copy.AddPage(page);
                            }
                        }
                        catch (Exception ex)
                        {
                            _log.Error("Error while SUFGenerateFSkattDocument. Error Message: " + ex.Message);
                            _log.Error("Full Error Details: " + ex.ToString());
                        }
                        finally
                        {
                            if (reader != null)
                                reader.Close();
                        }

                        ms.Flush(true);
                        copy.Close();
                        copy.Dispose();
                    }

                    doc.CloseDocument();
                    doc.Close();
                    doc.Dispose();
                }

                
                ms.Close();
                ms.Dispose();
            }
Posted
Updated 1-Jul-15 2:07am
v4
Comments
Kornfeld Eliyahu Peter 1-Jul-15 7:10am    
Debug your code and see if you are actually close all the streams you have opened...
Also check the order...
Ryan Zahra 1-Jul-15 7:19am    
As far as I know I believe that I'm closing all streams in the correct order.
Rob Philpott 1-Jul-15 7:21am    
Well, the filestream appears to being disposed of properly, so at that point I'd expect you to be free.

My guess is that the method is getting called twice at the same time, at which point the filestream becomes a contentious object. Easy to check with breakpoints or a bit of debug output.
Ryan Zahra 1-Jul-15 7:28am    
I'm sure that the method is being called only once because this method will fire on a button click event. I check again by adding a breakpoint at this code and the execution enters this piece of code only once.
virusstorm 1-Jul-15 7:54am    
How big of a file are we talking? I'm wondering if your issue is the FileStream object hasn't finished flushing the stream to disk. I noticed that you always use the same file name. I don't recommend this as two users making the same request will generate an error for one of them. Every time the button is clicked, generate a unique file name (a Guid is quick and easy). To clean up the files, if needed, simply add a clean up routine that looks for old files safe to delete or write a service that keeps the directory clean.

1 solution

 
Share this answer
 
Comments
Ryan Zahra 2-Jul-15 4:01am    
Thanks for the detailed explanation. I know that I need to dispose of all resources however I believe that I'm still missing something here but I don't know what I'm missing. I used the handle.exe tool and sure enough, the process that is locking my file is iisexpress.exe, since I'm testing this on my local machine. At this point, I suspect that it could be something that I'm not disposing from the itextsharp library, however, I don't know what. Any pointers would be really helpful! Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900