Hi, I have 2 DWG source files, and I want to create a new DWG output file containing the 2 source files. The first source DWG should be on the first half of the output drawing and the second source drawing in the second half of the output drawing. I don’t want any background drawing in the output file. Is it possible to do this using Aspose.Cad library? I use .Net Framework.
Yes, it is possible to merge two DWG files into a new one using the Aspose.CAD library in .NET. You can achieve this by loading the first DWG file, inserting the second DWG file at a specified position, and then saving the result. Below is a sample code snippet that demonstrates how to do this:
using Aspose.CAD;
using Aspose.CAD.FileFormats.Cad;
using Aspose.CAD.FileFormats.Cad.Objects;
using Aspose.CAD.ImageOptions;
public class DwgMerger
{
public static void MergeDwgFiles(string firstDwgPath, string secondDwgPath, string outputDwgPath)
{
// Load the first DWG file
using (CadImage cadImage = (CadImage)Image.Load(firstDwgPath))
{
// Define the insertion point for the second DWG file
Cad3DPoint insertionPoint = new Cad3DPoint(0, 0); // Adjust as needed
// Add the second DWG file
AddDwg(cadImage, secondDwgPath, insertionPoint);
// Save the merged DWG file
cadImage.Save(outputDwgPath);
}
}
private static void AddDwg(CadImage cadImage, string fileName, Cad3DPoint insertionPoint)
{
CadInsertObject newInsert = new CadInsertObject
{
Name = fileName,
LayerName = "0",
InsertionPoint = insertionPoint
};
CadBlockDictionary allBlocks = cadImage.BlockEntities;
CadBlockEntity newBlock = new CadBlockEntity
{
XRefPathName = fileName
};
allBlocks.Add(newInsert.Name, newBlock);
cadImage.BlockEntities = allBlocks;
List<CadEntity> entities = new List<CadEntity>(cadImage.Entities);
entities.Add(newInsert);
cadImage.Entities = entities.ToArray();
}
}
// Usage
string firstDwg = "path/to/first.dwg";
string secondDwg = "path/to/second.dwg";
string outputDwg = "path/to/output.dwg";
DwgMerger.MergeDwgFiles(firstDwg, secondDwg, outputDwg);
In this example, the MergeDwgFiles
method loads the first DWG file, inserts the second DWG file at the specified insertion point, and saves the merged result to a new DWG file. You can adjust the insertionPoint
to position the second drawing as needed.
Make sure to include the necessary Aspose.CAD library references in your project to use the above code.
If you have any further questions or need additional assistance, feel free to ask!
Hi, thanks for the quick answer. I tried the code above but i get a “NullReferenceException: Object reference not set to an instance of an object” at the line “cadImage.Save(outputDwgPath);” inside MergeDwgFiles function.
@daniel.mocanu.vard,
Hello,
it appears that we need to fix the issue in our side, we have created CADNET-10016 to do this. I will also provide correct example when the fix will be delivered in release. We are sorry for the inconvenience.