You can optimize the code.It is bit scrambbeled.
RemoveText();
string strSource = "D:\\test.pdf";
CreatePDFTemplateMSnew(strSource);
public void RemoveText()
{
string outputFilePath = "D:\\test.pdf";
string inputFilePath = "D:\\input.pdf";
try
{
using (Stream inputPdfStream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream outputPdfStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
using (Stream outputPdfStream2 = new FileStream(outputFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
PdfReader reader = new PdfReader(inputPdfStream);
PdfStamper stamper = new PdfStamper(reader, outputPdfStream);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(new Bitmap(130, 20), BaseColor.WHITE);
image.SetAbsolutePosition(Convert.ToInt16(txtX.Text), Convert.ToInt16(txtY.Text));
stamper.GetOverContent(1).AddImage(image, true);
stamper.Close();
}
}
catch (Exception ex)
{
}
}
private void CreatePDFTemplateMSnew(string strSource)
{
string oldFile = strSource;
PdfReader reader = new PdfReader(oldFile);
iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
PdfContentByte cb = writer.DirectContent;
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 12);
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
cb.BeginText();
string text = txtText.Text;
int intAlign = Convert.ToInt16(txtAlign.Text);
int intX = Convert.ToInt16(txtX.Text);
int intY = Convert.ToInt16(txtY.Text);
int intRotation = Convert.ToInt16(txtRotation.Text);
cb.ShowTextAligned(intAlign, text, intX, intY, intRotation);
cb.EndText();
writer.CloseStream = false;
if (document.IsOpen()) document.Close();
ms.Position = 0;
DownloadAsPDF(ms);
if (writer != null) writer.Close();
if (ms != null) ms.Close();
if (reader != null) reader.Close();
}
private void DownloadAsPDF(MemoryStream ms)
{
string attachment = "attachment; filename=Report_" + DateTime.Now.ToString("ddMMyyyyhhmmss") + ".pdf";
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", attachment);
Response.ContentType = "application/pdf";
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
Response.End();
ms.Close();
}