← Macro & add-in library

Drawings & BOM · C# add-in prototype

SolidWorks PDF Export Add-In Prototype

A minimal C# SolidWorks add-in that exposes a command to save the active drawing as PDF.

ENGINEERING CONTRIBUTION

Structured the add-in lifecycle, command routing, registration hooks, build metadata, and export service.

Prerequisites

  • Windows, compatible SolidWorks COM interop assemblies and a matching .NET/COM build configuration.
  • Complete add-in identity/build metadata, registration inputs and host installation.
  • An active drawing and permission to write its PDF output directory.

Additional setup

  • Building and installing this add-in requires BuildInfo.cs, project/solution configuration and COM registration inputs alongside these classes.

SOURCE WALKTHROUGH

How the workflow fits together.

  1. 01

    Connect and register the command

    ConnectToSW captures the application and cookie, registers callback information, creates the PDF service and adds a menu command.

  2. 02

    Validate drawing context

    The enable callback checks drawing type; the export service also independently rejects missing or non-drawing documents.

  3. 03

    Export through the service

    The service obtains PDF export data, chooses the saved drawing directory or Desktop fallback, calls SaveAs and verifies a file exists.

  4. 04

    Report and disconnect

    The command displays success/failure. DisconnectFromSW removes command UI and releases held references.

Output & model changes

  • Adds and removes a SolidWorks command group when registered/loaded.
  • Writes a PDF to the selected path; confirm naming and existing-file behavior before batch use.
  • Displays result messages within SolidWorks.

CODE & ENTRY POINTS

Read the implementation.

Find a procedure, follow an API call or download the module for your SolidWorks setup.

SwPdfExportAddin.cs

COM-visible ISwAddin lifecycle, CommandManager registration, drawing-only command enablement and routing to a separated PDF service.

C# · 237 lines

Download .cs

Entry points
API & integration calls
Selected line 1
using System;
using System.Runtime.InteropServices;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SolidWorks.Interop.swpublished;

namespace PdfExportAddin
{
    /// <summary>
    /// Minimal SOLIDWORKS add-in entry point.
    ///
    /// This class is COM-visible because SOLIDWORKS loads add-ins via COM.
    /// It implements ISwAddin, which is the standard add-in contract used by SOLIDWORKS.
    ///
    /// Responsibilities of this class:
    /// - Connect to and disconnect from SOLIDWORKS.
    /// - Register a simple command group/menu command.
    /// - Route the command to the PDF export service.
    /// - Keep the add-in bootstrap readable and low-risk.
    ///
    /// Design intent for future growth:
    /// - Keep add-in lifecycle code here.
    /// - Keep drawing export business logic in PdfExportService.
    /// - Add future commands/services as separate classes rather than bloating this file.
    /// </summary>
    [ComVisible(true)]
    [Guid(BuildInfo.AddinGuid)]
    [ProgId(BuildInfo.ProgId)]
    public sealed class SwPdfExportAddin : ISwAddin
    {
        private SldWorks _swApp;
        private int _addinCookie;
        private ICommandManager _commandManager;
        private PdfExportService _pdfExportService;

        /// <summary>
        /// SOLIDWORKS calls this when the add-in is loaded.
        ///
        /// This is the add-in's main initialization entry point.
        /// Required tasks performed here:
        /// - capture the SOLIDWORKS application pointer
        /// - store the add-in cookie
        /// - register callback info
        /// - create the PDF export service
        /// - register the menu command
        /// </summary>
        public bool ConnectToSW(object ThisSW, int Cookie)
        {
            _swApp = ThisSW as SldWorks;
            _addinCookie = Cookie;

            if (_swApp == null)
            {
                return false;
            }

            _swApp.SetAddinCallbackInfo2(0, this, _addinCookie);
            _pdfExportService = new PdfExportService(_swApp);
            _commandManager = _swApp.GetCommandManager(_addinCookie);

            AddCommandGroup();

            if (BuildInfo.ShowLoadMessage)
            {
                ShowInfo(
                    "PDF Export Test Add-in loaded.\n\n" +
                    "Use the command 'Save Active Drawing as PDF' from the add-in menu group.\n\n" +
                    "This starter add-in only enables the command when a drawing is active.");
            }

            return true;
        }

