Подтвердить что ты не робот

Как программно печатать в PDF файл без запроса имени файла в С# с помощью принтера Microsoft Print To PDF, который поставляется с Windows 10

Microsoft Windows 10 поставляется с принтером Microsoft Print To PDF, который может печатать что-либо в PDF файле. Он запрашивает имя файла для загрузки.

Как я могу программно управлять этим из С#, чтобы не запрашивать имя файла PDF, но сохранить его в определенное имя файла в какой-либо папке, которую я предоставляю?

Это для пакетной обработки многотипных документов или других типов файлов в PDF.

4b9b3361

Ответ 1

Чтобы напечатать объект PrintDocument используя принтер Microsoft Print to PDF, не запрашивая имя файла, вот PrintDocument способ кода сделать это:

// generate a file name as the current date/time in unix timestamp format
string file = (string)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds.ToString();

// the directory to store the output.
string directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

// 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, file + ".pdf"),
    }
};

doc.Print();

Вы также можете использовать этот метод для других принтеров типа "Сохранить как файл", таких как Microsoft XPS Printer.

Ответ 2

Вы можете распечатать на принтер PDF с Windows 10 с помощью метода PrintOut и указать параметр имени четвертого выходного файла, как в следующем примере:

/// <summary>
/// Convert a file to PDF using office _Document object
/// </summary>
/// <param name="InputFile">Full path and filename with extension of the file you want to convert from</param>
/// <returns></returns>
public void PrintFile(string InputFile)
{
    // convert input filename to new pdf name
    object OutputFileName = Path.Combine(
        Path.GetDirectoryName(InputFile),
        Path.GetFileNameWithoutExtension(InputFile)+".pdf"
    );


    // Set an object so there is less typing for values not needed
    object missing = System.Reflection.Missing.Value;

    // `doc` is of type `_Document`
    doc.PrintOut(
        ref missing,    // Background
        ref missing,    // Append
        ref missing,    // Range
        OutputFileName, // OutputFileName
        ref missing,    // From
        ref missing,    // To
        ref missing,    // Item
        ref missing,    // Copies
        ref missing,    // Pages
        ref missing,    // PageType
        ref missing,    // PrintToFile
        ref missing,    // Collate
        ref missing,    // ActivePrinterMacGX
        ref missing,    // ManualDuplexPrint
        ref missing,    // PrintZoomColumn
        ref missing,    // PrintZoomRow
        ref missing,    // PrintZoomPaperWidth
        ref missing,    // PrintZoomPaperHeight
    );
}

OutputFile - это строка полного пути входного документа, который вы хотите преобразовать, а документ - обычный объект документа. Для получения дополнительной информации о документе см. Следующие ссылки MSDN для _Document.PrintOut()

PrintOut в этом примере выводится тихая печать при печати через указанный inputFile на OutputFileName, который будет помещен в ту же папку, что и исходный документ, но он будет в формате PDF с расширением .pdf.