web-dev-qa-db-ja.com

Windows 10に付属のMicrosoft Print To PDFプリンターを使用して、C#でファイル名を要求せずにプログラムでPDFファイルに印刷する方法

Microsoft Windows 10には、何かをPDFファイルに印刷できるMicrosoft Print To PDFプリンターが付属しています。ダウンロードするファイル名の入力を求められます。

これをC#からプログラムで制御して、PDFファイル名を要求せずに、提供するフォルダーの特定のファイル名に保存するにはどうすればよいですか?

これは、多くのドキュメントまたは他の種類のファイルをプログラムでPDFに印刷するバッチ処理用です。

41
pdfman

ファイル名の入力を求めずに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プリンター

38
Kraang Prime

次の例のように、PrintOutメソッドを使用し、4番目の出力ファイル名パラメーターを指定することにより、Windows 10 PDFプリンターに印刷できます。

/// <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は、変換する入力ドキュメントのフルパス文字列であり、docは通常のドキュメントオブジェクトです。ドキュメントの詳細については、_Document.PrintOut()の次のMSDNリンクを参照してください。

例のPrintOutは、指定されたinputFileを介してOutputFileNameに印刷するとサイレントプリントになります。これは元のドキュメントと同じフォルダーに配置されますが、 PDF形式で、.pdf拡張子付き。

2
Jancsik Zsolt