Print a file saved in C #

I'm trying to print in winform, it turns out that when I print the document, I get the blank sheet. This is the code with which I try to print:

    private PrintDocument printDocument1 = new PrintDocument();
    private string stringToPrint;
    public Form1()
    {
        InitializeComponent();
    }


    private void button1_Click(object sender, EventArgs e)
    {
        ReadPrint();
        printDocument1.Print();
    }

    private void ReadPrint()
    {
        string docName = "ejemplo.pdf";
        string docPath = @"C:\dir1\";
        printDocument1.DocumentName = docName;
        using (FileStream stream = new FileStream(docPath + docName, FileMode.Open, FileAccess.Read))
        using (StreamReader reader = new StreamReader(stream))
        {
            stringToPrint = reader.ReadToEnd();
        }
    }

    private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
    {
        int charactersOnPage = 0;
        int linesPerPage = 0;


        e.Graphics.MeasureString(stringToPrint, this.Font,
            e.MarginBounds.Size, StringFormat.GenericTypographic,
            out charactersOnPage, out linesPerPage);


        e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
            e.MarginBounds, StringFormat.GenericTypographic);


        stringToPrint = stringToPrint.Substring(charactersOnPage);

        e.HasMorePages = (stringToPrint.Length > 0);
    }

    private void printButton_Click(object sender, EventArgs e)
    {
        LeerArchivo();
        printDocument1.Print();
    }

I would like to know if there is a way to correct it or some other way to print the file?Or some example code? regards

In stringToPrint: enter image description here

1 answer

  • answered 2017-12-06 01:38 Zwei James

    Are you sure that the stringToPrint is not empty or null ? I'm using the same thing and it works perfectly. You should try to add a print PrintPreviewDialog in case you want to check if the document to be print is not blank. Check your variables first.

    e.Graphics.DrawString("SomeString", new Font("Arial", 12, FontStyle.Bold), Brushes.Black, new Point(580, 510));
    
    e.Graphics.DrawString("SomeString1", new Font("Arial", 12, FontStyle.Bold), Brushes.Black, new Point(700, 510));
    

    for the parameter new Point() it is where your text appears via x and y coordinates.