qq1254582201 发表于 2025-11-13 10:04:57

模仿【陨落】【lisp源码:生成任意尺寸的pdf纸张】写的C#修改PMP,PC3 自定义图幅

本帖最后由 qq1254582201 于 2025-11-13 11:05 编辑

/// <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); // 返回找到的第一个
      }

      // 最后回退到默认名称
      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 ",
      " 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 ",
      " 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>

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}");
    }
}这是原贴地址: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); // 返回找到的第一个
          }

          // 最后回退到默认名称
          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 ",
          " 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 ",
          " 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>

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}");
      }
}


lxl217114 发表于 2025-11-13 10:13:50

谢谢大佬分享源码

yaojing38 发表于 2025-11-13 10:48:27

谢谢分享!感谢大佬!

lxw320 发表于 2025-11-16 15:29:20

这个可以继续细化在同一个文件里添加纸张、删除纸张、增加打印边界的功能吗
页: [1]
查看完整版本: 模仿【陨落】【lisp源码:生成任意尺寸的pdf纸张】写的C#修改PMP,PC3 自定义图幅