无法打开PDF,这是使用用C#编写的print到pdf代码生成的

时间:2018-05-29 14:27:23

标签: c# pdf printing

我使用C#使用Microsoft Print to PDF打印机将文件打印为PDF。该文件已成功生成。但我无法打开它,因为Adobe Reader说该文件已损坏。这是代码

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

但如果我使用相同的代码,没有PrinterSettings,那么它会提示输入目的地位置和文件名。如果我同时指定它们,那么它会生成一个pdf文件。这个,我可以用Adobe Reader打开。代码如下所示

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

不确定第一种方法中我缺少什么。请帮忙。以下部分是pd_PrintPage

的实现
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 = 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;
}

PS:我提到How to programmatically print to PDF file without prompting for filename in C# using the Microsoft Print To PDF printer that comes with Windows 10代码。

1 个答案:

答案 0 :(得分:0)

这是我运行正常的代码。我希望它有所帮助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing.Printing;
using System.IO;
using System.Drawing;

namespace ConsoleApp1
{
    class Program
    {
        private static Font printFont;
        private static StreamReader streamToPrint;

        static void Main(string[] args)
        {
            // generate a file name as the current date/time in unix timestamp format
            string fileName = (string)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds.ToString();

            // the directory to store the output.
            string directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            printFont = new Font("Arial", 10);

            try
            {
                streamToPrint = new StreamReader
                    ("C:\\Users\\RaikolAmaro\\Desktop\\lachy.txt");

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

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

                        // set the filename to whatever you like (full path)
                        PrintFileName = Path.Combine(directory, fileName + ".pdf"),
                    }
                };

                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;
        }
    }
}