Wednesday, February 23, 2011

Merge dynamically create PDF at runtime

I played with this more than 3 days. Finally got the solution.


protected void Button1_Click(object sender, EventArgs e)
{
 Guid uniqueid = Guid.NewGuid();
 string uniqueidStr = uniqueid.ToString();
 int cnt = 0;
 string file = Server.MapPath("~/Admin/doc/invoice/Invoice.pdf");
 string masterPDfFile = Server.MapPath("~/Admin/doc/invoice/result.pdf");
 PdfCopyFields myPdfCopy = new PdfCopyFields(new FileStream(masterPDfFile, FileMode.Create));

while (cnt < 3)
{
PdfReader tmpReader = new PdfReader(file);
string tmpFilePath = Server.MapPath("~/Admin/doc/invoice/" +uniqueidStr+ cnt.ToString() + ".pdf");
FileStream tmppoutputFile = new FileStream(tmpFilePath, FileMode.Create);
PdfStamper tmpoutStamper = new PdfStamper(tmpReader, tmppoutputFile);
AcroFields testform = tmpoutStamper.AcroFields;
testform.SetField("T1","Lasantha");
tmpoutStamper.Close();
PdfReader nwpgReader = new PdfReader(tmpFilePath);
PdfTemplate page = tmpoutStamper.GetImportedPage(nwpgReader, 1);
myPdfCopy.AddDocument(nwpgReader);
cnt += 1;
}

myPdfCopy.Close();
cnt = 0;

while (cnt < 3)
{
string tmpFilePath = Server.MapPath("~/Admin/doc/invoice/" + uniqueidStr+cnt.ToString() + ".pdf");
System.IO.File.Delete(tmpFilePath);
cnt += 1;
}

 PdfReader reader = new PdfReader(masterPDfFile);
string resultpath = Server.MapPath("~/Admin/doc/CustomerReports/result.pdf");
 FileStream resultstr=new FileStream(resultpath,FileMode.Create);
PdfStamper result = new PdfStamper(reader, resultstr);
result.Close();
reader.Close();
System.IO.File.Delete(masterPDfFile);
} 

No comments:

Post a Comment

TinyMCE Insert/Edit link not editable

 To fix this add  e.stopImmediatePropagation()  as below. $(document).on('focusin', function (e) {             if ($(e.target).close...