0

I did a windows form using C# about Conversion File to PDF using Microsoft Print to PDF. I already referred to many coding and one of it is from Unable to open the PDF, which was generated using print to pdf code written in C#.

Here below is what I made some little changes.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//using Microsoft.Office.Interop.Word;
//using Microsoft.Office.Interop.Excel;
//using Spire.Pdf;

namespace fileConversion
{
    public partial class Form1 : Form
    {
        private System.Drawing.Font printFont;
        private StreamReader streamToPrint;

        public Form1()
        {
            InitializeComponent();
        }

        private void selectFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                label1.Text = openFileDialog1.FileName; //text label1 tu pegang file name yang kita select
            }
        }

        private void convertFile_Click(object sender, EventArgs e)
        {
             string FileName = label1.Text;
             // the directory to store the output.
             //string directoryPath = System.IO.Path.GetDirectoryName(FileName);

            // initialize PrintDocument object
            PrintDocument doc = new PrintDocument()
             {
                PrinterSettings = new PrinterSettings()
                {
                   // set the printer to 'Microsoft Print to PDF'
                   PrinterName = "Microsoft Print to PDF",

                    // set the filename to whatever you like (full path)
                    PrintFileName = System.IO.Path.GetFullPath(@"" + FileName + ".pdf"),

                    // tell the object this document will print to file
                    PrintToFile = true,
                }
             };

             doc.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
             doc.Print();
        }

        private void pd_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 = File.ReadAllText(label1.Text);

           // Calculate the number of lines per page.
           linesPerPage = ev.MarginBounds.Height /
              printFont.GetHeight(ev.Graphics);

            // Print each line of the file.
            while ((line = streamToPrint.ReadLine()) != null)
            {
                yPos = topMargin + (count *
                   printFont.GetHeight(ev.Graphics));
                ev.Graphics.DrawString(line, printFont, Brushes.Black,
                   leftMargin, yPos, new StringFormat());
                count++;
            }

            // If more lines exist, print another page.
            if (line != null)
                ev.HasMorePages = true;
            else
                ev.HasMorePages = false;
        }
    }
}

However, based on what I did (above code), I successfully convert the file to pdf, but it is unable to open. Before I changed above code, I did:

private void convertFile_Click(object sender, EventArgs e)
        {
             string FileName = label1.Text;
             // the directory to store the output.
             //string directoryPath = System.IO.Path.GetDirectoryName(FileName);

            // initialize PrintDocument object
            PrintDocument doc = new PrintDocument()
             {
                PrinterSettings = new PrinterSettings()
                {
                   // set the printer to 'Microsoft Print to PDF'
                   PrinterName = "Microsoft Print to PDF",

                    // set the filename to whatever you like (full path)
                    PrintFileName = System.IO.Path.GetFullPath(@"" + FileName + ".pdf"),

                    // tell the object this document will print to file
                    PrintToFile = true,
                }
             };

             doc.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
             doc.Print();
        }

Though the conversion from file to pdf are success, but the contents in the pdf file are not displayed. there's only blank pdf file.

and this is my new code after corrected.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace fileConversion
{
    public partial class Form1 : Form
    {
        private static Font printFont;
        private static StreamReader streamToPrint;

        public Form1()
        {
            InitializeComponent();
        }

        private void selectFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                label1.Text = openFileDialog1.FileName; //text label1 tu pegang file name yang kita select
            }
        }

        private void convertFile_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult result = printDialog1.ShowDialog();
                if (result == DialogResult.OK)
                {
                    streamToPrint = new StreamReader(@"" + label1.Text);
                    PrintDocument doc = new PrintDocument();
                    if (printDialog1.PrinterSettings.PrinterName == "Microsoft Print to PDF")
                    {   // force a reasonable filename
                        string filename = Path.GetFileNameWithoutExtension(label1.Text);
                        string directory = Path.GetDirectoryName(label1.Text);
                        doc.PrinterSettings.PrintToFile = true;
                        // confirm the user wants to use that name
                        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                        saveFileDialog1.InitialDirectory = directory;
                        saveFileDialog1.FileName = filename + ".pdf";
                        saveFileDialog1.Filter = "PDF File|*.pdf";
                        result = saveFileDialog1.ShowDialog();
                        if (result != DialogResult.Cancel)
                            doc.PrinterSettings.PrintFileName = saveFileDialog1.FileName;
                    }

                    if (result != DialogResult.Cancel)  // in case they canceled the save as dialog
                    {
                        doc.PrintPage += new PrintPageEventHandler(pd_PrintPage);
                        doc.Print();
                    }
                }
            }
            finally
            {
                streamToPrint.Close();
            }
        }

        private static void pd_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;

            // Calculate the number of lines per page.
            linesPerPage = ev.MarginBounds.Height /
                           printFont.GetHeight(ev.Graphics);

            // Iterate over the file, printing each line.
            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 more lines exist, print another page.
            if (line != null)
                ev.HasMorePages = true;
            else
                ev.HasMorePages = false;
        }
    }
}
Anne
  • 1
  • 3
  • you haven't initialized the `streamToPrint` variable just initialize that with the file you want to be converted. – vikscool Aug 14 '18 at 07:29
  • @vikscool okay, i already put that. and after i tried run the program, **System.NullReferenceException: Object reference not set to an instance of an object.'** show up and it specified to `linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);` – Anne Aug 14 '18 at 09:14
  • the code one that i corrected, shows what i mentioned in the comment above. – Anne Aug 14 '18 at 09:20
  • you are getting **System.NullReferenceException: Object reference not set to an instance of an object.** because of the `printFont` variable as you have declared it but you haven't initialized it. So, it is null that's why it is throwing the error. Just initialize it as `printFont = new Font("Arial", 10);` (or define any font-family of your choice and the size) at the constructor of the `form1`. – vikscool Aug 14 '18 at 09:34
  • @vikscool when i convert excel or doc file to pdf, the contents turned out to be full of symbols. but for .txt file, it turned out okay. – Anne Aug 14 '18 at 09:49
  • the `.txt` files are simple they just contain texts whereas the formatting in the `word` or `excel` file is different which when you read with them via the `StreamReader` gives you symbols (as excel files are based on row and columns). So, create a different implementation of the type that you want to convert to pdf. – vikscool Aug 14 '18 at 09:59
  • @vikscool alright. Thank you so much helping me! – Anne Aug 14 '18 at 10:01
  • you are welcome. – vikscool Aug 14 '18 at 10:02

0 Answers0