Printing PDF document using C#

Hi all,

I have an aspx page whcih contains some lable controls with values. I would like to print those values in a table in PDF. I have added the iTextSharp PDF dll but I am not sure how to print the following StringBuilder object when a user clicks on the print button:

  protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {

        StringBuilder strHTML = new StringBuilder();
        strHTML.Append("<table border=1>");
        strHTML.Append("<tr>");
        strHTML.Append("<td>" + "<b> Car Size: </b>" + lblCarSize.Text + " " + "</td>");
        strHTML.Append("<td>" + "<b> Car Make:  </b>" + lblCarMake.Text + "</td>" + "<br />");
        strHTML.Append("</tr>");
        strHTML.Append("<tr>");
        strHTML.Append("<td>" + "<b> Car Model: </b>" + lblCarModel.Text + " " + "</td>");
        strHTML.Append("<td>" + "<b> Other Details:  </b>" + lblOtherDetails.Text + "</td>" + "<br />");
        strHTML.Append("</tr>");
        strHTML.Append("<tr>");
        strHTML.Append("<td>" + "<b> Pink-up Time: </b>" + lblPickupTime.Text + " " + "</td>");
        strHTML.Append("<td>" + "<b> Drop-off Time:  </b>" + lblDropoffTime.Text + "</td>" + "<br />");
        strHTML.Append("</tr>");
        strHTML.Append("<tr>");
        strHTML.Append("<td>" + "<b> Pick-up Location:  </b>" + lblPickupLocation.Text + " " + "</td>");
        strHTML.Append("<td>" + "<b> Drop-off Location:  </b>" + lblDropoffLocation.Text + " " + "</td>");
        strHTML.Append("</tr>");
        strHTML.Append("<tr>");
        strHTML.Append("<td>" + "<b> Pick-up Date:  </b>" + lblPickupDate.Text + "</td>" + "<br />");
        strHTML.Append("<td>" + "<b> Drop-off Date:  </b>" + lblDropoffDate.Text + "</td>" + "<br />");
        strHTML.Append("</tr>");
        strHTML.Append("<tr>");
        strHTML.Append("<td>" + "<b> Total Charges:  </b>" + lblTotalCharges.Text + " DKK " + "</td>");
        strHTML.Append("</tr>");
        strHTML.Append("</table>");
           
        //Generating pdf
        Document document = new Document();
        PdfWriter.GetInstance(document, new FileStream(@"C:\Temp\test.pdf", FileMode.Create));
        document.Open();
 
    }

Any ideas?
Itudk_2010Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

RonCraig_101Commented:
Itudk_2010Author Commented:
Hi,

That link does not help, any other ideas?
RonCraig_101Commented:
the attached code will open the file in pdf reader and you can print using the pdf reader.
or create a .bat file to execute    AcroRd32.exe /P c:/yourfilename.pdf
MemoryStream MStream = new MemoryStream();

        iTextSharp.text.Document doc = new iTextSharp.text.Document();
        PdfWriter writer = PdfWriter.GetInstance(doc, MStream);
        doc.Open();
        doc.Add(new Paragraph("Hello World"));
        PdfContentByte cb = writer.DirectContent;
        Barcode128 barcode = new Barcode128();
        barcode.CodeType = Barcode128.CODE_C;
        barcode.Code = "1234567890";
        iTextSharp.text.Image img = barcode.CreateImageWithBarcode(cb, null, null);
        doc.Add(new Phrase(new Chunk(img, 100, 0)));

        doc.Close();

        Response.ContentType ="application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=file.pdf");
        Response.Buffer = true;
        Response.Clear();

        Response.OutputStream.Write(MStream.GetBuffer(), 0, MStream.GetBuffer().Length);

        Response.OutputStream.Flush();

        Response.End();

Open in new window

Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Itudk_2010Author Commented:
Hi RonCraig_101,

