应用程序:ViewPrinter

Revit 平台:所有

Revit 版本:2011.0

首次发布版本:2008.0

编程语言:C#

技能水平:中等

类别:数据交换

类型:ExternalCommand

主题:打印可打印的视图。

概述:

该示例演示如何打印可打印的视图和工作表。

相关类:

Autodesk.Revit.DB.Document.PrintManager

Autodesk.Revit.DB.VirtualPrinterType

Autodesk.Revit.DB.PrintRange

Autodesk.Revit.DB.PrintSetup

Autodesk.Revit.DB.PrintSetting

Autodesk.Revit.DB.ViewSheetSetting

Autodesk.Revit.DB.ViewSheetSet

项目文件:

Command.cs

这是主要的 DLL 源文件;它包含实现 IExternalCommand 接口的 Command 类。

PrintMgr.cs

公开打印界面,就像 UI 中的打印对话框(文件->打印…)。

PrintSTP.cs

更改和保存打印机设置,公开打印参数,就像 UI 中的打印设置对话框(文件->打印设置…)中的打印机名称、纸张、缩放、选项等。

ViewSheets.cs

公开视图/工作表设置界面,就像 UI 中的视图/工作表设置对话框(文件->打印…;选择的视图/工作表->选择…)。

描述:

该示例演示以下功能:

-打印可打印的视图和工作表。

-更改打印设置。

说明:

假设:安装了可用的打印机。

1. 运行此命令。

2. 在打印对话框中,选择打印机的名称。

3. 如果需要,选择打印到文件。您可以将打印作业保存为 PRN PLT 文件。

4. 在打印范围下,指定您是否正在打印当前窗口、当前窗口的可见部分或选定的视图/工作表。如果您要打印选定的视图/工作表,请单击“选择”,从可用视图列表中选择要打印的视图,然后单击“确定”。

5. 在选项下,指定要打印的副本数以及是否按相反顺序打印视图或工作表集。对于多页打印作业,您可以选择反向打印顺序,以便最后一页首先打印。

6. 要在打印下一个副本的第一页之前打印整个项目的完整副本,请选择“协调”。要先打印所有第一页的副本,然后再打印每个后续页的所有副本,请取消选择“协调”。

7. 在“设置”下,单击“设置”以更改打印设置。

8. 当您准备好打印时,请单击“确定”。

源代码:
完整的源代码请加入QQ群649037449,在群文件中下载RevitSDK.exe,解压后在文件夹中搜索本文中应用程序名称即可获得完整源码

PrintMgr.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

