Harry
Harry

Reputation: 373

Programmatically print to PDF using "Microsoft Print to PDF" in c# windows 10

I am trying to print to pdf using "Microsoft Print to PDF" in c#. I worked really hard on it and wrote below code.

It is creating an empty pdf file instead of filling it with the content of I sent to the printer.

Could anyone help me?

try
{
    PrintDocument pd = new PrintDocument();
    ProcessStartInfo info = new ProcessStartInfo("E:\\ba\\Asp.pdf");
    info.Verb = "Print";
    pd.PrinterSettings.PrintToFile = true;
    pd.PrinterSettings.PrinterName = "Microsoft Print to PDF";
    pd.PrinterSettings.PrintToFile = true;
    pd.PrinterSettings.PrintFileName = Path.Combine("e://", "hktespri" + ".pdf");
    pd.Print();
    info.CreateNoWindow = true;
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);

}

Upvotes: 3

Views: 8174

Answers (1)

Yagnesh Khamar
Yagnesh Khamar

Reputation: 184

you have not given what to print to the pdf document. heres my code I am using it for having my panel to print

 protected void btnPrint_Click(object sender, EventArgs e)
    {
        PrintDialog pd = new PrintDialog();
        PrintDocument pdoc = new PrintDocument();

        pdoc.PrintPage += pdoc_PrintPage;

        if (pd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            pdoc.Print();
        }
    }

    void pdoc_PrintPage(object sender, PrintPageEventArgs e)
    {
        Bitmap bitmap = new Bitmap(outerPanel.Width, outerPanel.Height);
        outerPanel.DrawToBitmap(bitmap, new System.Drawing.Rectangle(5, 5, outerPanel.Width, outerPanel.Height));
        e.Graphics.DrawImage(bitmap, 5, 5);
        bitmap.Dispose();
    }

Upvotes: 1

Related Questions