Unable to open the PDF, which was generated using print to pdf code written in C#

心已入冬 提交于 2019-12-13 15:54:46

问题


I used C# to print a file to PDF using Microsoft Print to PDF printer. The file was successfully generated. But I am not able to open that because Adobe Reader says that the file is damaged. This is the code

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();

But if I use the same code, without PrinterSettings, then it prompts for the destination location and filename. If I specify both, then it generates a pdf file. This, I am able to open using Adobe Reader. Code is shown below

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

Not sure what am I missing in the first approach. Please help. The below part is the implementation for 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: I referred to 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 for the code.


回答1:


Here's the code I have which runs ok. I hope it helps.

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


来源:https://stackoverflow.com/questions/50586880/unable-to-open-the-pdf-which-was-generated-using-print-to-pdf-code-written-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!