Thanks for the code example. I can print a single string but how to print  multiple stirngs or multiple lable control values. Your following code can print one line:
 doc.Add(new Paragraph("Hello World"));

but how about multiple lines print inside a table?

Thanks for your help. Looking forward to your reply.
RonCraig_101Commented:
try this
 
MemoryStream MStream = new MemoryStream();

        iTextSharp.text.Document doc = new iTextSharp.text.Document();
        PdfWriter writer = PdfWriter.GetInstance(doc, MStream);
        StringBuilder strHTML = new StringBuilder();
        doc.Open();


        PdfPTable table = new PdfPTable(3);
        PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));
        cell.Colspan = 3;
        cell.HorizontalAlignment = 1;
        table.AddCell(cell);
        table.AddCell("Col 1 Row 1");
        table.AddCell("Col 2 Row 1");
        table.AddCell("Col 3 Row 1");
        table.AddCell("Col 1 Row 2");
        table.AddCell("Col 2 Row 2");
        table.AddCell("Col 3 Row 2");
        doc.Add(table);
        doc.Add(table);
        doc.Close();

        Response.ContentType ="application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=file.pdf");
        Response.Buffer = true;
        Response.Clear();

        Response.OutputStream.Write(MStream.GetBuffer(), 0, MStream.GetBuffer().Length);

        Response.OutputStream.Flush();

        Response.End();

Open in new window

Itudk_2010Author Commented:
Thanks, but where can I add this:
StringBuilder strHTML = new StringBuilder();

I am not sure how and where to add the strHTML so all the values of the table will be shown in the pdf document?

any ideas?

Thanks again for your help.

RonCraig_101Commented:
I would forget about the stringbuilder just do this...
string value =  "Car Make: " +  lblCarMake.Text ;
 table.AddCell(value);

but if you want to use it then you will have to cast the string as a table.
string testString = @"<?xml version=""1.0"" encoding=""UTF-8"">
<root><child><subchild>.....</subchild></child></root>";
DataSet ds = new DataSet();
StringReader stream = new StringReader(testString);
ds.ReadXml(stream);
DataTable dt = ds.Tables[0];

then do something like this to convert that to a pdfTable
http://www.dotnetspark.com/kb/1365-create-custom-table-pdf-document-using-itextsharp.aspx 
Itudk_2010Author Commented:
RonCraig_101,

I really appreciate your help. But this way it seems quite complicated. Is there any easiest way to implement that?

I will look on the link you provided.

Thanks.
Itudk_2010Author Commented:
Hi RonCraig_101,

I did the following changes in your code and it works fine except the last lines are not show in the pdf table while printing. The lines which are not shown are values of string value10 and string value11 as shown below:

        string value10 = "Other Details: " + otherCarDetails;
        table.AddCell(value10);
        string value11 = "Total Charges: " + totalCharges;
        table.AddCell(value11);

The rest is fine--

MemoryStream MStream = new MemoryStream();
        Document doc = new Document();
        PdfWriter writer = PdfWriter.GetInstance(doc, MStream);
        //StringBuilder strHTML = new StringBuilder();
        doc.Open();

        PdfPTable table = new PdfPTable(3);
        PdfPCell cell = new PdfPCell(new Phrase("Your Booking Details!"));
        cell.Colspan = 3;
        cell.HorizontalAlignment = 1;
        table.AddCell(cell);
        string value = "Car Size: " + carSize;
        table.AddCell(value);
        string value2 = "Car Make: " + carMake;
        table.AddCell(value2);
        string value3 = "Car Model: " + carModel;
        table.AddCell(value3);
        string value4 = "Pick-up Time: " + pickupTime;
        table.AddCell(value4);
        string value5 = "Drop-off Time: " + dropOffTime;
        table.AddCell(value5);
        string value6 = "Pick-up Location: " + PickUpLocation;
        table.AddCell(value6);
        string value7 = "Pick-up Date: " + PickUpDate;
        table.AddCell(value7);
        string value8 = "Drop-off Location: " + DropOffLocation;
        table.AddCell(value8);
        string value9 = "Drop-off Date: " + DropOffDate;
        table.AddCell(value9);
        string value10 = "Other Details: " + otherCarDetails;
        table.AddCell(value10);
        string value11 = "Total Charges: " + totalCharges;
        table.AddCell(value11);
        doc.Add(table);
        doc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=file.pdf");
        Response.Buffer = true;
        Response.Clear();
        Response.OutputStream.Write(MStream.GetBuffer(), 0, MStream.GetBuffer().Length);
        Response.OutputStream.Flush();
        Response.End();

