2015-11-29 333 views
6

私はC# .netの各種ドキュメントを作成するプログラムを持っています。これらの文書は、別々の場所に保存され、明確に定義された異なる名前で保存する必要があります。プログラムでファイル名とパスをMicrosoft印刷のPDFプリンタに設定します

これを行うには、System.Drawing.Printing.PrintDocumentクラスを使用します。 この文でプリンタとしてMicrosoft Print to PDFを選択します:

PrintDocument.PrinterSettings.PrinterName = "Microsoft Print to PDF";

私は文書をpdf fileに印刷することができます。ユーザーはファイル選択ダイアログを取得します。次に、このダイアログボックスで、pdfファイルの名前と格納場所を指定できます。

ファイルの量が多く、正しいパスと名前を見つけるのが面倒でエラーが発生しやすいため、このダイアログボックスでプログラムで正しいパスとファイル名を設定したいと思います。

私はすでに、これらの属性をテストしている:これらの属性に必要なパスとファイル名を書く

PrintDocument.PrinterSettings.PrintFileName PrintDocument.DocumentName

は助けにはなりませんでした。 C#でMicrosoft Print to PDFプリンタのパスとファイル名のデフォルト値を設定する方法はありますか?

注:私の環境PrintToFileプロパティがtrueに設定ないある場合PrintFilenameは無視されるよう のWindows 10、 のVisual Studio 2010、 の.NET Framework 4.5

答えて

0

に思えます。 PrintToFiletrueに設定されており、有効なファイル名(フルパス)が指定されている場合、ユーザーがfilenameを選択したフィールドダイアグラムは表示されません。

ヒント:プリンタセッティングのプリンシパル名を設定するときは、IsValidプロパティをチェックして、このプリンタが実際に存在することを確認してください。プリンタ設定とインストールされたプリンタの詳細についてはcheck this post

0

自分で試してみましたが、PrintDocumentインスタンスに既に埋め込まれているDocumentNameまたはPrinterSettings.PrintFileNameを持つPrintDialogのSaveAsダイアログをあらかじめ入力することができませんでした。これは直観に反しているようですので、何かが足りなくなっているかもしれません

あなたが望むのであれば、印刷ダイアログをバイパスして、ユーザーの操作なしで自動的に印刷することができます。これを行う場合は、ドキュメントを追加するディレクトリが存在し、追加するドキュメントが存在しないことを事前に確認する必要があります。

string existingPathName = @"C:\Users\UserName\Documents"; 
string notExistingFileName = @"C:\Users\UserName\Documents\TestPrinting1.pdf"; 

if (Directory.Exists(existingPathName) && !File.Exists(notExistingFileName)) 
{ 
    PrintDocument pdoc = new PrintDocument(); 
    pdoc.PrinterSettings.PrinterName = "Microsoft Print to PDF"; 
    pdoc.PrinterSettings.PrintFileName = notExistingFileName; 
    pdoc.PrinterSettings.PrintToFile = true; 
    pdoc.PrintPage += pdoc_PrintPage; 
    pdoc.Print(); 
} 
1

他の回答で述べたように、あなたはPrinterSettings.PrintToFile = trueを強制し、PrinterSettings.PrintFileNameを設定したが、その後、ユーザーはポップアップとして保存取得していませんことができます。私の解決策は、私の "提案された"ファイル名(私の場合、私が.pdfに変更するテキストファイル(.txt))でそれを設定してから、PrintFileNameを結果に設定することです。

DialogResult userResp = printDialog.ShowDialog(); 
if (userResp == DialogResult.OK) 
{ 
    if (printDialog.PrinterSettings.PrinterName == "Microsoft Print to PDF") 
    { // force a reasonable filename 
     string basename = Path.GetFileNameWithoutExtension(myFileName); 
     string directory = Path.GetDirectoryName(myFileName); 
     prtDoc.PrinterSettings.PrintToFile = true; 
     // confirm the user wants to use that name 
     SaveFileDialog pdfSaveDialog = new SaveFileDialog(); 
     pdfSaveDialog.InitialDirectory = directory; 
     pdfSaveDialog.FileName = basename + ".pdf"; 
     pdfSaveDialog.Filter = "PDF File|*.pdf"; 
     userResp = pdfSaveDialog.ShowDialog(); 
     if (userResp != DialogResult.Cancel) 
      prtDoc.PrinterSettings.PrintFileName = pdfSaveDialog.FileName; 
    } 

    if (userResp != DialogResult.Cancel) // in case they canceled the save as dialog 
    { 
     prtDoc.Print(); 
    } 
} 
関連する問題