本帖最后由 qq1254582201 于 2025-11-13 11:05 编辑
  1. /// <summary>
  2. /// 将字符串或列表写入文件(Unix格式)
  3. /// </summary>
  4. public static string VldosWriteFile(string filePath, object content, bool overwrite = false)
  5. {
  6.     try
  7.     {
  8.         if (content == null) return null;

  9.         // 如果指定覆盖模式且文件存在,先删除
  10.         if (overwrite && File.Exists(filePath))
  11.         {
  12.             File.Delete(filePath);
  13.         }

  14.         string textContent;

  15.         // 处理字符串或字符串列表
  16.         if (content is string str)
  17.         {
  18.             textContent = str;
  19.         }
  20.         else if (content is List<string> strList)
  21.         {
  22.             // 使用Unix换行符(LF)而不是Windows换行符(CRLF)
  23.             textContent = string.Join("\n", strList);
  24.             
  25.         }
  26.         else
  27.         {
  28.             throw new ArgumentException("内容必须是字符串或字符串列表");
  29.         }

  30.         // 确保目录存在
  31.         string directory = Path.GetDirectoryName(filePath);
  32.         if (!Directory.Exists(directory))
  33.         {
  34.             Directory.CreateDirectory(directory);
  35.         }

  36.         // 写入文件,使用Unix换行符
  37.         // 使用UTF-8编码,无BOM,这是Unix系统的标准
  38.         using (StreamWriter writer = new StreamWriter(filePath, false, new UTF8Encoding(false)))
  39.         {
  40.             writer.Write(textContent);
  41.         }

  42.         // 返回格式化后的路径
  43.         return FormatPath(Path.GetFullPath(filePath));
  44.     }
  45.     catch (Exception ex)
  46.     {
  47.         Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n写入文件错误: {ex.Message}");
  48.         return null;
  49.     }
  50. }

  51. /// <summary>
  52. /// 格式化文件路径
  53. /// </summary>
  54. public static string FormatPath(string path)
  55. {
  56.     if (string.IsNullOrEmpty(path)) return path;

  57.     // 统一反斜杠并转为大写
  58.     return Path.GetFullPath(path)
  59.                .Replace("/", "\")
  60.                .ToUpper();
  61. }

  62. /// <summary>
  63. /// 获取AutoCAD驱动程序路径
  64. /// </summary>
  65. private static string GetAcadDriverPath()
  66. {
  67.     try
  68.     {
  69.         // 方法1: 从环境变量获取
  70.         string acadDrv = Environment.GetEnvironmentVariable("ACADDRV");
  71.         if (!string.IsNullOrEmpty(acadDrv) && Directory.Exists(acadDrv))
  72.             return acadDrv;

  73.         // 方法2: 从注册表获取AutoCAD安装路径
  74.         string acadVersion = Application.Version.Major.ToString();
  75.         string registryPath = $@"SOFTWARE\Autodesk\AutoCAD\{acadVersion}.0\ACAD-8001:804";

  76.         using (RegistryKey key = Registry.LocalMachine.OpenSubKey(registryPath))
  77.         {
  78.             if (key != null)
  79.             {
  80.                 string acadLocation = key.GetValue("AcadLocation") as string;
  81.                 if (!string.IsNullOrEmpty(acadLocation))
  82.                 {
  83.                     string drvPath = Path.Combine(acadLocation, "Drv");
  84.                     if (Directory.Exists(drvPath))
  85.                         return drvPath;
  86.                 }
  87.             }
  88.         }

  89.         // 方法3: 从当前进程路径推断
  90.         string processPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
  91.         string acadDir = Path.GetDirectoryName(processPath);
  92.         if (!string.IsNullOrEmpty(acadDir))
  93.         {
  94.             string drvPath = Path.Combine(acadDir, "Drv");
  95.             if (Directory.Exists(drvPath))
  96.                 return drvPath;
  97.         }

  98.         // 方法4: 最后的备用方案
  99.         return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
  100.                           "Autodesk", "AutoCAD", "Drv");
  101.     }
  102.     catch (Exception ex)
  103.     {
  104.         Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n获取驱动程序路径错误: {ex.Message}");
  105.         return "C:\\Program Files\\Autodesk\\AutoCAD\\Drv"; // 默认路径
  106.     }
  107. }

  108. /// <summary>
  109. /// 获取PDF驱动程序文件名(根据AutoCAD版本)
  110. /// </summary>
  111. private static string GetPdfDriverFileName()
  112. {
  113.     try
  114.     {
  115.         int acadVersion = Application.Version.Major;
  116.         int pdfVersion = acadVersion - 8; // 根据AutoCAD版本计算

  117.         // 检查文件是否存在
  118.         string driverPath = GetAcadDriverPath();
  119.         string fileName = $"pdfplot{pdfVersion}.hdi";
  120.         string fullPath = Path.Combine(driverPath, fileName);

  121.         if (File.Exists(fullPath))
  122.             return fileName;

  123.         // 如果特定版本的文件不存在,尝试查找任何pdfplot*.hdi文件
  124.         string[] pdfDrivers = Directory.GetFiles(driverPath, "pdfplot*.hdi");
  125.         if (pdfDrivers.Length > 0)
  126.         {
  127.             return Path.GetFileName(pdfDrivers[0]); // 返回找到的第一个
  128.         }

  129.         // 最后回退到默认名称
  130.         return "pdfplot.hdi";
  131.     }
  132.     catch
  133.     {
  134.         return "pdfplot.hdi"; // 默认名称
  135.     }
  136. }

  137. /// <summary>
  138. /// 生成PMP文件(Unix格式)
  139. /// </summary>
  140. public static void CreatePmpFile(string pmpPath, string paperName, double width, double height)
  141. {
  142.     try
  143.     {
  144.         // 获取AutoCAD版本信息
  145.         string acadVer = Application.Version.Major.ToString();
  146.         string roamableRoot = Application.GetSystemVariable("ROAMABLEROOTPREFIX") as string;

  147.         // 使用新的方法获取驱动程序路径和文件名
  148.         string acadDrv = GetAcadDriverPath();
  149.         string driverFileName = GetPdfDriverFileName();

  150.         // PMP文件模板 - 使用Unix换行符
  151.         var pmpLines = new List<string>
  152.     {
  153.         "PIAFILEVERSION_2.0,PC3VER1",
  154.         "meta{",
  155.         $" user_defined_model_pathname="{roamableRoot}Plotters\\PMP Files\\DWG To PDF.pmp",
  156.         " user_defined_model_basename="",
  157.         $" driver_pathname="{acadDrv}\\{driverFileName}",
  158.         " driver_version="1.1-11.0.55.0 [v018-1]",
  159.         " driver_tag_line="PDF Plot - by Autodesk",
  160.         " toolkit_version=1",
  161.         " driver_type=3",
  162.         " canonical_family_name="Autodesk ePlot",
  163.         " show_custom_first=FALSE",
  164.         " truetype_as_text=TRUE",
  165.         " canonical_model_name="pdf",
  166.         " localized_family_name="Autodesk ePlot (PDF)",
  167.         " localized_model_name="PDF",
  168.         " file_only=TRUE",
  169.         " model_abilities="000550055000",
  170.         " udm_description="",
  171.         " short_net_name="",
  172.         " friendly_net_name="",
  173.         " dm_driver_version=0",
  174.         " default_system_cfg=FALSE",
  175.         " platform="2,6,1",
  176.         " locale="4B00409",
  177.         "}",
  178.         "mod{",
  179.         " media{",
  180.         "  abilities="500005500500505555000005550000000550000500000500000",
  181.         "  caps_state="000000000000000000000000000000000000000000000000000",
  182.         "  ui_owner="11111111111111111111110",
  183.         "  size_max_x=5080.0",
  184.         "  size_max_y=5080.0",
  185.         " }",
  186.         "}",
  187.         "del{",
  188.         " media{",
  189.         "  abilities="500005500500505555000005550000000550000500000500000",
  190.         "  caps_state="000000000000000000000000000000000000000000000000000",
  191.         "  ui_owner="11111111111111111111110",
  192.         "  size_max_x=5080.0",
  193.         "  size_max_y=5080.0",
  194.         " }",
  195.         "}",
  196.         "udm{",
  197.         " calibration{",
  198.         "  _x=1.0",
  199.         "  _y=1.0",
  200.         " }",
  201.         " media{",
  202.         "  abilities="500005500500505555000005550000000550000500000500000",
  203.         "  caps_state="000000000000000000000000000000000000000000000000000",
  204.         "  ui_owner="11111111111111111111110",
  205.         "  size_max_x=5080.0",
  206.         "  size_max_y=5080.0",
  207.         "  size{",
  208.         "   0{",
  209.         "    caps_type=2",
  210.         $"    name="UserDefinedMetric {width:F1}×{height:F1} 毫米",
  211.         $"    localized_name="{paperName}",
  212.         $"    media_description_name="UserDefinedMetric 纵向 {width:F1}W x {height:F1}H - (0, 0) x ({width:F0}, {height:F0}) ={width * height:F0} 纵向 x",
  213.         "    media_group=15",
  214.         "    landscape_mode=TRUE",
  215.         "   }",
  216.         " }",
  217.         "  description{",
  218.         "   0{",
  219.         "    caps_type=2",
  220.         $"    name="UserDefinedMetric 纵向 {width:F1}W x {height:F1}H - (0, 0) x ({width:F0}, {height:F0}) ={width * height:F0} 纵向 x",
  221.         $"    media_bounds_urx={width:F1}",
  222.         $"    media_bounds_ury={height:F1}",
  223.         "    printable_bounds_llx=0.0",
  224.         "    printable_bounds_lly=0.0",
  225.         $"    printable_bounds_urx={width:F1}",
  226.         $"    printable_bounds_ury={height:F1}",
  227.         $"    printable_area={width * height:F1}",
  228.         "    dimensional=TRUE",
  229.         "}}}}}",
  230.         "hidden{",
  231.         " media{",
  232.         "  abilities="500005500500505555000005550000000550000500000500000",
  233.         "  caps_state="000000000000000000000000000000000000000000000000000",
  234.         "  ui_owner="11111111111111111111110",
  235.         "  size_max_x=5080.0",
  236.         "  size_max_y=5080.0",
  237.         " }",
  238.         "}"
  239.     };

  240.         VldosWriteFile(pmpPath, pmpLines, true);
  241.     }
  242.     catch (Exception ex)
  243.     {
  244.         Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n创建PMP文件错误: {ex.Message}");
  245.     }
  246. }

  247. /// <summary>
  248. /// 生成PC3文件(Unix格式)
  249. /// </summary>
  250. public static void CreatePc3File(string pc3Path, string pmpPath, string paperName, double width, double height)
  251. {
  252.     try
  253.     {
  254.         // 先创建PMP文件
  255.         CreatePmpFile(pmpPath, paperName, width, height);

  256.         string acadVer = Application.Version.Major.ToString();
  257.         string roamableRoot = Application.GetSystemVariable("ROAMABLEROOTPREFIX") as string;

  258.         // 使用新的方法获取驱动程序路径和文件名
  259.         string acadDrv = GetAcadDriverPath();
  260.         string driverFileName = GetPdfDriverFileName();

  261.         // PC3文件基础部分 - 使用Unix换行符
  262.         var pc3Lines = new List<string>
  263.     {
  264.         "PIAFILEVERSION_2.0,PC3VER1",
  265.         "meta{",
  266.         $" user_defined_model_pathname="{pmpPath}",
  267.         " user_defined_model_basename= "",
  268.         $" driver_pathname="{acadDrv}\\{driverFileName}",
  269.         " driver_version= "1.0-16.0.47.0 [v018-1]",
  270.         " driver_tag_line= "PDF Plot - by Autodesk",
  271.         " toolkit_version=1",
  272.         " driver_type=3",
  273.         " canonical_family_name= "Autodesk ePlot",
  274.         " show_custom_first=FALSE",
  275.         " truetype_as_text=TRUE",
  276.         " canonical_model_name= "pdf",
  277.         " localized_family_name= "Autodesk ePlot (PDF)",
  278.         " localized_model_name= "PDF",
  279.         " file_only=TRUE",
  280.         " model_abilities= "000550055000",
  281.         " udm_description= "",
  282.         " short_net_name= "",
  283.         " friendly_net_name= "",
  284.         " dm_driver_version=0",
  285.         " default_system_cfg=FALSE",
  286.         " platform= "2,10,0",
  287.         " locale= "4B00409",
  288.         " config_description= "",
  289.         " config_autospool=FALSE",
  290.         "}",
  291.         "media{",
  292.         " selection_method=2",
  293.         " type= "",
  294.         " dm_orientation=1",
  295.         " actual_printable_bounds_llx=5.0",
  296.         " actual_printable_bounds_lly=17.0",
  297.         " actual_printable_bounds_urx=205.0",
  298.         " actual_printable_bounds_ury=280.0",
  299.         " number_of_copies=1",
  300.         " size{",
  301.         "  name= "ISO_A4_(210.00_x_297.00_MM)",
  302.         "  group=4",
  303.         "  landscape_mode=FALSE",
  304.         "  longplot_reduction=1.0",
  305.         "  media_description{",
  306.         "   printable_bounds_llx=5.0",
  307.         "   printable_bounds_lly=17.0",
  308.         "   printable_bounds_urx=205.0",
  309.         "   printable_bounds_ury=280.0",
  310.         "   printable_area=52600.0",
  311.         "   dimensional=TRUE",
  312.         "   media_bounds{",
  313.         "    urx=210.0",
  314.         "    ury=297.0",
  315.         "   }",
  316.         "  }",
  317.         " }",
  318.         "}",
  319.         "io{",
  320.         " type=2",
  321.         " pathname= "",
  322.         " allsysvalid=FALSE",
  323.         " plot_to_file=TRUE",
  324.         "}",
  325.         "res_color_mem{",
  326.         " name= "RGB",
  327.         " num_colors=16777216",
  328.         " color_depth=24",
  329.         " num_undithered_colors=16777216",
  330.         " color_system=1",
  331.         " dm_color=1",
  332.         " lines_overwrite=TRUE",
  333.         " resolution{",
  334.         "  name= "Default",
  335.         "  phys_resolution_x=400.0",
  336.         "  phys_resolution_y=400.0",
  337.         "  addr_resolution_x=1.0",
  338.         "  addr_resolution_y=1.0",
  339.         "  effective_resolution_x=400.0",
  340.         "  effective_resolution_y=400.0",
  341.         " }",
  342.         "}"
  343.     };

  344.         // 根据AutoCAD版本添加对应的自定义配置
  345.         if (int.Parse(acadVer) >= 18) // AutoCAD 2010及以上版本
  346.         {
  347.             pc3Lines.AddRange(new[]
  348.             {
  349.             "custom{",
  350.             " 0{",
  351.             "  name= "Custom_Raster_Resolution",
  352.             "  value=FALSE",
  353.             " }",
  354.             " 1{",
  355.             "  name= "Custom_DWF_Resolution",
  356.             "  value=FALSE",
  357.             " }",
  358.             " 2{",
  359.             "  name= "Custom_Monochrome_Resolution",
  360.             "  value=FALSE",
  361.             " }",
  362.             " 3{",
  363.             "  name= "Custom_Gradient_Resolution",
  364.             "  value=FALSE",
  365.             " }",
  366.             " 4{",
  367.             "  name= "Gradient_Limit",
  368.             "  value=400",
  369.             " }",
  370.             " 5{",
  371.             "  name= "Monochrome_Raster_Limit",
  372.             "  value=400",
  373.             " }",
  374.             " 6{",
  375.             "  name= "Raster_Limit",
  376.             "  value=400",
  377.             " }",
  378.             " 7{",
  379.             "  name= "All_As_Geometry",
  380.             "  value=TRUE",
  381.             " }",
  382.             " 8{",
  383.             "  name= "Capture",
  384.             "  value=1",
  385.             " }",
  386.             " 9{",
  387.             "  name= "Hardcopy_Resolution",
  388.             "  value=400",
  389.             " }",
  390.             " 10{",
  391.             "  name= "Font_Capture",
  392.             "  value=FALSE",
  393.             " }",
  394.             " 11{",
  395.             "  name= "Include_Layer",
  396.             "  value=TRUE",
  397.             " }",
  398.             " 12{",
  399.             "  name= "Resolution",
  400.             "  value=14",
  401.             " }",
  402.             "}"
  403.         });
  404.         }
  405.         else // AutoCAD 2008及以下版本
  406.         {
  407.             pc3Lines.AddRange(new[]
  408.             {
  409.             "custom{",
  410.             " 0{",
  411.             "  name= "Custom_Raster_Resolution",
  412.             "  value=FALSE",
  413.             " }",
  414.             " 1{",
  415.             "  name= "Custom_DWF_Resolution",
  416.             "  value=FALSE",
  417.             " }",
  418.             " 2{",
  419.             "  name= "Custom_Monochrome_Resolution",
  420.             "  value=FALSE",
  421.             " }",
  422.             " 3{",
  423.             "  name= "Custom_Gradient_Resolution",
  424.             "  value=FALSE",
  425.             " }",
  426.             " 4{",
  427.             "  name= "Gradient_Limit",
  428.             "  value=400",
  429.             " }",
  430.             " 5{",
  431.             "  name= "Monochrome_Raster_Limit",
  432.             "  value=400",
  433.             " }",
  434.             " 6{",
  435.             "  name= "Raster_Limit",
  436.             "  value=400",
  437.             " }",
  438.             " 7{",
  439.             "  name= "All_As_Geometry",
  440.             "  value=TRUE",
  441.             " }",
  442.             " 8{",
  443.             "  name= "Include_Preview",
  444.             "  value=FALSE",
  445.             " }",
  446.             " 9{",
  447.             "  name= "Capture",
  448.             "  value=1",
  449.             " }",
  450.             " 10{",
  451.             "  name= "Thumbnail_And_Preview",
  452.             "  value=FALSE",
  453.             " }",
  454.             " 11{",
  455.             "  name= "SuperDWF_Opcodes",
  456.             "  value=TRUE",
  457.             " }",
  458.             " 12{",
  459.             "  name= "Optimized_For_Plotting",
  460.             "  value=TRUE",
  461.             " }",
  462.             " 13{",
  463.             "  name= "Hardcopy_Resolution",
  464.             "  value=400",
  465.             " }",
  466.             " 14{",
  467.             "  name= "Font_Capture",
  468.             "  value=TRUE",
  469.             " }",
  470.             " 15{",
  471.             "  name= "Color_Depth_Control",
  472.             "  value=TRUE",
  473.             " }",
  474.             " 16{",
  475.             "  name= "File_Format",
  476.             "  value=50",
  477.             " }",
  478.             " 17{",
  479.             "  name= "Show_Paper_Boundaries",
  480.             "  value=FALSE",
  481.             " }",
  482.             " 18{",
  483.             "  name= "Convert_DWG_to_DWF",
  484.             "  value=FALSE",
  485.             " }",
  486.             " 19{",
  487.             "  name= "Include_Measurement",
  488.             "  value=TRUE",
  489.             " }",
  490.             " 20{",
  491.             "  name= "Include_Scale",
  492.             "  value=TRUE",
  493.             " }",
  494.             " 21{",
  495.             "  name= "Include_Layer",
  496.             "  value=TRUE",
  497.             " }",
  498.             " 22{",
  499.             "  name= "Background_Color",
  500.             "  value=16777215",
  501.             " }",
  502.             " 23{",
  503.             "  name= "Format",
  504.             "  value=2",
  505.             " }",
  506.             " 24{",
  507.             "  name= "Resolution",
  508.             "  value=14",
  509.             " }",
  510.             "}"
  511.         });
  512.         }

  513.         // 写入PC3文件(Unix格式)
  514.         VldosWriteFile(pc3Path, pc3Lines, true);

  515.         Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\nPC3文件已创建: {pc3Path}");
  516.     }
  517.     catch (Exception ex)
  518.     {
  519.         Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n创建PC3文件错误: {ex.Message}");
  520.     }
  521. }

  522. /// <summary>
  523. /// 主命令:创建自定义PDF打印配置
  524. /// </summary>
  525. [CommandMethod("TTDD2")]
  526. public static void CreateCustomPlotConfig2()
  527. {
  528.     try
  529.     {
  530.         Document doc = Application.DocumentManager.MdiActiveDocument;
  531.         Editor ed = doc.Editor;

  532.         // 获取用户输入的宽度和高度
  533.         var widthOpt = ed.GetDouble("\n输入图纸宽度: ");
  534.         if (widthOpt.Status != Autodesk.AutoCAD.EditorInput.PromptStatus.OK) return;

  535.         var heightOpt = ed.GetDouble("\n输入图纸高度: ");
  536.         if (heightOpt.Status != Autodesk.AutoCAD.EditorInput.PromptStatus.OK) return;

  537.         double width = widthOpt.Value;
  538.         double height = heightOpt.Value;

  539.         ed.WriteMessage($"\n图纸尺寸: {width:F2} x {height:F2}");

  540.         // 获取配置文件路径
  541.         string roamableRoot = Application.GetSystemVariable("ROAMABLEROOTPREFIX") as string;
  542.         string pc3Path = Path.Combine(roamableRoot, "Plotters", "zpdf.pc3");
  543.         string pmpPath = Path.Combine(roamableRoot, "Plotters", "PMP Files", "zpdf.pmp");

  544.         // 确保目录存在
  545.         Directory.CreateDirectory(Path.GetDirectoryName(pc3Path));
  546.         Directory.CreateDirectory(Path.GetDirectoryName(pmpPath));

  547.         // 创建PC3和PMP文件
  548.         CreatePc3File(pc3Path, pmpPath, "mysize123", width, height);

  549.         // 设置为当前布局的打印机
  550.         using (Database db = doc.Database)
  551.         {
  552.             //using (Transaction tr = db.TransactionManager.StartTransaction())
  553.             //{
  554.             //    LayoutManager layoutMgr = LayoutManager.Current;
  555.             //    Layout layout = tr.GetObject(layoutMgr.GetLayoutId(layoutMgr.CurrentLayout), OpenMode.ForWrite) as Layout;

  556.             //    if (layout != null)
  557.             //    {
  558.             //        layout.ConfigName = "zpdf.pc3";
  559.             //        tr.Commit();
  560.             //    }
  561.             //}
  562.         }

  563.         ed.WriteMessage("\n自定义PDF打印配置已创建并设为当前布局的打印机");
  564.     }
  565.     catch (Exception ex)
  566.     {
  567.         Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n错误: {ex.Message}");
  568.     }
  569. }