RonCraig_101Commented:
Replace this line
PdfPTable table = new PdfPTable(1);
Add these two lines
            int[] widths = {100};
            table.SetWidths(widths);
RonCraig_101Commented:
complete code
MemoryStream MStream = new MemoryStream();
        iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.LETTER, 72, 72, 72, 72);
        PdfWriter writer = PdfWriter.GetInstance(doc, MStream);
        doc.Open();
        PdfPTable table = new PdfPTable(1);
        int[] widths = { 100 };
        table.SetWidths(widths);
        PdfPCell cell = new PdfPCell();
        string value = "Car Size: " + "carSize";
        table.AddCell(value);
        string value2 = "Car Make: " + "carMake";
        table.AddCell(value2);
        string value3 = "Car Model: " + "carModel";
        table.AddCell(value3);
        string value4 = "Pick-up Time: " + "pickupTime";
        table.AddCell(value4);
        string value5 = "Drop-off Time: " + "dropOffTime";
        table.AddCell(value5);
        string value6 = "Pick-up Location: " + "PickUpLocation";
        table.AddCell(value6);
        string value7 = "Pick-up Date: " + "PickUpDate";
        table.AddCell(value7);
        string value8 = "Drop-off Location: " + "DropOffLocation";
        table.AddCell(value8);
        string value9 = "Drop-off Date: " + "DropOffDate";
        table.AddCell(value9);
        string value10 = "Other Details: " + "otherCarDetails";
        table.AddCell(value10);
        string value11 = "Total Charges: " + "totalCharges";
        table.AddCell(value11);
        string value12 = "Total Charges: " + "totalCharges";
        table.AddCell(value12);
        table.AddCell(value12);
        table.AddCell(value12);
        table.AddCell(value12);
        doc.Add(table);
        doc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=file.pdf");
        Response.Buffer = true;
        Response.Clear();
        Response.OutputStream.Write(MStream.GetBuffer(), 0, MStream.GetBuffer().Length);
        Response.OutputStream.Flush();
        Response.End();

Open in new window

RonCraig_101Commented:
and the reason...  PdfPTable table = new PdfPTable(3); says you will have 3 columns per row.
becase you have 11 cells /3 give you 3 complete rows and 1 incomplete row.. the incomplete row was not printed to your document.

so change the number of columns or add a complete set of cells for each row.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Itudk_2010Author Commented:
The following lines of code work fine but it does not add any columns in the table. It displays the records in only rows so you don't see any columns in the table:

       PdfPTable table = new PdfPTable(1);
        int[] widths = { 100 };
        table.SetWidths(widths);

Any other ideas?

I will also try to look into it in more detail.
RonCraig_101Commented:
you have all the basic concepts... you just need to read more on how to format the pdftable to your liking...
PdfPTable table = new PdfPTable(1); will change the number of columns you have .... just make sure you use the corect number of cells per row...

if you want blank cells just add them..


Itudk_2010Author Commented:
Ok, I will try.

Thanks a lot.
RonCraig_101Commented:
could you please make as answerd please.

Thanks you .
Itudk_2010Author Commented:
Ok, but it is not 100% correct?
Itudk_2010Author Commented:
solved
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.