        /// <summary>
        /// SOLIDWORKS calls this when the add-in is being unloaded.
        ///
        /// Required cleanup:
        /// - remove command UI that we created
        /// - release references so SOLIDWORKS can unload cleanly
        /// </summary>
        public bool DisconnectFromSW()
        {
            try
            {
                RemoveCommandGroup();
            }
            catch
            {
                // Keep unload robust. During disconnect we do not want a UI cleanup issue
                // to prevent the add-in from unloading.
            }
            finally
            {
                _pdfExportService = null;
                _commandManager = null;
                _swApp = null;
            }

            return true;
        }

        /// <summary>
        /// Creates a minimal command group with a single menu command.
        ///
        /// Why menu only for the first trial?
        /// - Fewer moving parts than toolbar/icon setup.
        /// - Lower risk for the first add-in smoke test.
        /// - Easy to extend later into a CommandManager tab or toolbar.
        /// </summary>
        private void AddCommandGroup()
        {
            if (_commandManager == null)
            {
                return;
            }

            int errors = 0;
            bool ignorePreviousVersion = true;

            ICommandGroup group = _commandManager.CreateCommandGroup2(
                BuildInfo.CommandGroupId,
                BuildInfo.CommandGroupTitle,
                BuildInfo.CommandTooltip,
                BuildInfo.CommandTooltip,
                -1,
                ignorePreviousVersion,
                ref errors);

            if (group == null)
            {
                ShowError(string.Format("Failed to create command group. Error code={0}.", errors));
                return;
            }

            // Menu-only starter command. Once your pipeline is proven, this is the natural place
            // to add toolbar buttons, tabs, icons, multiple commands, and document-specific UI.
            group.AddCommandItem2(
                BuildInfo.CommandTitle,
                -1,
                BuildInfo.CommandTooltip,
                BuildInfo.CommandTooltip,
                -1,
                nameof(Command_SaveActiveDrawingAsPdf),
                nameof(Enable_SaveActiveDrawingAsPdf),
                0,
                (int)swCommandItemType_e.swMenuItem);

            group.HasMenu = true;
            group.HasToolbar = false;
            group.Activate();
        }

        /// <summary>
        /// Removes the command group created by this add-in.
        /// </summary>
        private void RemoveCommandGroup()
        {
            if (_commandManager == null)
            {
                return;
            }

            _commandManager.RemoveCommandGroup(BuildInfo.CommandGroupId);
        }

        /// <summary>
        /// SOLIDWORKS callback method for the command.
        ///
        /// IMPORTANT:
        /// The method name is passed to AddCommandItem2 as a string callback name,
        /// so renaming this method requires updating that string as well.
        /// </summary>
        public void Command_SaveActiveDrawingAsPdf()
        {
            if (_pdfExportService == null)
            {
                ShowError("PDF export service is not initialized.");
                return;
            }

            ExportResult result = _pdfExportService.ExportActiveDrawingToPdf();

            if (!result.IsSuccess)
            {
                ShowError(result.Message);
                return;
            }

            if (BuildInfo.ShowSuccessMessage)
            {
                ShowInfo(result.Message);
            }
        }

        /// <summary>
        /// SOLIDWORKS enable-method callback for the menu command.
        ///
        /// Return convention:
        /// - 1 = enabled
        /// - 0 = disabled
        ///
        /// This starter logic enables the command only when the active document is a drawing.
        /// </summary>
        public int Enable_SaveActiveDrawingAsPdf()
        {
            if (_swApp == null)
            {
                return 0;
            }

            ModelDoc2 model = _swApp.ActiveDoc as ModelDoc2;
            if (model == null)
            {
                return 0;
            }

            return model.GetType() == (int)swDocumentTypes_e.swDocDRAWING ? 1 : 0;
        }

        private void ShowInfo(string message)
        {
            _swApp?.SendMsgToUser2(
                message,
                (int)swMessageBoxIcon_e.swMbInformation,
                (int)swMessageBoxBtn_e.swMbOk);
        }

        private void ShowError(string message)
        {
            _swApp?.SendMsgToUser2(
                message,
                (int)swMessageBoxIcon_e.swMbStop,
                (int)swMessageBoxBtn_e.swMbOk);
        }
    }
}
Procedure index · 8 declarations
File checksum

SHA-256: 68ccdaea6801a9bb09f8ad0e1fb3cbbb7d47de68a77eb88d103b2c0977d4d983