namespace Revit.SDK.Samples.ViewPrinter.CS
{
/// <summary>
/// Exposes the print interfaces just like the Print Dialog (File->Print...) in UI.
/// </summary>
public class PrintMgr
{
private ExternalCommandData m_commandData;
private PrintManager m_printMgr;

public PrintMgr(ExternalCommandData commandData)
{
m_commandData = commandData;
m_printMgr = commandData.Application.ActiveUIDocument.Document.PrintManager;
}

public List<string> InstalledPrinterNames
{
get
{
try
{
PrinterSettings.StringCollection printers
= PrinterSettings.InstalledPrinters;
string[] printerNames = new string[printers.Count];
printers.CopyTo(printerNames, 0);

List<string> names = new List<string>();
foreach (string name in printerNames)
{
names.Add(name);
}

return 0 == names.Count ? null : names;
}
catch (Exception)
{
return null;// can not get installed printer
}
}
}

public string PrinterName
{
get
{
return m_printMgr.PrinterName;
}
set
{
try
{
m_printMgr.SelectNewPrintDriver(value);
}
catch (Exception)
{
// un-available or exceptional printer
}
}
}

public string PrintSetupName
{
get
{
IPrintSetting setting = m_printMgr.PrintSetup.CurrentPrintSetting;
return (setting is PrintSetting) ?
(setting as PrintSetting).Name : ConstData.InSessionName;
}
}

public bool IsPrintToFile
{
get
{
return m_printMgr.PrintToFile;
}
set
{
m_printMgr.PrintToFile = value;
m_printMgr.Apply();
}
}

public bool IsCombinedFile
{
get
{
return m_printMgr.CombinedFile;
}
set
{
// CombinedFile property cannot be setted to false when the Print Range is Current/Visable!
m_printMgr.CombinedFile = value;
m_printMgr.Apply();
}
}

public string PrintToFileName
{
get
{
return m_printMgr.PrintToFileName;
}
}

public string ChangePrintToFileName()
{
using (SaveFileDialog saveDlg = new SaveFileDialog())
{
string postfix = null;

switch (m_printMgr.IsVirtual)
{
case Autodesk.Revit.DB.VirtualPrinterType.AdobePDF:
saveDlg.Filter = "pdf files (*.pdf)|*.pdf";
postfix = ".pdf";
break;
case Autodesk.Revit.DB.VirtualPrinterType.DWFWriter:
saveDlg.Filter = "dwf files (*.dwf)|*.dwf";
postfix = ".dwf";
break;
case Autodesk.Revit.DB.VirtualPrinterType.None:
saveDlg.Filter = "prn files (*.prn)|*.prn";
postfix = ".prn";
break;
case VirtualPrinterType.XPSWriter:
saveDlg.Filter = "XPS files (*.xps)|*.xps";
postfix = ".xps";
break;
default:
break;
}

string title = m_commandData.Application.ActiveUIDocument.Document.Title;
if (title.Contains(".rvt"))
{
saveDlg.FileName = title.Remove(title.LastIndexOf(".")) + postfix;
}
else
{
saveDlg.FileName = title + postfix;
}

if (saveDlg.ShowDialog() == DialogResult.OK)
{
return m_printMgr.PrintToFileName
= saveDlg.FileName;
}
else
{
return null;
}
}
}

public Autodesk.Revit.DB.PrintRange PrintRange
{
get
{
return m_printMgr.PrintRange;
}
set
{
m_printMgr.PrintRange = value;
m_printMgr.Apply();
}
}

public bool Collate
{
get
{
return m_printMgr.Collate;
}
set
{
m_printMgr.Collate = value;
m_printMgr.Apply();
}
}

public int CopyNumber
{
get
{
return m_printMgr.CopyNumber;
}
set
{
m_printMgr.CopyNumber = value;
m_printMgr.Apply();
}
}

public bool PrintOrderReverse
{
get
{
return m_printMgr.PrintOrderReverse;
}
set
{
m_printMgr.PrintOrderReverse = value;
m_printMgr.Apply();
}
}

public string SelectedViewSheetSetName
{
get
{
IViewSheetSet theSet = m_printMgr.ViewSheetSetting.CurrentViewSheetSet;
return (theSet is ViewSheetSet) ?
(theSet as ViewSheetSet).Name : ConstData.InSessionName;
}
}

public string DocumentTitle
{
get
{
string title = m_commandData.Application.ActiveUIDocument.Document.Title;
if (title.Contains(".rvt"))
{
return title.Remove(title.LastIndexOf(".")) + PostFix;
}
else
{
return title + PostFix;
}
}
}

public string PostFix
{
get
{
string postfix = null;
switch (m_printMgr.IsVirtual)
{
case Autodesk.Revit.DB.VirtualPrinterType.AdobePDF:
postfix = ".pdf";
break;
case Autodesk.Revit.DB.VirtualPrinterType.DWFWriter:
postfix = ".dwf";
break;
case Autodesk.Revit.DB.VirtualPrinterType.XPSWriter:
postfix = ".xps";
break;
case Autodesk.Revit.DB.VirtualPrinterType.None:
postfix = ".prn";
break;
default:
break;
}

return postfix;
}
}

public void ChangePrintSetup()
{
using (PrintSetupForm dlg = new PrintSetupForm(
new PrintSTP(m_printMgr, m_commandData)))
{
dlg.ShowDialog();
}
}

public void SelectViewSheetSet()
{
using (viewSheetSetForm dlg = new viewSheetSetForm(
new ViewSheets(m_commandData.Application.ActiveUIDocument.Document)))
{
dlg.ShowDialog();
}
}

public bool SubmitPrint()
{
return m_printMgr.SubmitPrint();
}

public bool VerifyPrintToFile(System.Windows.Forms.Control controlToEnableOrNot)
{
// Enable terms (or):
// 1. Print to non-virtual printer.
return controlToEnableOrNot.Enabled =
m_printMgr.IsVirtual == VirtualPrinterType.None ? true : false;
}

public bool VerifyCopies(Collection<System.Windows.Forms.Control> controlsToEnableOrNot)
{
// Enable terms (or):
// 1. Print to non-virtual priter (physical printer or OneNote), and
// the "Print to file" check box is NOT checked.
// Note: SnagIt is an exception

bool enableOrNot = m_printMgr.IsVirtual == VirtualPrinterType.None
&& !m_printMgr.PrintToFile;

try
{
int cn = m_printMgr.CopyNumber;
}
catch (Exception)
{
enableOrNot = false;
// Note: SnagIt is an exception
}

foreach (System.Windows.Forms.Control control in controlsToEnableOrNot)
{
control.Enabled = enableOrNot;
}

return enableOrNot;
}

public bool VerifyPrintToFileName(Collection<System.Windows.Forms.Control> controlsToEnableOrNot)
{
// Enable terms (or):
// 1. Print to virtual priter (PDF or DWF printer)
// 2. Print to none-virtual printer (physical printer or OneNote), and the
// "Print to file" check box is checked.
bool enableOrNot = (m_printMgr.IsVirtual != VirtualPrinterType.None)
|| (m_printMgr.IsVirtual == VirtualPrinterType.None
&& m_printMgr.PrintToFile);

foreach (System.Windows.Forms.Control control in controlsToEnableOrNot)
{
control.Enabled = enableOrNot;
}

return enableOrNot;
}

public bool VerifyPrintToSingleFile(System.Windows.Forms.Control controlToEnableOrNot)
{
// Enable terms (or):
// 1. Print to virtual priter (PDF or DWF printer)
return controlToEnableOrNot.Enabled = m_printMgr.IsVirtual != VirtualPrinterType.None;
}

public bool VerifyPrintToSeparateFile(System.Windows.Forms.Control controlToEnableOrNot)
{
// Enable terms (or):
// 1. Print to virtual priter (PDF or DWF printer) and Print range is select.
// 2. a) Print to none-virtual printer (physical printer or OneNote), b) the
// "Print to file" check box is checked, and c) the Print range is select

return controlToEnableOrNot.Enabled = ((m_printMgr.IsVirtual != VirtualPrinterType.None
&& m_printMgr.PrintRange == Autodesk.Revit.DB.PrintRange.Select)
|| (m_printMgr.IsVirtual == VirtualPrinterType.None
&& m_printMgr.PrintRange == Autodesk.Revit.DB.PrintRange.Select
&& m_printMgr.PrintToFile));
}

public bool VerifyCollate(System.Windows.Forms.Control controlToEnableOrNot)
{
// Enable terms (or):
// 1. a) Print range is select b) the copy number is more 1 c) and the Print to file
// is not selected.
int cn = 0;
try
{
cn = m_printMgr.CopyNumber;
}
catch (InvalidOperationException)
{
//The property CopyNumber is not available.
}

return controlToEnableOrNot.Enabled = m_printMgr.PrintRange == Autodesk.Revit.DB.PrintRange.Select
&& !m_printMgr.PrintToFile
&& cn > 1;
}

public bool VerifySelectViewSheetSet(Collection<System.Windows.Forms.Control> controlsToEnableOrNot)
{
// Enable terms (or):
// 1. Print range is select.
bool enableOrNot = m_printMgr.PrintRange == Autodesk.Revit.DB.PrintRange.Select;
foreach (System.Windows.Forms.Control control in controlsToEnableOrNot)
{
control.Enabled = enableOrNot;
}

return enableOrNot;
}

/// <summary>
/// global and consistent for message box with same caption
/// </summary>
/// <param name="text">MessageBox's text.</param>
public static void MyMessageBox(string text)
{
TaskDialog.Show("View Printer", text);
}
}
}

