无法打开使用C#编写的打印到pdf代码生成的PDF [英] Unable to open the PDF, which was generated using print to pdf code written in C#

查看:259
本文介绍了无法打开使用C#编写的打印到pdf代码生成的PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是,如果我使用相同的代码,但没有PrinterSettings,则会提示输入目标位置和文件名.如果同时指定两者,则将生成一个pdf文件.这样,我可以使用Adobe Reader打开.代码如下所示

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

不确定第一种方法中我缺少什么.请帮忙.下一部分是pd_PrintPage的实现

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:我指的是推荐答案

这是我运行正常的代码.希望对您有帮助.

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

这篇关于无法打开使用C#编写的打印到pdf代码生成的PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