textinfo.c

  name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-5572165936844014&dt=1194442938015&lmt=1194190197&format=336x280_as&output=html&correlator=1194442937843&url=file%3A%2F%2F%2FC%3A%2FDocuments%2520and%2520Settings%2Flhh1%2F%E6%A1%8C%E9%9D%A2%2FCLanguage.htm&color_bg=FFFFFF&color_text=000000&color_link=000000&color_url=FFFFFF&color_border=FFFFFF&ad_type=text&ga_vid=583001034.1194442938&ga_sid=1194442938&ga_hid=1942779085&flash=9&u_h=768&u_w=1024&u_ah=740&u_aw=1024&u_cd=32&u_tz=480&u_java=true" frameborder="0" width="336" scrolling="no" height="280" allowtransparency="allowtransparency"> #include <conio.h>

void main(void)
 {
   struct text_info text;

   gettextinfo(&text);

   cprintf("Screen coordinates %d,%d to %d,%d/r/n",
     text.wintop, text.winleft, text.winbottom, text.winright);

   cprintf("Text attribute %d Normal attribute %d/r/n",
     text.attribute, text.normattr);

   cprintf("Screen height %d width %d/r/n", text.screenheight,
     text.screenwidth);

   cprintf("Cursor position was row %d column %d/r/n",
     text.cury, text.curx);
 }

 