PrintSTP.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Forms;

using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

namespace Revit.SDK.Samples.ViewPrinter.CS
{
/// <summary>
/// Change and save printer setup setting, exposes the print parameters just
/// like the Print Setup Dialog (File->Print Setup...) in UI such as Printer name,
/// paper, zoom, options, etc.
/// </summary>
public class PrintSTP : ISettingNameOperation
{
private ExternalCommandData m_commandData;
private PrintManager m_printMgr;

public PrintSTP(PrintManager printMgr
, ExternalCommandData commandData)
{
m_commandData = commandData;
m_printMgr = printMgr;
}

public string PrinterName
{
get
{
return m_printMgr.PrinterName;
}
}

public string Prefix
{
get
{
return "Default ";
}
}

public int SettingCount
{
get
{
return m_commandData.Application.ActiveUIDocument.Document.GetPrintSettingIds().Count;
}
}

public bool SaveAs(string newName)
{
try
{
return m_printMgr.PrintSetup.SaveAs(newName);
}
catch (Exception ex)
{
PrintMgr.MyMessageBox(ex.Message);
return false;
}
}

public bool Rename(string name)
{
try
{
return m_printMgr.PrintSetup.Rename(name);
}
catch (Exception ex)
{
PrintMgr.MyMessageBox(ex.Message);
return false;
}
}

public List<string> PrintSettingNames
{
get
{
List<string> names = new List<string>();
//foreach (Element printSetting in m_commandData.Application.ActiveUIDocument.Document.PrintSettings)
ICollection<ElementId> printSettingIds = m_commandData.Application.ActiveUIDocument.Document.GetPrintSettingIds();
foreach (ElementId eid in printSettingIds)
{
Element printSetting = m_commandData.Application.ActiveUIDocument.Document.GetElement(eid);
names.Add(printSetting.Name);
}
names.Add(ConstData.InSessionName);
return names;
}
}

public string SettingName
{
get
{
IPrintSetting setting = m_printMgr.PrintSetup.CurrentPrintSetting;
return (setting is PrintSetting) ?
(setting as PrintSetting).Name : ConstData.InSessionName;
}
set
{
if (value == ConstData.InSessionName)
{
m_printMgr.PrintSetup.CurrentPrintSetting = m_printMgr.PrintSetup.InSession;
return;
}
//foreach (Element printSetting in m_commandData.Application.ActiveUIDocument.Document.PrintSettings)
ICollection<ElementId> printSettingIds = m_commandData.Application.ActiveUIDocument.Document.GetPrintSettingIds();
foreach (ElementId eid in printSettingIds)
{
Element printSetting = m_commandData.Application.ActiveUIDocument.Document.GetElement(eid);
if (printSetting.Name.Equals(value))
{
m_printMgr.PrintSetup.CurrentPrintSetting = printSetting as PrintSetting;
}
}
}
}

public List<string> PaperSizes
{
get
{
List<string> names = new List<string>();
foreach (PaperSize ps in m_printMgr.PaperSizes)
{
names.Add(ps.Name);
}
return names;
}
}

public string PaperSize
{
get
{
try
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.PaperSize.Name;
}
catch (Exception)
{
return null;
}
}
set
{
foreach (PaperSize ps in m_printMgr.PaperSizes)
{
if (ps.Name.Equals(value))
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.PaperSize = ps;
break;
}
}
}
}

