Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

c# - Programmatically provide a filepath as input file for “Microsoft Print to PDF” printer

Desired result

I want to print a file to a new PDF using the Windows 10 printer "Microsoft Print to PDF" which is installed by default.

When you select this printer as your default printer and use your context menu on a file and select Print, it only asks for a save directory and name. After that, it immediately converts to PDF and saves the file.

As long as MS Office is installed, this works for Word, Excel, PowerPoint file types. But also for common image types and normal text files.

I'd like to automate this by providing a default path.

What I already tried

Stackoverflow already has this related question, but it does not address my specific problem and is rather incomplete and not working.

But I came up with this C# console program which uses the PDF printer to produce a new PDF on my desktop with "Hello World" as string

namespace PrintToPdf_Win10
{
    using System;
    using System.Drawing;
    using System.Drawing.Printing;

    class Program
    {
        public static void Main(string[] args)
        {
            PrintDocument printDoc = new PrintDocument
            {
                PrinterSettings = new PrinterSettings
                {
                    PrinterName = "Microsoft Print to PDF",
                    PrintToFile = true,
                    PrintFileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/test.pdf"
                }
            };

            printDoc.PrintPage += printDoc_PrintPage;
            printDoc.Print();
            Console.ReadKey(true);
        }

        static void printDoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.Graphics.DrawString("Hello World", new Font("Arial", 12), Brushes.Black, 50, 50);
        }
    }
}

Problem

How do I set the content of - let's say a Word file - as input for my printDoc object?

Is there a generic way to set printDoc by providing only a filePath to my file I want to print from? Or do I have to create a custom function for each possible filetype families like:

  • Office filetypes (doc, docx, xls, xlsx, xlsm, ppt, pptx etc.)
  • Image filetypes (png, bmp, jpg)
  • text files (txt, rtf, ini)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is simple solution how to print image or text (it could help you with formats like png, bmp, jpg, txt, ini)

       private static StreamReader streamToPrint;

    static void Main(string[] args)
    {
        string printFormat;
        printFormat = "txt";

        try
        {
            streamToPrint = new StreamReader(@"D:TestText.txt");

            PrintDocument printDoc = new PrintDocument
            {
                PrinterSettings = new PrinterSettings
                {
                    PrinterName = "Microsoft Print to PDF",
                    PrintToFile = true,
                    PrintFileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/test.pdf"
                }
            };

            printDoc.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("A4", 210, 290);
            printDoc.PrinterSettings.DefaultPageSettings.Landscape = false;
            printDoc.PrinterSettings.DefaultPageSettings.Margins.Top = 0;
            printDoc.PrinterSettings.DefaultPageSettings.Margins.Left = 0;

            switch (printFormat)
            {
                case "jpg":
                    printDoc.PrintPage += printDoc_PrintImage;
                    break;
                case "txt":
                    printDoc.PrintPage += printDoc_PrintText;
                    break;
                default:
                    break;
            }
            printDoc.Print();


        }
        finally
        {
            streamToPrint.Close();
        }

        Console.ReadKey(true);

    }

    static void printDoc_PrintImage(object sender, PrintPageEventArgs e)
    {
        Image photo = Image.FromFile(@"D:TestImage.jpg");
        Point pPoint = new Point(0, 0);
        e.Graphics.DrawImage(photo, pPoint);
    }

    static void printDoc_PrintText(object sender, PrintPageEventArgs e)
    {

        Font printFont;
        printFont = new Font("Arial", 10);

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

        float yPos = 0;
        int count = 0;
        float leftMargin = e.MarginBounds.Left;
        float topMargin = e.MarginBounds.Top;

        string line = null;

        while (count < linesPerPage &&
      ((line = streamToPrint.ReadLine()) != null))
        {
            yPos = topMargin + (count *
               printFont.GetHeight(e.Graphics));
            e.Graphics.DrawString(line, printFont, Brushes.Black,
               leftMargin, yPos, new StringFormat());
            count++;
        }

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

As you know docx, xlsx are like zip files and you can unzip and get content as xml. So, it's much work to to if you want to print them


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...