ASP.NET - Write pdf document using iTextSharp - Asked By Anandh Ramanujam on 06-Dec-11 07:27 AM

Hi,

I am creating and writing to pdf document using iTextSharp.

I have to write content to pdf in such a way that splitting into two columns.

Means, split the page like two columns and write the content to that.

How we can do.. please help me in this regard

Thanks
Jitendra Faye replied to Anandh Ramanujam on 06-Dec-11 07:31 AM

Generate PDFs using the http://www.itextpdf.com/.



Step 1:
First create an instance of document object

Document myDocument= new Document(PageSize.A4.Rotate());

Step 2: Now create a writer that listens to this doucment and writes the document to desired Stream.

PdfWriter.GetInstance(myDocument, new FileStream("Salman.pdf", FileMode.Create));

Step 3: Open the document now using

myDocument.Open();

Step 4: Now add some contents to the document

myDocument.add( new Paragraph ( "First Pdf File made by Salman using iText"));

Step 5: Remember to close the documnet

myDocument.close();


There's a full code sample below to get you started.

// Code

using System;
using System.IO;
using System.Diagnostics;

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

public class iTextDemo 
{
 public static void Main() 
 {
  Console.WriteLine("iText Demo");

  // step 1: creation of a document-object
  Document myDocument = new Document(PageSize.A4.Rotate());

  try 
  {

   // step 2:
   // Now create a writer that listens to this doucment and writes the document to desired Stream.

   PdfWriter.GetInstance(myDocument, new FileStream("Salman.pdf", FileMode.Create));

   // step 3:  Open the document now using
   myDocument.Open();

   // step 4: Now add some contents to the document
   myDocument.Add(new Paragraph("First Pdf File made by Salman using iText"));

  }
  catch(DocumentException de) 
  {
   Console.Error.WriteLine(de.Message);
  }
  catch(IOException ioe) 
  {
   Console.Error.WriteLine(ioe.Message);
  }

  // step 5: Remember to close the documnet

  myDocument.Close();
 }
}



hope this helps you...
dipa ahuja replied to Anandh Ramanujam on 06-Dec-11 07:34 AM
This is the simple example
 
Try this way:
 
Download the dll of itextSharp.dll
 
http://sourceforge.net/projects/itextsharp/
 
and try this code
 
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
 
private void btnExport_Click(object sender, EventArgs e)
{
   Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
   PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("d:\\Test.pdf", FileMode.Create));
 
   doc.Open();//Open Document to write
 
 
   Paragraph paragraph = new Paragraph("data Exported From DataGridview!");
 
   doc.Add(paragraph);
   doc.Add(t1);
   doc.Close(); //Close document
   //
   MessageBox.Show("PDF Created!");
}
 
 
 
 
 
