PDF underlay’s are represented by the PdfDefinition and PdfReference classes in the AutoCAD .NET API. An Underlay (in this case PDF) Reference must reference compatible an underlay definition. The Underlay reference is responsible for the placement of the content within the drawing while Underlay Definition handles the linkage to the underlay content.
Note: The path for the PDF is hard coded and needs to be edited to reflect the path on your system.
[CommandMethod("pdfInsert")]
static public void DoPdfInsert()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
using (Transaction t =
doc.TransactionManager.StartTransaction())
{
DBDictionary nod =
(DBDictionary)t.GetObject(db.NamedObjectsDictionaryId,
OpenMode.ForWrite);
string defDictKey =
UnderlayDefinition.GetDictionaryKey(typeof(PdfDefinition));
if (!nod.Contains(defDictKey))
{
using (DBDictionary dict = new DBDictionary())
{
nod.SetAt(defDictKey, dict);
t.AddNewlyCreatedDBObject(dict, true);
}
}
ObjectId idPdfDef;
DBDictionary pdfDict =
(DBDictionary)t.GetObject(nod.GetAt(defDictKey),
OpenMode.ForWrite);
using (PdfDefinition pdfDef = new PdfDefinition())
{
pdfDef.SourceFileName = @"C:\temp\test.pdf";
idPdfDef = pdfDict.SetAt("TEST", pdfDef);
t.AddNewlyCreatedDBObject(pdfDef, true);
}
BlockTable bt =
(BlockTable)t.GetObject(db.BlockTableId,
OpenMode.ForRead);
BlockTableRecord btr =
(BlockTableRecord)t.GetObjec(
bt[BlockTableRecord.ModelSpace],
OpenMode.ForWrite);
using (PdfReference pdf = new PdfReference())
{
pdf.DefinitionId = idPdfDef;
btr.AppendEntity(pdf);
t.AddNewlyCreatedDBObject(pdf, true);
}
t.Commit();
}
}