这是原贴地址:http://bbs.mjtd.com/thread-189649-1-1.html
字符串上传后错乱了:  /// <summary>
  /// 将字符串或列表写入文件(Unix格式)
  /// </summary>
  public static string VldosWriteFile(string filePath, object content, bool overwrite = false)
  {
      try
      {
          if (content == null) return null;

          // 如果指定覆盖模式且文件存在,先删除
          if (overwrite && File.Exists(filePath))
          {
              File.Delete(filePath);
          }

          string textContent;

          // 处理字符串或字符串列表
          if (content is string str)
          {
              textContent = str;
          }
          else if (content is List<string> strList)
          {
              // 使用Unix换行符(LF)而不是Windows换行符(CRLF)
              textContent = string.Join("\n", strList);
              
          }
          else
          {
              throw new ArgumentException("内容必须是字符串或字符串列表");
          }

          // 确保目录存在
          string directory = Path.GetDirectoryName(filePath);
          if (!Directory.Exists(directory))
          {
              Directory.CreateDirectory(directory);
          }

          // 写入文件,使用Unix换行符
          // 使用UTF-8编码,无BOM,这是Unix系统的标准
          using (StreamWriter writer = new StreamWriter(filePath, false, new UTF8Encoding(false)))
          {
              writer.Write(textContent);
          }

          // 返回格式化后的路径
          return FormatPath(Path.GetFullPath(filePath));
      }
      catch (Exception ex)
      {
          Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n写入文件错误: {ex.Message}");
          return null;
      }
  }

  /// <summary>
  /// 格式化文件路径
  /// </summary>
  public static string FormatPath(string path)
  {
      if (string.IsNullOrEmpty(path)) return path;

      // 统一反斜杠并转为大写
      return Path.GetFullPath(path)
                 .Replace("/", "\\")
                 .ToUpper();
  }

  /// <summary>
  /// 获取AutoCAD驱动程序路径
  /// </summary>
  private static string GetAcadDriverPath()
  {
      try
      {
          // 方法1: 从环境变量获取
          string acadDrv = Environment.GetEnvironmentVariable("ACADDRV");
          if (!string.IsNullOrEmpty(acadDrv) && Directory.Exists(acadDrv))
              return acadDrv;

          // 方法2: 从注册表获取AutoCAD安装路径
          string acadVersion = Application.Version.Major.ToString();
          string registryPath = $@"SOFTWARE\Autodesk\AutoCAD\{acadVersion}.0\ACAD-8001:804";

          using (RegistryKey key = Registry.LocalMachine.OpenSubKey(registryPath))
          {
              if (key != null)
              {
                  string acadLocation = key.GetValue("AcadLocation") as string;
                  if (!string.IsNullOrEmpty(acadLocation))
                  {
                      string drvPath = Path.Combine(acadLocation, "Drv");
                      if (Directory.Exists(drvPath))
                          return drvPath;
                  }
              }
          }

          // 方法3: 从当前进程路径推断
          string processPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
          string acadDir = Path.GetDirectoryName(processPath);
          if (!string.IsNullOrEmpty(acadDir))
          {
              string drvPath = Path.Combine(acadDir, "Drv");
              if (Directory.Exists(drvPath))
                  return drvPath;
          }

          // 方法4: 最后的备用方案
          return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
                            "Autodesk", "AutoCAD", "Drv");
      }
      catch (Exception ex)
      {
          Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n获取驱动程序路径错误: {ex.Message}");
          return "C:\\Program Files\\Autodesk\\AutoCAD\\Drv"; // 默认路径
      }
  }

  /// <summary>
  /// 获取PDF驱动程序文件名(根据AutoCAD版本)
  /// </summary>
  private static string GetPdfDriverFileName()
  {
      try
      {
          int acadVersion = Application.Version.Major;
          int pdfVersion = acadVersion - 8; // 根据AutoCAD版本计算

          // 检查文件是否存在
          string driverPath = GetAcadDriverPath();
          string fileName = $"pdfplot{pdfVersion}.hdi";
          string fullPath = Path.Combine(driverPath, fileName);

          if (File.Exists(fullPath))
              return fileName;

          // 如果特定版本的文件不存在,尝试查找任何pdfplot*.hdi文件
          string[] pdfDrivers = Directory.GetFiles(driverPath, "pdfplot*.hdi");
          if (pdfDrivers.Length > 0)
          {
              return Path.GetFileName(pdfDrivers[0]); // 返回找到的第一个
          }

          // 最后回退到默认名称
          return "pdfplot.hdi";
      }
      catch
      {
          return "pdfplot.hdi"; // 默认名称
      }
  }

  /// <summary>
  /// 生成PMP文件(Unix格式)
  /// </summary>
  public static void CreatePmpFile(string pmpPath, string paperName, double width, double height)
  {
      try
      {
          // 获取AutoCAD版本信息
          string acadVer = Application.Version.Major.ToString();
          string roamableRoot = Application.GetSystemVariable("ROAMABLEROOTPREFIX") as string;

          // 使用新的方法获取驱动程序路径和文件名
          string acadDrv = GetAcadDriverPath();
          string driverFileName = GetPdfDriverFileName();

          // PMP文件模板 - 使用Unix换行符
          var pmpLines = new List<string>
      {
          "PIAFILEVERSION_2.0,PC3VER1",
          "meta{",
          $" user_defined_model_pathname=\"{roamableRoot}Plotters\\PMP Files\\DWG To PDF.pmp",
          " user_defined_model_basename=\"",
          $" driver_pathname=\"{acadDrv}\\{driverFileName}",
          " driver_version=\"1.1-11.0.55.0 [v018-1]",
          " driver_tag_line=\"PDF Plot - by Autodesk",
          " toolkit_version=1",
          " driver_type=3",
          " canonical_family_name=\"Autodesk ePlot",
          " show_custom_first=FALSE",
          " truetype_as_text=TRUE",
          " canonical_model_name=\"pdf",
          " localized_family_name=\"Autodesk ePlot (PDF)",
          " localized_model_name=\"PDF",
          " file_only=TRUE",
          " model_abilities=\"000550055000",
          " udm_description=\"",
          " short_net_name=\"",
          " friendly_net_name=\"",
          " dm_driver_version=0",
          " default_system_cfg=FALSE",
          " platform=\"2,6,1",
          " locale=\"4B00409",
          "}",
          "mod{",
          " media{",
          "  abilities=\"500005500500505555000005550000000550000500000500000",
          "  caps_state=\"000000000000000000000000000000000000000000000000000",
          "  ui_owner=\"11111111111111111111110",
          "  size_max_x=5080.0",
          "  size_max_y=5080.0",
          " }",
          "}",
          "del{",
          " media{",
          "  abilities=\"500005500500505555000005550000000550000500000500000",
          "  caps_state=\"000000000000000000000000000000000000000000000000000",
          "  ui_owner=\"11111111111111111111110",
          "  size_max_x=5080.0",
          "  size_max_y=5080.0",
          " }",
          "}",
          "udm{",
          " calibration{",
          "  _x=1.0",
          "  _y=1.0",
          " }",
          " media{",
          "  abilities=\"500005500500505555000005550000000550000500000500000",
          "  caps_state=\"000000000000000000000000000000000000000000000000000",
          "  ui_owner=\"11111111111111111111110",
          "  size_max_x=5080.0",
          "  size_max_y=5080.0",
          "  size{",
          "   0{",
          "    caps_type=2",
          $"    name=\"UserDefinedMetric {width:F1}×{height:F1} 毫米",
          $"    localized_name=\"{paperName}",
          $"    media_description_name=\"UserDefinedMetric 纵向 {width:F1}W x {height:F1}H - (0, 0) x ({width:F0}, {height:F0}) ={width * height:F0} 纵向 x",
          "    media_group=15",
          "    landscape_mode=TRUE",
          "   }",
          " }",
          "  description{",
          "   0{",
          "    caps_type=2",
          $"    name=\"UserDefinedMetric 纵向 {width:F1}W x {height:F1}H - (0, 0) x ({width:F0}, {height:F0}) ={width * height:F0} 纵向 x",
          $"    media_bounds_urx={width:F1}",
          $"    media_bounds_ury={height:F1}",
          "    printable_bounds_llx=0.0",
          "    printable_bounds_lly=0.0",
          $"    printable_bounds_urx={width:F1}",
          $"    printable_bounds_ury={height:F1}",
          $"    printable_area={width * height:F1}",
          "    dimensional=TRUE",
          "}}}}}",
          "hidden{",
          " media{",
          "  abilities=\"500005500500505555000005550000000550000500000500000",
          "  caps_state=\"000000000000000000000000000000000000000000000000000",
          "  ui_owner=\"11111111111111111111110",
          "  size_max_x=5080.0",
          "  size_max_y=5080.0",
          " }",
          "}"
      };

          VldosWriteFile(pmpPath, pmpLines, true);
      }
      catch (Exception ex)
      {
          Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n创建PMP文件错误: {ex.Message}");
      }
  }

  /// <summary>
  /// 生成PC3文件(Unix格式)
  /// </summary>
  public static void CreatePc3File(string pc3Path, string pmpPath, string paperName, double width, double height)
  {
      try
      {
          // 先创建PMP文件
          CreatePmpFile(pmpPath, paperName, width, height);

          string acadVer = Application.Version.Major.ToString();
          string roamableRoot = Application.GetSystemVariable("ROAMABLEROOTPREFIX") as string;

          // 使用新的方法获取驱动程序路径和文件名
          string acadDrv = GetAcadDriverPath();
          string driverFileName = GetPdfDriverFileName();

          // PC3文件基础部分 - 使用Unix换行符
          var pc3Lines = new List<string>
      {
          "PIAFILEVERSION_2.0,PC3VER1",
          "meta{",
          $" user_defined_model_pathname=\"{pmpPath}",
          " user_defined_model_basename= \"",
          $" driver_pathname=\"{acadDrv}\\{driverFileName}",
          " driver_version= \"1.0-16.0.47.0 [v018-1]",
          " driver_tag_line= \"PDF Plot - by Autodesk",
          " toolkit_version=1",
          " driver_type=3",
          " canonical_family_name= \"Autodesk ePlot",
          " show_custom_first=FALSE",
          " truetype_as_text=TRUE",
          " canonical_model_name= \"pdf",
          " localized_family_name= \"Autodesk ePlot (PDF)",
          " localized_model_name= \"PDF",
          " file_only=TRUE",
          " model_abilities= \"000550055000",
          " udm_description= \"",
          " short_net_name= \"",
          " friendly_net_name= \"",
          " dm_driver_version=0",
          " default_system_cfg=FALSE",
          " platform= \"2,10,0",
          " locale= \"4B00409",
          " config_description= \"",
          " config_autospool=FALSE",
          "}",
          "media{",
          " selection_method=2",
          " type= \"",
          " dm_orientation=1",
          " actual_printable_bounds_llx=5.0",
          " actual_printable_bounds_lly=17.0",
          " actual_printable_bounds_urx=205.0",
          " actual_printable_bounds_ury=280.0",
          " number_of_copies=1",
          " size{",
          "  name= \"ISO_A4_(210.00_x_297.00_MM)",
          "  group=4",
          "  landscape_mode=FALSE",
          "  longplot_reduction=1.0",
          "  media_description{",
          "   printable_bounds_llx=5.0",
          "   printable_bounds_lly=17.0",
          "   printable_bounds_urx=205.0",
          "   printable_bounds_ury=280.0",
          "   printable_area=52600.0",
          "   dimensional=TRUE",
          "   media_bounds{",
          "    urx=210.0",
          "    ury=297.0",
          "   }",
          "  }",
          " }",
          "}",
          "io{",
          " type=2",
          " pathname= \"",
          " allsysvalid=FALSE",
          " plot_to_file=TRUE",
          "}",
          "res_color_mem{",
          " name= \"RGB",
          " num_colors=16777216",
          " color_depth=24",
          " num_undithered_colors=16777216",
          " color_system=1",
          " dm_color=1",
          " lines_overwrite=TRUE",
          " resolution{",
          "  name= \"Default",
          "  phys_resolution_x=400.0",
          "  phys_resolution_y=400.0",
          "  addr_resolution_x=1.0",
          "  addr_resolution_y=1.0",
          "  effective_resolution_x=400.0",
          "  effective_resolution_y=400.0",
          " }",
          "}"
      };

          // 根据AutoCAD版本添加对应的自定义配置
          if (int.Parse(acadVer) >= 18) // AutoCAD 2010及以上版本
          {
              pc3Lines.AddRange(new[]
              {
              "custom{",
              " 0{",
              "  name= \"Custom_Raster_Resolution",
              "  value=FALSE",
              " }",
              " 1{",
              "  name= \"Custom_DWF_Resolution",
              "  value=FALSE",
              " }",
              " 2{",
              "  name= \"Custom_Monochrome_Resolution",
              "  value=FALSE",
              " }",
              " 3{",
              "  name= \"Custom_Gradient_Resolution",
              "  value=FALSE",
              " }",
              " 4{",
              "  name= \"Gradient_Limit",
              "  value=400",
              " }",
              " 5{",
              "  name= \"Monochrome_Raster_Limit",
              "  value=400",
              " }",
              " 6{",
              "  name= \"Raster_Limit",
              "  value=400",
              " }",
              " 7{",
              "  name= \"All_As_Geometry",
              "  value=TRUE",
              " }",
              " 8{",
              "  name= \"Capture",
              "  value=1",
              " }",
              " 9{",
              "  name= \"Hardcopy_Resolution",
              "  value=400",
              " }",
              " 10{",
              "  name= \"Font_Capture",
              "  value=FALSE",
              " }",
              " 11{",
              "  name= \"Include_Layer",
              "  value=TRUE",
              " }",
              " 12{",
              "  name= \"Resolution",
              "  value=14",
              " }",
              "}"
          });
          }
          else // AutoCAD 2008及以下版本
          {
              pc3Lines.AddRange(new[]
              {
              "custom{",
              " 0{",
              "  name= \"Custom_Raster_Resolution",
              "  value=FALSE",
              " }",
              " 1{",
              "  name= \"Custom_DWF_Resolution",
              "  value=FALSE",
              " }",
              " 2{",
              "  name= \"Custom_Monochrome_Resolution",
              "  value=FALSE",
              " }",
              " 3{",
              "  name= \"Custom_Gradient_Resolution",
              "  value=FALSE",
              " }",
              " 4{",
              "  name= \"Gradient_Limit",
              "  value=400",
              " }",
              " 5{",
              "  name= \"Monochrome_Raster_Limit",
              "  value=400",
              " }",
              " 6{",
              "  name= \"Raster_Limit",
              "  value=400",
              " }",
              " 7{",
              "  name= \"All_As_Geometry",
              "  value=TRUE",
              " }",
              " 8{",
              "  name= \"Include_Preview",
              "  value=FALSE",
              " }",
              " 9{",
              "  name= \"Capture",
              "  value=1",
              " }",
              " 10{",
              "  name= \"Thumbnail_And_Preview",
              "  value=FALSE",
              " }",
              " 11{",
              "  name= \"SuperDWF_Opcodes",
              "  value=TRUE",
              " }",
              " 12{",
              "  name= \"Optimized_For_Plotting",
              "  value=TRUE",
              " }",
              " 13{",
              "  name= \"Hardcopy_Resolution",
              "  value=400",
              " }",
              " 14{",
              "  name= \"Font_Capture",
              "  value=TRUE",
              " }",
              " 15{",
              "  name= \"Color_Depth_Control",
              "  value=TRUE",
              " }",
              " 16{",
              "  name= \"File_Format",
              "  value=50",
              " }",
              " 17{",
              "  name= \"Show_Paper_Boundaries",
              "  value=FALSE",
              " }",
              " 18{",
              "  name= \"Convert_DWG_to_DWF",
              "  value=FALSE",
              " }",
              " 19{",
              "  name= \"Include_Measurement",
              "  value=TRUE",
              " }",
              " 20{",
              "  name= \"Include_Scale",
              "  value=TRUE",
              " }",
              " 21{",
              "  name= \"Include_Layer",
              "  value=TRUE",
              " }",
              " 22{",
              "  name= \"Background_Color",
              "  value=16777215",
              " }",
              " 23{",
              "  name= \"Format",
              "  value=2",
              " }",
              " 24{",
              "  name= \"Resolution",
              "  value=14",
              " }",
              "}"
          });
          }

          // 写入PC3文件(Unix格式)
          VldosWriteFile(pc3Path, pc3Lines, true);

          Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\nPC3文件已创建: {pc3Path}");
      }
      catch (Exception ex)
      {
          Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n创建PC3文件错误: {ex.Message}");
      }
  }

  /// <summary>
  /// 主命令:创建自定义PDF打印配置
  /// </summary>
  [CommandMethod("TTDD2")]
  public static void CreateCustomPlotConfig2()
  {
      try
      {
          Document doc = Application.DocumentManager.MdiActiveDocument;
          Editor ed = doc.Editor;

          // 获取用户输入的宽度和高度
          var widthOpt = ed.GetDouble("\n输入图纸宽度: ");
          if (widthOpt.Status != Autodesk.AutoCAD.EditorInput.PromptStatus.OK) return;

          var heightOpt = ed.GetDouble("\n输入图纸高度: ");
          if (heightOpt.Status != Autodesk.AutoCAD.EditorInput.PromptStatus.OK) return;

          double width = widthOpt.Value;
          double height = heightOpt.Value;

          ed.WriteMessage($"\n图纸尺寸: {width:F2} x {height:F2}");

          // 获取配置文件路径
          string roamableRoot = Application.GetSystemVariable("ROAMABLEROOTPREFIX") as string;
          string pc3Path = Path.Combine(roamableRoot, "Plotters", "zpdf.pc3");
          string pmpPath = Path.Combine(roamableRoot, "Plotters", "PMP Files", "zpdf.pmp");

          // 确保目录存在
          Directory.CreateDirectory(Path.GetDirectoryName(pc3Path));
          Directory.CreateDirectory(Path.GetDirectoryName(pmpPath));

          // 创建PC3和PMP文件
          CreatePc3File(pc3Path, pmpPath, "mysize123", width, height);

          // 设置为当前布局的打印机
          using (Database db = doc.Database)
          {
              //using (Transaction tr = db.TransactionManager.StartTransaction())
              //{
              //    LayoutManager layoutMgr = LayoutManager.Current;
              //    Layout layout = tr.GetObject(layoutMgr.GetLayoutId(layoutMgr.CurrentLayout), OpenMode.ForWrite) as Layout;

              //    if (layout != null)
              //    {
              //        layout.ConfigName = "zpdf.pc3";
              //        tr.Commit();
              //    }
              //}
          }

          ed.WriteMessage("\n自定义PDF打印配置已创建并设为当前布局的打印机");
      }
      catch (Exception ex)
      {
          Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n错误: {ex.Message}");
      }
  }




网友答: 谢谢大佬分享源码

网友答: 谢谢分享!感谢大佬!

网友答: 这个可以继续细化  在同一个文件里添加纸张、删除纸张、增加打印边界的功能吗
  • 上一篇:轮盘菜单研究
  • 下一篇:没有了