Anoop S replied to Anandh Ramanujam on 06-Dec-11 08:57 AM
1 using System.IO;
 2 using System.Text;
 3 using iTextSharp.text;
 4 using iTextSharp.text.pdf;
 5 
 6 namespace FooTheory.iTextSharpLibrary
 7 {
 8     /// <summary>
 9     /// Example PDF Class
10     /// </summary>
11     public class FooTheoryPdf
12     {
13         /// <summary>
14         /// Method that will utilize iTextSharp to write the <see cref="stringToWriteToPdf"/> to the 
15         /// pdf on each page of the PDF.
16         /// </summary>
17         /// <param name="sourceFile">The PDf File</param>
18         /// <param name="stringToWriteToPdf">The text to write to the pdf</param>
19         /// <returns>The bytes of the newly updated PDF with <see cref="stringToWriteToPdf"/> in the pdf.</returns>
20         public static byte[] WriteToPdf(FileInfo sourceFile, string stringToWriteToPdf)
21         {
22             PdfReader reader = new PdfReader(sourceFile.FullName);
23 
24             using (MemoryStream memoryStream = new MemoryStream())
25             {
26                 //
27                 // PDFStamper is the class we use from iTextSharp to alter an existing PDF.
28                 //
29                 PdfStamper pdfStamper = new PdfStamper(reader, memoryStream);
30 
31                 for (int i = 1; i <= reader.NumberOfPages; i++) // Must start at 1 because 0 is not an actual page.
32                 {
33                     //
34                     // If you ask for the page size with the method getPageSize(), you always get a
35                     // Rectangle object without rotation (rot. 0 degrees)—in other words, the paper size
36                     // without orientation. That’s fine if that’s what you’re expecting; but if you reuse
37                     // the page, you need to know its orientation. You can ask for it separately with
38                     // getPageRotation(), or you can use getPageSizeWithRotation(). - (Manning Java iText Book)
39                     //   
40                     //
41                     Rectangle pageSize = reader.GetPageSizeWithRotation(i);
42 
43                     //
44                     // Gets the content ABOVE the PDF, Another option is GetUnderContent(...)  
45                     // which will place the text below the PDF content. 
46                     //
47                     PdfContentByte pdfPageContents = pdfStamper.GetUnderContent(i);
48                     pdfPageContents.BeginText(); // Start working with text.
49 
50                     //
51                     // Create a font to work with 
52                     //
53                     BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);
54                     pdfPageContents.SetFontAndSize(baseFont, 40); // 40 point font
55                     pdfPageContents.SetRGBColorFill(255, 0, 0); // Sets the color of the font, RED in this instance
56 
57 
58                     //
59                     // Angle of the text. This will give us the angle so we can angle the text diagonally 
60                     // from the bottom left corner to the top right corner through the use of simple trigonometry. 
61                     //
62                     float textAngle =
63                         (float) FooTheoryMath.GetHypotenuseAngleInDegreesFrom(pageSize.Height, pageSize.Width);
64 
65                     //
66                     // Note: The x,y of the Pdf Matrix is from bottom left corner. 
67                     // This command tells iTextSharp to write the text at a certain location with a certain angle.
68                     // Again, this will angle the text from bottom left corner to top right corner and it will 
69                     // place the text in the middle of the page. 
70                     //
71                     pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, stringToWriteToPdf,
72                                                     pageSize.Width/2,
73                                                     pageSize.Height/2,
74                                                     textAngle);
75 
76                     pdfPageContents.EndText(); // Done working with text
77                 }
78                 pdfStamper.FormFlattening = true; // enable this if you want the PDF flattened. 
79                 pdfStamper.Close(); // Always close the stamper or you'll have a 0 byte stream. 
80 
81 
82                 return memoryStream.ToArray();
83             }
84         }
85     }
86 }

Refer ths Using iTextSharp To Watermark/Write Text To Existing PDF's 1; i <= reader.NumberOfPages; i++)

http://footheory.com/blogs/donnfelker/archive/2008/05/11/using-itextsharp-to-watermark-write-text-to-existing-pdf-s.aspx
Suchit shah replied to Anandh Ramanujam on 06-Dec-11 11:48 PM
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnExport_Click(object sender, EventArgs e)
{
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string html = sw.ToString();
Document Doc = new Document();

//PdfWriter.GetInstance
//(Doc, new FileStream(Request.PhysicalApplicationPath
//+ "\\AmitJain.pdf", FileMode.Create));

PdfWriter.GetInstance
(Doc, new FileStream(Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf", FileMode.Create));
Doc.Open();

Chunk c = new Chunk
("Export GridView to PDF Using iTextSharp \n",
FontFactory.GetFont("Verdana", 15));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
Chunk chunk1 = new Chunk
("By Amit Jain, amit_jain_online@yahoo.com \n",
FontFactory.GetFont("Verdana", 8));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_RIGHT;
p1.Add(chunk1);

Doc.Add(p);
Doc.Add(p1);

System.Xml.XmlTextReader xmlReader =
new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(Doc, xmlReader);

Doc.Close();
string Path = Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf";


ShowPdf(Path);


}

private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader
("Content-Disposition","attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
//Response.WriteFile(strS);
Response.Flush();
Response.Clear();

}
}

Look at :
http://csharpdotnetfreak.blogspot.com/2008/12/export-gridview-to-pdf-using-itextsharp.html
http://www.dotnetfunda.com/articles/article1150-all-in-one-export-data-in-aspnet-gridview-to-doc-gridview-to-excel-gr.aspx


Write pdf document using iTextSharp - forum patel replied to Suchit shah on 23-May-12 04:42 AM
I am writing to text in pdf document using iTextSharp.
Means write content should be append in existing pdf.
not replace but only append content.

How we can do.. please help me in this regard

Thanks