Thursday, November 26, 2009

The only possible solution to generate pdf under Medium Trust level

It’s been a nightmare if you application work fine at your development end and it’s unable to work under production environment; just due to do ACCESS LEVEL ISSUES.

I have to create pdf.

1.       Microsoft reporting was creating a trust level issue so it was rejected.

2.       Then I opt for itextsharp

Again ran into trust level problem.


Then I download the open source code from the itextsharp website and added

using System.Security;

[assembly: AllowPartiallyTrustedCallers()]   attribute inside AssemblyInfo.cs

Compiled the file and uploaded it to server.


Got a function from internet which I modified according to mine needs


protected void btnExportPDF_Click(object sender, EventArgs e)


        Response.ContentType = "application/pdf";

        Response.AddHeader("content-disposition", "attachment;filename=BranchDataExport1.pdf");



        StringWriter sw = new StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(sw);


        // I need to get the data from HTML table so I used it’s rendercontrol.


        StringReader sr = new StringReader(sw.ToString());

        Document pdfDoc = new Document(PageSize.A4, 50f, 50f, 50f, 50f);

        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);





            //Create a footer that will display page number

            HeaderFooter footer = new HeaderFooter(new Phrase("List -: " + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString(), new Font(1, 10, 1, Color.BLACK)), false);

            pdfDoc.Footer = footer;

            //Parse Html



        catch (Exception ex)


            //Display parser errors in PDF.

            //Parser errors will also be wisible in Debug.Output window in VS

            Paragraph paragraph = new Paragraph("Error! " + ex.Source + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace);


            Chunk text = paragraph.Chunks[0] as Chunk;

            if (text != null)


                text.Font.Color = Color.RED;













And this generate pdf for. Also I ran into different sort of problem which I didn’t mention like

Web.Permission….   That was due to the inclusion of file.

Some pdf page related error etc etc.


This whole took mine so much time, so I want you guys don’t waste time on this issue. BEST OF LUCK


No comments: