Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi I have a page that i wanted to print to pdf file.not in the particular device setting but to print it as PDF file ... any one idea?

i have tried this code. but it only refreshing my page..nothing happen. please correct me if this is a appropriate code or not.. Thanks for sharing your ideas.

What I have tried:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using MySql.Web;
using MySql.Data;
using System.IO;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.ComponentModel;

namespace SchoolPortal
{

    public partial class nmb : System.Web.UI.Page
    {
        public Font printFont;
        public StreamReader streamToPrint;
        static string filePath;

        MySqlConnection conn = new MySqlConnection(@"Data Source =localhost; port=3306;Initial Catalog=mysql_testing;Uid=root;Pwd=secret;Database=payroll_system;");
        MySqlCommand cmd;
        MySqlDataReader mdr;
        protected void Page_Load(object sender, EventArgs e)
        {
            txte.Text = Session["e"].ToString();

        }
        protected void btnView_Click(object sender, EventArgs e)
        {

            conn.Open();
            string SelectQuery = "SELECT * From info_info WHERE employee_ID='" + txte.Text + "' AND month='" + txtmonth.Text + "' AND days='" + txtday.Text + "' AND year ='" + txtyear.Text + "'";
            cmd = new MySqlCommand(SelectQuery, conn);
            mdr = cmd.ExecuteReader();
            if (mdr.Read())
            {
                lblemployee.Text = mdr.GetString("employee_ID");
                lblmonth.Text = mdr.GetString("month");
                lbldays.Text = mdr.GetString("days");
                lblyear.Text = mdr.GetString("year");
                lbllast.Text = mdr.GetString("Name");
                lblLast1.Text = mdr.GetString("Name");
                lblposition.Text = mdr.GetString("position");
                lblregular.Text = mdr.GetString("regular");
                lbltotal.Text = mdr.GetString("totalday");
                lblGen.Text = mdr.GetString("month1");
                lblStat.Text = mdr.GetString("day1");
                lblCon.Text = mdr.GetString("month2");
                lblperm.Text = mdr.GetString("day2");
                lblcent.Text = mdr.GetString("percent");
                lblamount.Text = mdr.GetString("amount");
                lblcent1.Text = mdr.GetString("percent1");
                lblamount1.Text = mdr.GetString("amount1");
                lblcent2.Text = mdr.GetString("percent2");
                lblamount2.Text = mdr.GetString("amount2");
                lblcent3.Text = mdr.GetString("percent3");
                lblamount3.Text = mdr.GetString("amount3");
                lblholiday.Text = mdr.GetString("holiday");
                lblspecial.Text = mdr.GetString("special");
                //lbltotal.Text = mdr.GetString("total");
                lbldeduction.Text = mdr.GetString("deduction");
                lblholds.Text = mdr.GetString("date1");
                lblCash.Text = mdr.GetString("cash_advance");
                lblnet.Text = mdr.GetString("net");
                lbllate.Text = mdr.GetString("late");
                lblundertime.Text = mdr.GetString("under_time");
                lblabsent.Text = mdr.GetString("absent");

                lblmess.Text = "";
            }

            else
            {

                lblmess.Text = "no record found please check your ID number as well as month, day, and year then TRY AGAIN";
            }
            conn.Close();


        }
           
        protected void Button1_PrintPage(object sender, PrintPageEventArgs ev)
        {
            float linesPerPage = 0;
            float yPos = 0;
            int count = 0;
            float leftMargin = ev.MarginBounds.Left;
            float topMargin = ev.MarginBounds.Top;
            String line = null;

            linesPerPage = ev.MarginBounds.Height /
                printFont.GetHeight(ev.Graphics);

            while (count < linesPerPage && ((line = streamToPrint.ReadLine()) != null))
            {
                yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
                ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
                count++;
            }
            if (line != null)
                ev.HasMorePages = true;
            else
                ev.HasMorePages = false;
        }
        public void Printing()
        {
            try
            {
                streamToPrint = new StreamReader(filePath);
                try
                {

                    PrintDocument pd = new PrintDocument();
                    pd.PrintPage += new PrintPageEventHandler(Button1_PrintPage);
                    pd.Print();

                }
                finally
                {
                    streamToPrint.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }

        }

        public static void Main(string[] args)
        {
            string sampleName = Environment.GetCommandLineArgs()[0];
            if (args.Length != 1)
            {
                Console.WriteLine("Usage : " + sampleName + "<file path>");
                return;
            }
            filePath = args[0];
            new PrintingPermissionLevel();

        }


        }
    }
Posted
Updated 30-Mar-18 17:46pm

Sir is this the one youve trying to tell me to code?
using System.IO;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;


protected void btnExport_Click(object sender, EventArgs e)
{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    this.Page.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End();
}
 
Share this answer
 
Obviously month, days and year are a date, it is a bad idea to handle a date as 3 fields, it is even a worse idea to make them strings.
if a list is sorted on days, you will get:
1 10 11 12 13 14 15 16 17 18 19 2 20 21 ...
And anything will get more complicated with that date.
C#
string SelectQuery = "SELECT * From info_info WHERE employee_ID='" + txte.Text + "' AND month='" + txtmonth.Text + "' AND days='" + txtday.Text + "' AND year ='" + txtyear.Text + "'";

Not a solution to your question, but another problem you have.
Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
 
Share this answer
 
Ummm...ASP.NET code runs ENTIRELY on the server, never the client.

Printing from ASP.NET code is never a good idea because the printer driver may put up a dialog on the server that nobody will ever see or be able to respond to. It is also never a good idea to use System.Windows.Forms classes in an ASP.NET page.

Also, the page is not rendered by the server. It's rendered by the browser on the client.

In order to get a page rendered on the server, in the ASP.NET pipeline, you'd need to either write you're own filter to do a render, or you can use a 3rd party library to do it for you, an example of which you can find here[^].

Or, just Google for "ASP.NET render page to pdf".
 
Share this answer
 
Comments
CaThey Joy Galias 28-Mar-18 19:30pm    
Any idea...
Dave Kreskowiak 28-Mar-18 19:34pm    
WHAT??? Did you even read my post? Especially, the last few lines of it.
CaThey Joy Galias 28-Mar-18 19:34pm    
Because im only a beginner using asp. Net.. Can you guve sample code for my problem
Dave Kreskowiak 28-Mar-18 21:34pm    
No, I can't. I've never had the need to render anything ASP.NET to PDF.

This is where the RESEARCH portion of writing code comes in. I already told you what to search for. Go forth and search, then start reading.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900