Wednesday 30 January 2013

Generate Pdf File Wih iTextSharp


using System;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Text;
using iTextSharp.text.pdf.parser;


namespace SampleCSharpApplication
{
    public partial class Test1 : System.Web.UI.Page
    {
        protected void Button1_Click(object sender, EventArgs e)
        {
            var doc = new Document();
            string Path = Server.MapPath("Scripts");

            PdfWriter.GetInstance(doc, new FileStream(Path + "/Test.pdf", FileMode.Create));
            doc.Open();
            TextReader txt = new StreamReader(Path + "/Test.txt");
            doc.Add(new Paragraph(txt.ReadToEnd()));
            Image img = Image.GetInstance(Path + "/Test.jpg");
            img.ScaleAbsolute(500, 200);
            // Read PDF File
            StringBuilder sb = new StringBuilder();
            using (PdfReader reader = new PdfReader(Path + "/Receipt.pdf"))
            {
                ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                for (int page = 0; page < reader.NumberOfPages; page++)
                {
                    string text = PdfTextExtractor.GetTextFromPage(reader, page + 1, strategy);
                    if (!string.IsNullOrWhiteSpace(text))
                    {                            
                       sb.Append(Encoding.UTF8.GetString(ASCIIEncoding.
                                      Convert(Encoding.Default, Encoding.UTF8,       
                                      Encoding.Default.GetBytes(text))));
                    }
                }               
            }
            doc.Add(new Paragraph(sb.ToString()));
            doc.Add(img);
            doc.Close();
        }



    }
}

No comments:

Post a Comment