public List<string> PaperSources
{
get
{
List<string> names = new List<string>();
foreach (PaperSource ps in m_printMgr.PaperSources)
{
names.Add(ps.Name);
}
return names;
}
}

public string PaperSource
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.PaperSource.Name;
}
set
{
foreach (PaperSource ps in m_printMgr.PaperSources)
{
if (ps.Name.Equals(value))
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.PaperSource = ps;
break;
}
}
}
}

public PageOrientationType PageOrientation
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.PageOrientation;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.PageOrientation = value;
}
}

public PaperPlacementType PaperPlacement
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.PaperPlacement;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.PaperPlacement = value;
}
}

public Array MarginTypes
{
get
{
return Enum.GetValues(typeof(MarginType));
}
}

public MarginType SelectedMarginType
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.MarginType;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.MarginType = value;
}
}

public double UserDefinedMarginX
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.UserDefinedMarginX;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.UserDefinedMarginX = value;
}
}

public double UserDefinedMarginY
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.UserDefinedMarginY;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.UserDefinedMarginY = value;
}
}

public HiddenLineViewsType HiddenLineViews
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.HiddenLineViews;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.HiddenLineViews = value;
}
}

public int Zoom
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.Zoom;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.Zoom = value;
}
}

public ZoomType ZoomType
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.ZoomType;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.ZoomType = value;
}
}