using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.Runtime; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; // 为避免命名冲突,创建别名 using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application; using SystemException = System.Exception; [assembly: CommandClass(typeof(CadLibraryPlugin.LibraryCommands))] namespace CadLibraryPlugin { public class LibraryCommands { [CommandMethod("CFS")] public void ShowLibrary() { try { AcadApp.ShowModelessDialog(AcadApp.MainWindow.Handle, new LibraryForm(), false); } catch (SystemException ex) { MessageBox.Show($"打开词库时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } public class TextInfo { public string Name { get; set; } public string Path { get; set; } public bool IsSystemText { get; set; } public string OriginalFileName { get; set; } public string Content { get; set; } public int EntryNumber { get; set; } } public partial class LibraryForm : Form { private string _systemTextsPath; private string _userTextsPath; private string _selectedTextName = string.Empty; private bool _isSystemText = false; private string _selectedTextPath = string.Empty; private string _originalPreviewContent = string.Empty; private Document _currentDoc; public LibraryForm() { InitializeComponent(); InitializeForm(); } private void InitializeForm() { try { InitializePaths(); _currentDoc = AcadApp.DocumentManager.MdiActiveDocument; LoadAllTexts(); btnDelete.Enabled = false; } catch (SystemException ex) { MessageBox.Show($"初始化词库窗体时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void InitializePaths() { try { string pluginPath = System.Reflection.Assembly.GetExecutingAssembly().Location; string pluginDirectory = Path.GetDirectoryName(pluginPath); _systemTextsPath = Path.Combine(pluginDirectory, "ScaffoldBlocks"); if (!Directory.Exists(_systemTextsPath)) { Directory.CreateDirectory(_systemTextsPath); } _userTextsPath = GetBestUserPath(); Directory.CreateDirectory(_userTextsPath); System.Diagnostics.Debug.WriteLine($"系统词库路径: {_systemTextsPath}"); System.Diagnostics.Debug.WriteLine($"用户词库路径: {_userTextsPath}"); } catch (SystemException ex) { MessageBox.Show($"初始化路径时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private string GetBestUserPath() { List<string> potentialPaths = new List<string> { Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "CADTextLibrary"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CADTextLibrary"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "CADTextLibrary") }; foreach (var path in potentialPaths) { try { string testFile = Path.Combine(path, "test_write_permission.tmp"); Directory.CreateDirectory(path); File.WriteAllText(testFile, "test"); File.Delete(testFile); if (!ContainsChineseCharacters(path)) { return path; } } catch { continue; } } return potentialPaths[0]; } private bool ContainsChineseCharacters(string text) { return text.Any(c => c >= 0x4e00 && c <= 0x9fff); } private void LoadAllTexts() { try { treeViewDirectory.Nodes.Clear(); // 系统词库节点 TreeNode systemNode = new TreeNode("系统词库"); treeViewDirectory.Nodes.Add(systemNode); if (Directory.Exists(_systemTextsPath)) { var systemFiles = Directory.GetFiles(_systemTextsPath, "*.txt"); List<TreeNode> allSystemEntries = new List<TreeNode>(); foreach (string file in systemFiles) { try { var entries = ParseTextFileEntries(file); foreach (var entry in entries) { allSystemEntries.Add(entry); } } catch (SystemException ex) { System.Diagnostics.Debug.WriteLine($"加载系统文本失败 {file}: {ex.Message}"); } } // 为条目编号 for (int i = 0; i < allSystemEntries.Count; i++) { int entryNumber = i + 1; TreeNode entryNode = allSystemEntries[i]; if (entryNode.Tag is TextInfo textInfo) { textInfo.EntryNumber = entryNumber; entryNode.Text = $"{entryNumber}.{textInfo.Name}"; } systemNode.Nodes.Add(entryNode); } if (allSystemEntries.Count == 0) { systemNode.Nodes.Add($"暂无系统文本 (路径: {_systemTextsPath})"); } } else { systemNode.Nodes.Add($"系统词库目录不存在 (路径: {_systemTextsPath})"); } // 用户词库节点 TreeNode userNode = new TreeNode("用户词库"); treeViewDirectory.Nodes.Add(userNode); if (Directory.Exists(_userTextsPath)) { string[] userFiles = Directory.GetFiles(_userTextsPath, "*.txt"); foreach (string file in userFiles) { try { string textName = Path.GetFileNameWithoutExtension(file); string content = File.ReadAllText(file); string displayName = ExtractTitleFromContent(content) ?? textName; TreeNode node = new TreeNode(displayName); node.Tag = new TextInfo { Name = displayName, Path = file, IsSystemText = false, OriginalFileName = textName, Content = content }; userNode.Nodes.Add(node); } catch (SystemException ex) { System.Diagnostics.Debug.WriteLine($"加载用户文本失败 {file}: {ex.Message}"); } } if (userFiles.Length == 0) { userNode.Nodes.Add("暂无用户文本"); } } else { userNode.Nodes.Add("用户词库目录不存在"); } treeViewDirectory.ExpandAll(); } catch (SystemException ex) { MessageBox.Show($"加载文本列表时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private List<TreeNode> ParseTextFileEntries(string filePath) { List<TreeNode> entries = new List<TreeNode>(); string fileName = Path.GetFileNameWithoutExtension(filePath); try { string[] lines = File.ReadAllLines(filePath); List<string> currentEntryLines = new List<string>(); string currentTitle = null; foreach (string line in lines) { string trimmedLine = line.Trim(); if (trimmedLine.StartsWith("《") && trimmedLine.EndsWith("》")) { if (currentTitle != null && currentEntryLines.Count > 0) { entries.Add(CreateEntryNode(currentTitle, currentEntryLines, filePath, fileName)); } currentTitle = trimmedLine.Substring(1, trimmedLine.Length - 2); currentEntryLines = new List<string>(); } else if (currentTitle != null) { currentEntryLines.Add(line); } } if (currentTitle != null && currentEntryLines.Count > 0) { entries.Add(CreateEntryNode(currentTitle, currentEntryLines, filePath, fileName)); } if (entries.Count == 0) { entries.Add(CreateEntryNode(fileName, lines.ToList(), filePath, fileName)); } } catch (SystemException ex) { System.Diagnostics.Debug.WriteLine($"解析文本文件失败 {filePath}: {ex.Message}"); entries.Add(new TreeNode($"错误: 无法解析 {fileName}") { Tag = null }); } return entries; } private TreeNode CreateEntryNode(string title, List<string> contentLines, string filePath, string fileName) { string content = string.Join(Environment.NewLine, contentLines).Trim(); TreeNode node = new TreeNode(title); node.Tag = new TextInfo { Name = title, Path = filePath, IsSystemText = true, OriginalFileName = fileName, Content = content }; return node; } private string ExtractTitleFromContent(string content) { if (string.IsNullOrEmpty(content)) return null; string[] lines = content.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { string trimmedLine = line.Trim(); if (trimmedLine.StartsWith("《") && trimmedLine.EndsWith("》")) { return trimmedLine.Substring(1, trimmedLine.Length - 2); } } return null; } private void btnAdd_Click(object sender, EventArgs e) { Document doc = null; try { doc = AcadApp.DocumentManager.MdiActiveDocument; if (doc == null) { MessageBox.Show("没有打开的AutoCAD文档!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Editor ed = doc.Editor; PromptSelectionOptions selOpts = new PromptSelectionOptions(); selOpts.MessageForAdding = "选择要入库的文本对象 (支持TEXT和MTEXT): "; selOpts.AllowDuplicates = false; // 选择过滤器 TypedValue[] filterList = new TypedValue[] { new TypedValue((int)DxfCode.Operator, "<or"), new TypedValue((int)DxfCode.Start, "TEXT"), new TypedValue((int)DxfCode.Start, "MTEXT"), new TypedValue((int)DxfCode.Operator, "or>") }; SelectionFilter filter = new SelectionFilter(filterList); ed.WriteMessage("\n请选择文本对象,或按ESC取消...\n"); PromptSelectionResult selRes = ed.GetSelection(selOpts, filter); if (selRes.Status == PromptStatus.Cancel) { ed.WriteMessage("操作已取消。\n"); return; } if (selRes.Status != PromptStatus.OK) { ed.WriteMessage("未选择任何对象。\n"); return; } if (selRes.Value.Count == 0) { MessageBox.Show("没有选择任何文本对象!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } ed.WriteMessage($"已选择 {selRes.Value.Count} 个对象,正在提取文本...\n"); string textContent = ExtractTextFromSelection(doc, selRes.Value); if (string.IsNullOrEmpty(textContent)) { MessageBox.Show("选中的对象中没有可提取的文本!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } using (InputTextNameForm inputForm = new InputTextNameForm()) { if (inputForm.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(inputForm.TextName)) { string textName = inputForm.TextName.Trim(); if (string.IsNullOrEmpty(textName)) { MessageBox.Show("文本名称不能为空!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } textName = CleanTextName(textName); string filePath = Path.Combine(_userTextsPath, $"{textName}.txt"); if (File.Exists(filePath)) { if (MessageBox.Show($"文本 '{textName}' 已存在,是否覆盖?", "确认覆盖", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } } File.WriteAllText(filePath, textContent); LoadAllTexts(); ed.WriteMessage($"\n文本 '{textName}' 已成功入库!"); MessageBox.Show($"文本 '{textName}' 已成功入库!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (SystemException ex) { MessageBox.Show($"保存文本时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private string ExtractTextFromSelection(Document doc, SelectionSet selectionSet) { List<string> textContents = new List<string>(); int textCount = 0; int mtextCount = 0; int otherCount = 0; using (Transaction tr = doc.Database.TransactionManager.StartTransaction()) { foreach (ObjectId id in selectionSet.GetObjectIds()) { DBObject obj = tr.GetObject(id, OpenMode.ForRead); if (obj is DBText dbText) { textContents.Add(dbText.TextString); textCount++; } else if (obj is MText mText) { textContents.Add(mText.Contents); mtextCount++; } else { otherCount++; } } tr.Commit(); } System.Diagnostics.Debug.WriteLine($"提取文本统计 - TEXT: {textCount}, MTEXT: {mtextCount}, 其他: {otherCount}"); return string.Join(Environment.NewLine, textContents); } private string CleanTextName(string name) { char[] invalidChars = Path.GetInvalidFileNameChars(); return string.Join("_", name.Split(invalidChars, StringSplitOptions.RemoveEmptyEntries)); } private void btnDelete_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(_selectedTextName) || _isSystemText) { MessageBox.Show("请选择一个用户文本进行删除!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (MessageBox.Show($"确定要删除文本 '{_selectedTextName}' 吗?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { if (File.Exists(_selectedTextPath)) { File.Delete(_selectedTextPath); LoadAllTexts(); ClearPreview(); MessageBox.Show("文本已成功删除!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("文本文件不存在!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch (SystemException ex) { MessageBox.Show($"删除文本时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnInsert_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(_selectedTextName) || string.IsNullOrEmpty(_selectedTextPath)) { MessageBox.Show("请先选择一个文本!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } Document doc = AcadApp.DocumentManager.MdiActiveDocument; if (doc == null) { MessageBox.Show("没有打开的AutoCAD文档!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } using (DocumentLock docLock = doc.LockDocument()) { Editor ed = doc.Editor; PromptPointOptions ptOpts = new PromptPointOptions("\n请指定插入点: "); PromptPointResult ptRes = ed.GetPoint(ptOpts); if (ptRes.Status != PromptStatus.OK) return; Point3d insertPoint = ptRes.Value; string textToInsert = textBoxPreview.Text; if (InsertText(doc, insertPoint, textToInsert)) { ed.WriteMessage($"\n文本 '{_selectedTextName}' 已成功插入!"); textBoxPreview.Text = _originalPreviewContent; } else { MessageBox.Show($"文本 '{_selectedTextName}' 插入失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch (SystemException ex) { MessageBox.Show($"插入文本时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool InsertText(Document doc, Point3d insertPoint, string textContent) { try { using (Transaction tr = doc.Database.TransactionManager.StartTransaction()) { BlockTable bt = tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; MText mText = new MText(); mText.Contents = textContent; mText.Location = insertPoint; mText.Width = 500; mText.Height = 2.5; btr.AppendEntity(mText); tr.AddNewlyCreatedDBObject(mText, true); tr.Commit(); return true; } } catch (SystemException ex) { System.Diagnostics.Debug.WriteLine($"插入文本失败: {ex.Message}"); return false; } } private void treeViewDirectory_AfterSelect(object sender, TreeViewEventArgs e) { try { if (e.Node.Tag is TextInfo textInfo) { _selectedTextName = textInfo.Name; _selectedTextPath = textInfo.Path; _isSystemText = textInfo.IsSystemText; // 显示文本内容并确保滚动到顶部 textBoxPreview.Text = textInfo.Content; textBoxPreview.SelectionStart = 0; textBoxPreview.SelectionLength = 0; textBoxPreview.ScrollToCaret(); // 滚动到光标位置(顶部) _originalPreviewContent = textInfo.Content; labelPreviewInfo.Text = $"预览: {textInfo.Name}"; btnDelete.Enabled = !textInfo.IsSystemText; } else { ClearPreview(); btnDelete.Enabled = false; _selectedTextName = string.Empty; _selectedTextPath = string.Empty; } } catch (SystemException ex) { MessageBox.Show($"选择文本时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ClearPreview() { textBoxPreview.Text = string.Empty; _originalPreviewContent = string.Empty; labelPreviewInfo.Text = "预览: 无"; } private void btnRefresh_Click(object sender, EventArgs e) { try { LoadAllTexts(); ClearPreview(); } catch (SystemException ex) { MessageBox.Show($"刷新词库时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } public partial class InputTextNameForm : Form { public string TextName { get; private set; } public InputTextNameForm() { InitializeComponent(); } private void btnSave_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(textBoxTextName.Text)) { MessageBox.Show("请输入文本名称!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } TextName = textBoxTextName.Text.Trim(); DialogResult = DialogResult.OK; Close(); } private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void InputTextNameForm_Load(object sender, EventArgs e) { textBoxTextName.Focus(); } private void textBoxTextName_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Enter) btnSave_Click(sender, e); else if (e.KeyChar == (char)Keys.Escape) btnCancel_Click(sender, e); } } } namespace CadLibraryPlugin { partial class LibraryForm { private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { this.panelButtons = new System.Windows.Forms.Panel(); this.btnRefresh = new System.Windows.Forms.Button(); this.btnInsert = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.btnAdd = new System.Windows.Forms.Button(); this.splitContainerMain = new System.Windows.Forms.SplitContainer(); this.treeViewDirectory = new System.Windows.Forms.TreeView(); this.panelPreview = new System.Windows.Forms.Panel(); this.labelPreviewInfo = new System.Windows.Forms.Label(); this.textBoxPreview = new System.Windows.Forms.TextBox(); this.panelButtons.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainerMain)).BeginInit(); this.splitContainerMain.Panel1.SuspendLayout(); this.splitContainerMain.Panel2.SuspendLayout(); this.splitContainerMain.SuspendLayout(); this.panelPreview.SuspendLayout(); this.SuspendLayout(); // // panelButtons // this.panelButtons.Controls.Add(this.btnRefresh); this.panelButtons.Controls.Add(this.btnInsert); this.panelButtons.Controls.Add(this.btnDelete); this.panelButtons.Controls.Add(this.btnAdd); this.panelButtons.Dock = System.Windows.Forms.DockStyle.Top; this.panelButtons.Location = new System.Drawing.Point(0, 0); this.panelButtons.Margin = new System.Windows.Forms.Padding(0); this.panelButtons.Name = "panelButtons"; this.panelButtons.Size = new System.Drawing.Size(800, 45); this.panelButtons.TabIndex = 0; // // btnRefresh // this.btnRefresh.Location = new System.Drawing.Point(340, 8); this.btnRefresh.Name = "btnRefresh"; this.btnRefresh.Size = new System.Drawing.Size(75, 30); this.btnRefresh.TabIndex = 3; this.btnRefresh.Text = "刷新"; this.btnRefresh.UseVisualStyleBackColor = true; this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click); // // btnInsert // this.btnInsert.Location = new System.Drawing.Point(250, 8); this.btnInsert.Name = "btnInsert"; this.btnInsert.Size = new System.Drawing.Size(75, 30); this.btnInsert.TabIndex = 2; this.btnInsert.Text = "选用"; this.btnInsert.UseVisualStyleBackColor = true; this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click); // // btnDelete // this.btnDelete.Location = new System.Drawing.Point(160, 8); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(75, 30); this.btnDelete.TabIndex = 1; this.btnDelete.Text = "删除"; this.btnDelete.UseVisualStyleBackColor = true; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // btnAdd // this.btnAdd.Location = new System.Drawing.Point(10, 8); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(135, 30); this.btnAdd.TabIndex = 0; this.btnAdd.Text = "拾取文本入库"; this.btnAdd.UseVisualStyleBackColor = true; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // splitContainerMain // this.splitContainerMain.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainerMain.Location = new System.Drawing.Point(0, 45); this.splitContainerMain.Name = "splitContainerMain"; // 调整分割容器比例,给预览窗口更多空间 this.splitContainerMain.SplitterDistance = 220; // // splitContainerMain.Panel1 // this.splitContainerMain.Panel1.Controls.Add(this.treeViewDirectory); // // splitContainerMain.Panel2 // this.splitContainerMain.Panel2.Controls.Add(this.panelPreview); this.splitContainerMain.Size = new System.Drawing.Size(800, 405); // 减小总高度 this.splitContainerMain.SplitterWidth = 6; this.splitContainerMain.TabIndex = 1; // // treeViewDirectory // this.treeViewDirectory.Dock = System.Windows.Forms.DockStyle.Fill; this.treeViewDirectory.Location = new System.Drawing.Point(0, 0); this.treeViewDirectory.Name = "treeViewDirectory"; this.treeViewDirectory.Size = new System.Drawing.Size(220, 405); this.treeViewDirectory.TabIndex = 0; this.treeViewDirectory.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeViewDirectory_AfterSelect); // // panelPreview // this.panelPreview.Controls.Add(this.labelPreviewInfo); this.panelPreview.Controls.Add(this.textBoxPreview); this.panelPreview.Dock = System.Windows.Forms.DockStyle.Fill; this.panelPreview.Location = new System.Drawing.Point(0, 0); this.panelPreview.Margin = new System.Windows.Forms.Padding(0); this.panelPreview.Name = "panelPreview"; this.panelPreview.Padding = new System.Windows.Forms.Padding(5); this.panelPreview.Size = new System.Drawing.Size(574, 405); this.panelPreview.TabIndex = 0; // // labelPreviewInfo // this.labelPreviewInfo.Dock = System.Windows.Forms.DockStyle.Top; this.labelPreviewInfo.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.labelPreviewInfo.Location = new System.Drawing.Point(5, 5); this.labelPreviewInfo.Margin = new System.Windows.Forms.Padding(0, 0, 0, 5); this.labelPreviewInfo.Name = "labelPreviewInfo"; this.labelPreviewInfo.Size = new System.Drawing.Size(564, 25); // 增加标签高度 this.labelPreviewInfo.TabIndex = 1; this.labelPreviewInfo.Text = "预览: 无"; this.labelPreviewInfo.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // textBoxPreview // this.textBoxPreview.Dock = System.Windows.Forms.DockStyle.Fill; this.textBoxPreview.Location = new System.Drawing.Point(5, 35); // 增加顶部距离,避免文本被遮挡 this.textBoxPreview.Margin = new System.Windows.Forms.Padding(10, 5, 10, 10); // 增加边距 this.textBoxPreview.Multiline = true; this.textBoxPreview.Name = "textBoxPreview"; this.textBoxPreview.Padding = new System.Windows.Forms.Padding(8); this.textBoxPreview.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textBoxPreview.Size = new System.Drawing.Size(564, 365); // 调整高度 this.textBoxPreview.TabIndex = 0; this.textBoxPreview.WordWrap = true; // // LibraryForm // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.ClientSize = new System.Drawing.Size(800, 450); // 减小窗体高度 this.Controls.Add(this.splitContainerMain); this.Controls.Add(this.panelButtons); this.MinimumSize = new System.Drawing.Size(800, 450); this.Name = "LibraryForm"; this.Text = "通用词库"; this.panelButtons.ResumeLayout(false); this.splitContainerMain.Panel1.ResumeLayout(false); this.splitContainerMain.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainerMain)).EndInit(); this.splitContainerMain.ResumeLayout(false); this.panelPreview.ResumeLayout(false); this.panelPreview.PerformLayout(); this.ResumeLayout(false); } private System.Windows.Forms.Panel panelButtons; internal System.Windows.Forms.Button btnAdd; internal System.Windows.Forms.Button btnDelete; internal System.Windows.Forms.Button btnInsert; internal System.Windows.Forms.Button btnRefresh; private System.Windows.Forms.SplitContainer splitContainerMain; internal System.Windows.Forms.TreeView treeViewDirectory; private System.Windows.Forms.Panel panelPreview; internal System.Windows.Forms.TextBox textBoxPreview; internal System.Windows.Forms.Label labelPreviewInfo; } partial class InputTextNameForm { private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.textBoxTextName = new System.Windows.Forms.TextBox(); this.btnSave = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(20, 20); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(35, 12); this.label1.TabIndex = 0; this.label1.Text = "词名:"; // // textBoxTextName // this.textBoxTextName.Location = new System.Drawing.Point(60, 17); this.textBoxTextName.Name = "textBoxTextName"; this.textBoxTextName.Size = new System.Drawing.Size(200, 21); this.textBoxTextName.TabIndex = 1; this.textBoxTextName.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBoxTextName_KeyPress); // // btnSave // this.btnSave.Location = new System.Drawing.Point(60, 60); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(75, 23); this.btnSave.TabIndex = 2; this.btnSave.Text = "保存"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(185, 60); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 3; this.btnCancel.Text = "取消"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // InputTextNameForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(300, 100); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnSave); this.Controls.Add(this.textBoxTextName); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "InputTextNameForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "保存文本"; this.Load += new System.EventHandler(this.InputTextNameForm_Load); this.ResumeLayout(false); this.PerformLayout(); } private System.Windows.Forms.Label label1; internal System.Windows.Forms.TextBox textBoxTextName; internal System.Windows.Forms.Button btnSave; internal System.Windows.Forms.Button btnCancel; } } 预览窗口内的内容还是显示不完整;举例:选择目录中的“1.结构梁做法”,预览窗口中显示的内容: 40x90木方次龙骨@100 50x100x3单根方钢主龙骨 10#双槽钢拖梁支撑 预览窗口中必须显示的内容是: 200x500结构梁 15厚模板 40x90木方次龙骨@100 50x100x3单根方钢主龙骨 10#双槽钢拖梁支撑
最新发布
09-27
下面代码是我用itext+netDxf框架组合,将pdf转成dxf的代码,目前离最终效果还差三步:1.绕Z轴旋转90度,2.沿Y轴向上移动一个页面的宽度或者是高度的距离?(根据旋转后计算)3.绕着X轴旋转180度,因为现在看到的都是反的,请帮我调整下面的相关代码,主要是AddTransformedPoint方法: using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas.Parser; using iText.Kernel.Pdf.Canvas.Parser.Data; using iText.Kernel.Pdf.Canvas.Parser.Listener; using netDxf; using netDxf.Entities; using netDxf.Objects; using netDxf.Tables; using netDxf.Units; using System; using System.Collections.Generic; using System.IO; using System.Linq; using Path = System.IO.Path; using Point = iText.Kernel.Geom.Point; namespace SElevationTools { public class SPdfToDxfConverter { // 核心转换方法 public static void ConvertPdfToDxf(string pdfPath, string dxfPath) { using (var pdfDoc = new PdfDocument(new PdfReader(pdfPath))) { for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++) { var dxfDoc = new DxfDocument(); var page = pdfDoc.GetPage(i); var pageSize = page.GetPageSize(); // 创建DXF图层用于当前页面 Layer pageLayer = new Layer($"Page_{i}"); // 添加页面边界作为图框 AddPageFrame(dxfDoc, pageSize, pageLayer); // 处理页面内容 var processor = new PdfCanvasProcessor(new DxfElementListener(dxfDoc, pageSize, pageLayer)); processor.ProcessPageContent(page); dxfDoc.Save(i + "_" + dxfPath); } } } // 添加页面边界作为图框 private static void AddPageFrame(DxfDocument dxfDoc, Rectangle pageSize, Layer layer) { float width = (float)pageSize.GetWidth(); float height = (float)pageSize.GetHeight(); var frame = new Polyline2D(new[] { new Polyline2DVertex(0, 0), new Polyline2DVertex(width, 0), new Polyline2DVertex(width, height), new Polyline2DVertex(0, height), new Polyline2DVertex(0, 0) // 闭合 }) { Layer = layer, IsClosed = true }; dxfDoc.Entities.Add(frame); } // 自定义PDF元素监听器 private class DxfElementListener : IEventListener { private readonly DxfDocument _dxfDoc; private readonly Rectangle _pageSize; private readonly Layer _currentLayer; // 存储当前路径状态 private Matrix _currentCtm = new Matrix(); private List<Vector2> _currentPathPoints = new List<Vector2>(); public DxfElementListener(DxfDocument dxfDoc, Rectangle pageSize, Layer layer) { _dxfDoc = dxfDoc; _pageSize = pageSize; _currentLayer = layer; } public void EventOccurred(IEventData data, EventType type) { try { // 更新当前变换矩阵 if (data is AbstractRenderInfo renderInfo) { // 通过CanvasGraphicsState获取变换矩阵 _currentCtm = renderInfo.GetGraphicsState().GetCtm(); } // 1. 处理文本 if (data is TextRenderInfo textInfo) { ProcessText(textInfo); } // 2. 处理路径 else if (data is PathRenderInfo pathInfo) { ProcessPath(pathInfo); } // 3. 处理图像 else if (data is ImageRenderInfo imageInfo) { ProcessImage(imageInfo); } } catch (Exception ex) { Console.WriteLine($"Error processing element: {ex.Message}"); } } private void ProcessText(TextRenderInfo textInfo) { string text = textInfo.GetText(); if (string.IsNullOrWhiteSpace(text)) return; // 获取基线并转换坐标系 LineSegment baseline = textInfo.GetBaseline(); Vector startPoint = baseline.GetStartPoint(); // 转换为DXF坐标系 (原点在左下角) float x = (float)startPoint.Get(Vector.I1); float y = (float)(_pageSize.GetHeight() - startPoint.Get(Vector.I2)); // 创建DXF文本 var dxfText = new Text(text, new Vector2(x, y), textInfo.GetFontSize()) { Layer = _currentLayer, Rotation = (float)GetTextRotation(textInfo) }; _dxfDoc.Entities.Add(dxfText); } private double GetTextRotation(TextRenderInfo textInfo) { // 从文本矩阵中提取旋转角度 Matrix textMatrix = textInfo.GetTextMatrix(); double angleRad = Math.Atan2(textMatrix.Get(Matrix.I21), textMatrix.Get(Matrix.I11)); return angleRad * (180.0 / Math.PI); // 转为角度 } private void ProcessPath(PathRenderInfo pathInfo) { try { var path = pathInfo.GetPath(); _currentPathPoints.Clear(); foreach (var subpath in path.GetSubpaths()) { // 处理子路径起始点 - 使用Point对象而不是Vector Point startPoint = subpath.GetStartPoint(); if (startPoint != null) { // 直接使用Point的坐标 AddTransformedPoint(startPoint.GetX(), startPoint.GetY()); } // 处理路径段 foreach (var segment in subpath.GetSegments()) { if (segment is iText.Kernel.Geom.Line line) { // 获取线的终点(Point对象) Point endPoint = line.GetBasePoints()[1]; AddTransformedPoint(endPoint.GetX(), endPoint.GetY()); } else if (segment is iText.Kernel.Geom.BezierCurve bezier) { // 将贝塞尔曲线转换为多段线 var points = bezier.GetPiecewiseLinearApproximation(); for (int i = 1; i < points.Count; i++) // 跳过起点 { Point point = points[i]; AddTransformedPoint(point.GetX(), point.GetY()); } } // 可以添加其他曲线类型的处理 } // 创建DXF实体 if (_currentPathPoints.Count > 1) { CreatePathEntity(subpath.IsClosed()); } } } catch (Exception ex) { Console.WriteLine($"Error processing path: {ex.Message}"); } } // 使用double坐标 private void AddTransformedPoint(double x, double y) { // 手动应用变换矩阵 // newX = a*x + c*y + e // newY = b*x + d*y + f double newX = _currentCtm.Get(Matrix.I11) * x + _currentCtm.Get(Matrix.I21) * y + _currentCtm.Get(Matrix.I31); double newY = _currentCtm.Get(Matrix.I12) * x + _currentCtm.Get(Matrix.I22) * y + _currentCtm.Get(Matrix.I32); // 转换为DXF坐标系 (Y轴翻转) float dxfX = (float)newX; float dxfY = (float)(_pageSize.GetHeight() - newY); _currentPathPoints.Add(new Vector2(dxfX, dxfY)); } private void CreatePathEntity(bool isClosed) { // 创建多段线 var polyline = new Polyline2D( _currentPathPoints.Select(p => new Polyline2DVertex(p.X, p.Y)).ToList()); polyline.IsClosed = isClosed; polyline.Layer = _currentLayer; _dxfDoc.Entities.Add(polyline); _currentPathPoints.Clear(); } private void ProcessImage(ImageRenderInfo imageInfo) { try { var image = imageInfo.GetImage(); byte[] imageData = image.GetImageBytes(true); // 获取变换矩阵 Matrix ctm = imageInfo.GetImageCtm(); // 计算插入点 (转换坐标系) Vector startPoint = imageInfo.GetStartPoint(); // 手动应用变换矩阵 double x = startPoint.Get(Vector.I1); double y = startPoint.Get(Vector.I2); double newX = ctm.Get(Matrix.I11) * x + ctm.Get(Matrix.I21) * y + ctm.Get(Matrix.I31); double newY = ctm.Get(Matrix.I12) * x + ctm.Get(Matrix.I22) * y + ctm.Get(Matrix.I32); // 转换为DXF坐标系 float dxfX = (float)newX; float dxfY = (float)(_pageSize.GetHeight() - newY); // 创建唯一的图像名称 string imageName = $"IMG_{Guid.NewGuid().ToString("N")}"; // 创建ImageDefinition - 使用正确的构造函数 ImageDefinition imageDef; try { string tempFilePath = Path.Combine(Path.GetTempPath(), $"{imageName}.png"); File.WriteAllBytes(tempFilePath, imageData); // 使用带文件路径的构造函数 imageDef = new ImageDefinition(imageName, tempFilePath); } catch { // 回退方案:使用参数化构造函数 double dpi = 72; // 默认分辨率 // 获取正确的宽度和高度(整数) int width = (int)image.GetWidth(); int height = (int)image.GetHeight(); imageDef = new ImageDefinition( imageName, "", // 空文件路径 width, dpi, height, dpi, ImageResolutionUnits.Inches ); } _dxfDoc.ImageDefinitions.Add(imageDef); // 计算图像尺寸 float renderWidth = (float)(ctm.Get(Matrix.I11) * image.GetWidth()); float renderHeight = (float)(Math.Abs(ctm.Get(Matrix.I22)) * image.GetHeight()); // 创建图像实体 var dxfImage = new netDxf.Entities.Image( imageDef, new Vector2(dxfX, dxfY), renderWidth, renderHeight ) { Layer = _currentLayer }; // 计算旋转角度 double rotation = Math.Atan2(ctm.Get(Matrix.I12), ctm.Get(Matrix.I11)) * (180.0 / Math.PI); dxfImage.Rotation = (float)rotation; _dxfDoc.Entities.Add(dxfImage); } catch (Exception ex) { Console.WriteLine($"Error processing image: {ex.Message}"); } } // 实现GetSupportedEvents接口方法 ICollection<EventType> IEventListener.GetSupportedEvents() { return new HashSet<EventType> { EventType.RENDER_TEXT, EventType.RENDER_PATH, EventType.RENDER_IMAGE }; } } } }
08-06
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值