I have changed my mind & and used AcCoreConsole for batch plot. And worked for me. But works little bit slow.
using Autodesk.AutoCAD.Runtime;
using acApp = Autodesk.AutoCAD.ApplicationServices.Core.Application;
using Autodesk.AutoCAD.DatabaseServices;
using System.Windows.Forms;
using Autodesk.AutoCAD.EditorInput;
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
public class PlotMultipleDWGFilesToPDF : IExtensionApplication
{
#region
public void Initialize()
{
}
public void Terminate()
{
}
#endregion
[CommandMethod("OO")]
public void ProcessFilesSelection()
{
var docs = acApp.DocumentManager;
var acDoc = docs.MdiActiveDocument;
var ed = acDoc.Editor;
string ver = GetInstalledAutoCADVersion();
string cadPath = GetInstalledAutoCADPath();
string accoreconsole = Path.Combine(cadPath, "accoreconsole.exe");
AutoCADVersionChecker checker = new AutoCADVersionChecker();
if (!(ver != null) || !checker.IsVersionEqualOrGreater(ver, "R20"))
{
MessageBox.Show($"\nThe application only works with AutoCAD 2020 or later ");
return;
}
using (var db = acDoc.Database)
{
try
{
var openFileDialog = new Autodesk.AutoCAD.Windows.OpenFileDialog
("Select Drawing Files",
"",
"dwg",
"",
Autodesk.AutoCAD.Windows.OpenFileDialog.OpenFileDialogFlags.AllowMultiple
);
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var layerName = string.Empty;
while (string.IsNullOrEmpty(layerName))
{
var layResult = ed.GetString("\nSpecify the layer name: ");
if (layResult.Status != PromptStatus.OK)
{
MessageBox.Show($"\nOperation has been canceled by the User. ");
return;
}
layerName = layResult.StringResult.Trim();
if (string.IsNullOrEmpty(layerName))
{
ed.WriteMessage("\nThe layer name wasn't specified. Please enter a valid layer name. ");
}
}
using (Transaction tr = db.TransactionManager.StartTransaction())
{
var bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead, false) as BlockTable;
var btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead, false) as BlockTableRecord;
var lo = tr.GetObject(btr.LayoutId, OpenMode.ForRead, false) as Layout;
var plotter = lo.PlotConfigurationName;
var pageSize = lo.CanonicalMediaName.Replace("_", " ");
var plotStyle = lo.CurrentStyleSheet;
var dir = Path.GetDirectoryName(openFileDialog.GetFilenames()[0]);
var path = Path.Combine(dir + "\\PDF\\");
var repPath = path.Replace($"\\", $"\\\\");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
foreach (string file in openFileDialog.GetFilenames())
{
var scriptFile = CreateScriptFile(layerName, plotter, pageSize, plotStyle, repPath + Path.GetFileNameWithoutExtension(file));
ProcessScripts(accoreconsole, file, scriptFile);
}
tr.Commit();
}
}
else
{
MessageBox.Show("\nAt least one file must be selected to continue. ");
return;
}
}
catch (System.Exception ex)
{
ed.WriteMessage($"\nError: {ex.Message}\n{ex.StackTrace}");
}
}
}
public string GetInstalledAutoCADPath()
{
string path = "";
try
{
string autoCADVersionKey = GetInstalledAutoCADVersion();
if (!string.IsNullOrEmpty(autoCADVersionKey))
{
string keyPath = @"SOFTWARE\Autodesk\AutoCAD\" + autoCADVersionKey;
path = SearchSubKeysForKey(keyPath, "InstallDir");
if (string.IsNullOrEmpty(path))
{
path = SearchSubKeysForKey(keyPath, "AcadLocation");
}
}
}
catch (System.Exception ex)
{
path = "Error: " + ex.Message;
}
return path;
}
private string SearchSubKeysForKey(string keyPath, string valueName)
{
string result = "";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(keyPath))
{
if (key != null)
{
foreach (string subKeyName in key.GetSubKeyNames())
{
using (RegistryKey subKey = key.OpenSubKey(subKeyName))
{
if (subKey != null)
{
object value = subKey.GetValue(valueName);
if (value != null)
{
result = value.ToString();
break;
}
}
}
}
}
}
return result;
}
public string GetInstalledAutoCADVersion()
{
string version = "";
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Autodesk\AutoCAD"))
{
if (key != null)
{
string[] subKeyNames = key.GetSubKeyNames();
foreach (string subKeyName in subKeyNames)
{
if (subKeyName.StartsWith("R"))
{
version = subKeyName;
break;
}
}
}
}
}
catch (System.Exception ex)
{
version = "Error: " + ex.Message;
}
return version;
}
private static string CreateScriptFile(string layerName, string plotter, string size, string style, string path)
{
string tempFolder = Path.GetTempPath();
string scriptFolder = Path.Combine(tempFolder, "AutoCAD_Scripts");
string scriptFile = Path.Combine(scriptFolder, "AutoCAD_Script.scr");
if (!Directory.Exists(scriptFolder))
{
try
{
Directory.CreateDirectory(scriptFolder);
Console.WriteLine($"Script folder created at: {scriptFolder}");
}
catch (System.Exception ex)
{
Console.WriteLine($"Error creating script folder: {ex.Message}");
}
}
string[] scriptContent = {
$"(setvar \"cmdecho\" 0)",
$"(setvar \"filedia\" 0)",
$"(setq vertices nil)",
$"(setq layFilter (list (cons 8 \"{layerName}\")))",
$"(setq ss (ssget \"X\" layFilter))",
$"(if ss",
$"(progn",
$"(setq sslen (sslength ss))",
$"(setq i 0)",
$"(repeat sslen",
$"(setq ent (ssname ss i))",
$"(if (and (= (cdr (assoc 0 (entget ent))) \"LWPOLYLINE\") (= 4 (cdr (assoc 90 (entget ent)))))",
$"(progn",
$"(foreach d (entget ent)",
$"(if (= 10 (car d))",
$"(progn",
$"(setq vertex (cdr d))",
$"(setq vertices (append (list vertex) vertices)))))))",
$"(setq i (1+ i)))",
$"(setq minListX (vl-sort vertices '(lambda (a b) (< (car a) (car b)))))",
$"(setq minListY (vl-sort vertices '(lambda (a b) (< (cadr a) (cadr b)))))",
$"(setq minPoint (list (car (car minListX)) (cadr (car minListY))))",
$"(setq maxListX (vl-sort vertices '(lambda (a b) (> (car a) (car b)))))",
$"(setq maxListY (vl-sort vertices '(lambda (a b) (> (cadr a) (cadr b)))))",
$"(setq maxPoint (list (car (car maxListX)) (cadr (car maxListY))))))",
//$"(command \"Zoom\" \"w\" minPoint maxPoint)",
$"(command \"-Plot\" \"y\" \"\" \"{plotter}\" \"{size}\" \"\" \"\" \"\" \"w\" minPoint maxPoint \"f\" \"c\" \"y\" \"{style}\" \"\" \"\" \"{path}\" \"y\" \"y\")",
//$"(command \"qsave\")",
$"(setvar \"filedia\" 1)",
$"(setvar \"cmdecho\" 1)",
$"quit",
$"y"
};
try
{
File.WriteAllLines(scriptFile, scriptContent);
Console.WriteLine($"Script file created at: {scriptFile}");
}
catch (System.Exception ex)
{
Console.WriteLine($"Error creating script file: {ex.Message}");
}
return scriptFile;
}
private static void ProcessScripts(string AcCoreConsolePath, string fileName, string scriptFile)
{
ProcessStartInfo psi = new ProcessStartInfo(AcCoreConsolePath)
{
Arguments = $"/i \"{fileName}\" /s \"{scriptFile}\" /l en-us",
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true
};
using (Process process = new Process())
{
process.StartInfo = psi;
process.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data);
process.ErrorDataReceived += (sender, e) => Console.WriteLine(e.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
Console.WriteLine("Process finished.");
}
}
}
public class AutoCADVersionChecker
{
public bool IsVersionEqualOrGreater(string versionToCheck, string targetVersion)
{
// Extract version numbers after "R"
int versionNumberToCheck = ExtractVersionNumber(versionToCheck);
int targetVersionNumber = ExtractVersionNumber(targetVersion);
// Compare versions
return versionNumberToCheck >= targetVersionNumber;
}
private int ExtractVersionNumber(string version)
{
// Extract version number after "R" using regular expression
Match match = Regex.Match(version, @"R(\d+)");
if (match.Success && match.Groups.Count > 1)
{
return int.Parse(match.Groups[1].Value);
}
throw new ArgumentException("Invalid version format");
}
}