public Array RasterQualities
{
get
{
return Enum.GetValues(typeof(RasterQualityType));
}
}

public RasterQualityType RasterQuality
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.RasterQuality;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.RasterQuality = value;
}
}

public Array Colors
{
get
{
return Enum.GetValues(typeof(ColorDepthType));
}
}

public ColorDepthType Color
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.ColorDepth;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.ColorDepth = value;
}
}

public bool ViewLinksinBlue
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.ViewLinksinBlue;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.ViewLinksinBlue = value;
}
}

public bool HideScopeBoxes
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.HideScopeBoxes;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.HideScopeBoxes = value;
}
}

public bool HideReforWorkPlanes
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.HideReforWorkPlanes;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.HideReforWorkPlanes = value;
}
}

public bool HideCropBoundaries
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.HideCropBoundaries;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.HideCropBoundaries = value;
}
}

public bool HideUnreferencedViewTags
{
get
{
return m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.HideUnreferencedViewTags;
}
set
{
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.HideUnreferencedViewTags = value;
}
}

public bool Save()
{
try
{
return m_printMgr.PrintSetup.Save();
}
catch (Exception ex)
{
PrintMgr.MyMessageBox(ex.Message);
return false;
}
}

public void Revert()
{
try
{
m_printMgr.PrintSetup.Revert();
}
catch (Exception ex)
{
PrintMgr.MyMessageBox(ex.Message);
}
}

public bool Delete()
{
try
{
return m_printMgr.PrintSetup.Delete();
}
catch (Exception ex)
{
PrintMgr.MyMessageBox(ex.Message);
return false;
}
}

public bool VerifyMarginType(System.Windows.Forms.Control controlToEnableOrNot)
{
// Enable terms (or):
// 1. Paper placement is Margins.
return controlToEnableOrNot.Enabled =
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.PaperPlacement == PaperPlacementType.Margins;
}

public bool VerifyUserDefinedMargin(Collection<System.Windows.Forms.Control> controlsToEnableOrNot)
{
bool enableOrNot =
m_printMgr.PrintSetup.CurrentPrintSetting.PrintParameters.MarginType == MarginType.UserDefined;

foreach (System.Windows.Forms.Control control in controlsToEnableOrNot)
{
control.Enabled = enableOrNot;
}

return enableOrNot;
}
}
}

ViewSheets.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using Autodesk.Revit;
using Autodesk.Revit.DB;
namespace Revit.SDK.Samples.ViewPrinter.CS
{
    public enum VisibleType
    {
        VT_ViewOnly,
        VT_SheetOnly,
        VT_BothViewAndSheet,
        VT_None
    }
    public interface ISettingNameOperation
    {
        string SettingName
        {
            get;
            set;
        }
        string Prefix
        {
            get;
        }
        int SettingCount
        {
            get;
        }
        bool Rename(string name);
        bool SaveAs(string newName);
    }
    /// <summary>
    /// Define some config data which is useful in this sample.
    /// </summary>
    public static class ConstData
    {
        /// <summary>
        /// The const string data which is used as the name 
        /// for InSessionPrintSetting and InSessionViewSheetSet data
        /// </summary>
        public const string InSessionName = "<In-Session>";
    }
    /// <summary>
    /// Exposes the View/Sheet Set interfaces just like 
    /// the View/Sheet Set Dialog (File->Print...; selected views/sheets->Select...) in UI.
    /// </summary>
    public class ViewSheets : ISettingNameOperation
    {
        Document m_doc;
        ViewSheetSetting m_viewSheetSetting;
        public ViewSheets(Document doc)
        {
            m_doc = doc;
            m_viewSheetSetting = doc.PrintManager.ViewSheetSetting;
        }
        public string SettingName
        {
            get
            {
                IViewSheetSet theSet = m_viewSheetSetting.CurrentViewSheetSet;
                return (theSet is ViewSheetSet) ?
                    (theSet as ViewSheetSet).Name : ConstData.InSessionName;
            }
            set
            {
                if (value == ConstData.InSessionName)
                {
                    m_viewSheetSetting.CurrentViewSheetSet = m_viewSheetSetting.InSession;
                    return;
                }
                FilteredElementCollector filteredElementCollector = new FilteredElementCollector(m_doc);
                filteredElementCollector.OfClass(typeof(ViewSheetSet));
                IEnumerable<ViewSheetSet> viewSheetSets = filteredElementCollector.Cast<ViewSheetSet>().Where<ViewSheetSet>(viewSheetSet => viewSheetSet.Name.Equals(value as string));
                if (viewSheetSets.Count<ViewSheetSet>() > 0)
                {
                    m_viewSheetSetting.CurrentViewSheetSet = viewSheetSets.First<ViewSheetSet>();
                }
            }
        }
        public string Prefix
        {
            get
            {
                return "Set ";
            }
        }
        public int SettingCount
        {
            get
            {
                return (new FilteredElementCollector(m_doc)).OfClass(typeof(ViewSheetSet)).ToElementIds().Count;
            }
        }
        public bool SaveAs(string newName)
        {
            try
            {
                return m_viewSheetSetting.SaveAs(newName);
            }
            catch (Exception ex)
            {
                PrintMgr.MyMessageBox(ex.Message);
                return false;
            }
        }
        public bool Rename(string name)
        {
            try
            {
                return m_viewSheetSetting.Rename(name);
            }
            catch (Exception ex)
            {
                PrintMgr.MyMessageBox(ex.Message);
                return false;
            }
        }
        public List<string> ViewSheetSetNames
        {
            get
            {
                List<string> names = new List<string>();
                FilteredElementCollector filteredElementCollector = new FilteredElementCollector(m_doc);
                filteredElementCollector.OfClass(typeof(ViewSheetSet));
                foreach (Element element in filteredElementCollector)
                {
                    ViewSheetSet viewSheetSet = element as ViewSheetSet;
                    names.Add(viewSheetSet.Name);
                }
                names.Add(ConstData.InSessionName);
                return names;
            }
        }
        public bool Save()
        {
            try
            {
                return m_viewSheetSetting.Save();
            }
            catch (Exception)
            {
                return false;
            }
        }
        public void Revert()
        {
            try
            {
                m_viewSheetSetting.Revert();
            }
            catch (Exception ex)
            {
                PrintMgr.MyMessageBox(ex.Message);
            }
        }
        public bool Delete()
        {
            try
            {
                return m_viewSheetSetting.Delete();
            }
            catch (Exception ex)
            {
                PrintMgr.MyMessageBox(ex.Message);
                return false;
            }
        }
        public List<Autodesk.Revit.DB.View> AvailableViewSheetSet(VisibleType visibleType)
        {
            if (visibleType == VisibleType.VT_None)
                return null;
            List<Autodesk.Revit.DB.View> views = new List<Autodesk.Revit.DB.View>();
            foreach (Autodesk.Revit.DB.View view in m_viewSheetSetting.AvailableViews)
            {
                if (view.ViewType == Autodesk.Revit.DB.ViewType.DrawingSheet
                    && visibleType == VisibleType.VT_ViewOnly)
                {
                    continue;   // filter out sheets.
                }
                if (view.ViewType != Autodesk.Revit.DB.ViewType.DrawingSheet
                    && visibleType == VisibleType.VT_SheetOnly)
                {
                    continue;   // filter out views.
                }
                views.Add(view);
            }
            return views;
        }
        public bool IsSelected(string viewName)
        {
            foreach (Autodesk.Revit.DB.View view in m_viewSheetSetting.CurrentViewSheetSet.Views)
            {
                if (viewName.Equals(view.ViewType.ToString() + ": " + view.Name))
                {
                    return true;
                }
            }
            return false;
        }
        public void ChangeCurrentViewSheetSet(List<string> names)
        {
            ViewSet selectedViews = new ViewSet();
            if (null != names && 0 < names.Count)
            {
                foreach (Autodesk.Revit.DB.View view in m_viewSheetSetting.AvailableViews)
                {
                    if (names.Contains(view.ViewType.ToString() + ": " + view.Name))
                    {
                        selectedViews.Insert(view);
                    }
                }
            }
            IViewSheetSet viewSheetSet = m_viewSheetSetting.CurrentViewSheetSet;
            viewSheetSet.Views = selectedViews;
            Save();
        }
    }
}