{"title":"Creating a Printer Extension","url":"https://jonas-paprotka.de/docs/dev-itpro/developer/devenv-reports-create-printer-extension/","by":"JOP-AL","license":"Copyright (c) Microsoft Corporation. CC BY 4.0, https://creativecommons.org/licenses/by/4.0/; code samples MIT. From https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-reports-create-printer-extension, MicrosoftDocs/dynamics365smb-devitpro-pb at 828b6ee (2026-11-19). Changed: includes filled in, links to this site, and for agents shortened without dropping a fact.","credit":"Microsoft Corporation, CC BY 4.0","origin":"https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-reports-create-printer-extension","source":{"name":"Business Central developer and IT pro docs","repo":"https://github.com/MicrosoftDocs/dynamics365smb-devitpro-pb","commit":"828b6ee72fcd75755627cd6011f3d20899217ab2","date":"2026-11-19"},"checked":"2026-11-19","description":"Describes how to create an extension that sets up cloud printers.","date":"2021-04-01","meta":{"topic":"how-to"},"outline":[{"level":1,"title":"Creating a Printer Extension","slug":"creating-a-printer-extension","at":0,"chars":12457},{"level":2,"title":"Overview","slug":"overview","at":195,"chars":573},{"level":2,"title":"Set up printers using the OnAfterSetupPrinters event","slug":"set-up-printers-using-the-onaftersetupprinters-event","at":768,"chars":5798},{"level":3,"title":"Getting started","slug":"getting-started","at":992,"chars":2805},{"level":3,"title":"About the printer payload","slug":"about-the-printer-payload","at":3797,"chars":1086},{"level":3,"title":"Using the ReadFrom method to create the payload","slug":"using-the-readfrom-method-to-create-the-payload","at":4883,"chars":774},{"level":3,"title":"Select the paper tray","slug":"select-the-paper-tray","at":5657,"chars":909},{"level":2,"title":"Handle print using the OnAfterDocumentPrintReady event","slug":"handle-print-using-the-onafterdocumentprintready-event","at":6566,"chars":5629},{"level":3,"title":"Getting started","slug":"getting-started-1","at":6884,"chars":3692},{"level":3,"title":"About the report payload","slug":"about-the-report-payload","at":10576,"chars":1619},{"level":2,"title":"Related information","slug":"related-information","at":12195,"chars":262}],"text":"# Creating a Printer Extension\nThis article describes how to use the devenv-onaftersetupprinters-event and devenv-onafterdocumentprintready-event events to set up different printers for reports.\n## Overview\nThis article uses a simplified printer extension example for sending reports to an email printer. The example creates a printer extension that sets up a single email printer. Users can then assign the printer to reports from the Printer Selections page in the client. In this article, you will:\n Create two codeunits, one that subscribes to the OnAfterSetupPrinters event and another that subscribes to the OnAfterDocumentPrintReady event.\n Use the SMTP Mail and Mail Management codeunits that are part of the base application for sending the report via email.\n## Set up printers using the OnAfterSetupPrinters event\nThis section describes how to use the OnAfterSetupPrinters event to set up a printer. When completed, users can select the printer from on the Printer Selections page.\n### Getting started\n1. Create an AL project for the printer extension.\n See Get Started with AL<devenv-get-started>.\n2. Create a codeunit to use for subscribing to the OnAfterSetupPrinters event.\n2. Create a method that subscribes to the OnAfterSetupPrinters event.\n At this point, your code would look something like this:\n ```al\n codeunit 50100 SetupPrinter\n {\n     [EventSubscriber(ObjectType::Codeunit, Codeunit::\"ReportManagement\", 'OnAfterSetupPrinters', '', true, true)]\n     procedure OnSetupPrinters(var Printers: Dictionary of [Text[250], JsonObject])\n     var\n\n     begin\n\n     end;\n }\n\n ```\n For more information about subscribing to events, see devenv-subscribing-to-events.\n3. Now you can start adding code to the event subscriber method to create the printer payloads.\n In this example, you set up a printer named 'My Printer' that has two paper trays: A4 and Custom. There are two ways of setting values for a payload JSON object. You can add properties (key-value pairs) by using the Add method, as shown in the example. Or, you can use the ReadFrom method to read the JSON data from the string into a JsonObject variable (see Using ReadFrom to create the payload<#readfrom>).\n ```al\n codeunit 50100 SetupPrinter\n {\n     [EventSubscriber(ObjectType::Codeunit, Codeunit::\"ReportManagement\", 'OnAfterSetupPrinters', '', true, true)]\n     procedure OnSetupPrinters(var Printers: Dictionary of [Text[250], JsonObject])\n     var\n         Payload: JsonObject;\n         PaperTrays: JsonArray;\n         PaperTrayA4: JsonObject;\n         PaperTrayCustom: JsonObject;\n     begin\n         // Step 1: Create the paper trays\n         PaperTrayA4.Add('papersourcekind', 'Upper');\n         PaperTrayA4.Add('paperkind', 'A4');\n\n         PaperTrayCustom.Add('papersourcekind', 'Custom');\n         PaperTrayCustom.Add('paperkind', 'Custom');\n         PaperTrayCustom.Add('width', 236);\n         PaperTrayCustom.Add('height', 322);\n         PaperTrayCustom.Add('units', 'mm');\n\n         // Step 2: Add the paper trays to the list of paper trays\n         PaperTrays.Add(PaperTrayA4);\n         PaperTrays.Add(PaperTrayCustom);\n\n         // Step 3: Add the required parameters for the payload\n         Payload.Add('version', 1);\n         Payload.Add('papertrays', PaperTrays);\n\n         // Step 4: Add the printer to the dictionary\n         Printers.Add('My Printer', Payload);\n     end;\n }\n\n ```\n4. At this point, you can compile your project, and publish/install the extension on the tenant to test the payload.\n Open the Printer Selections page in the client. You should see My Printer as an option in the Printer Name field. If there are errors with payload, you'll get an error when you try to open the Printer Name field. See Troubleshooting Printer Payload Errors<devenv-reports-troubleshoot-printing>.\n### About the printer payload\nThe event subscriber method has one parameter, which is a dictionary of printers. The key is a name of the printer. The value is a JSON object that is referred to as the payload. The payload specifies information about a specific printer. The payload includes several attributes in the following structure:\n```json\n{\n    \"version\": 1,\n    \"description\":[default=\"\"],\n    \"duplex\":[default=false],\n    \"color\":[default=false],\n    \"defaultcopies\":[default=1],\n    \"papertrays\":\n    [\n        {\n            \"papersourcekind\":'Upper' | 1,\n            \"paperkind\":'A4' | 9,\n            \"units\":[default='HI'],\n            \"height\":[default=0],\n            \"width\":[default=0],\n            \"landscape\":[default=false]\n        }\n    ]\n}\n```\nThere are few required attributes, such as version and papertrays. The papertrays attribute must contain at least one paper tray setup, which in turn must include the attributes papersourcekind and paperkind. For more information about the attributes, see Printer Payload<devenv-onaftersetupprinters-event#printpayload>.\n### Using the ReadFrom method to create the payload\nThe following example illustrates how to create a payload by using the ReadFrom method.\n```al\ncodeunit 50101 SetupPrinter2\n{\n    [EventSubscriber(ObjectType::Codeunit, Codeunit::\"ReportManagement\", 'OnAfterSetupPrinters', '', true, true)]\n    procedure SetupPrinters(var Printers: Dictionary of [Text[250], JsonObject])\n    var\n        Payload: JsonObject;\n    begin\n        // Step 1: Read the payload from the text\n        Payload.ReadFrom('{\"version\":1,\"papertrays\":[{\"papersourcekind\":\"Upper\",\"paperkind\":\"A4\"},{\"papersourcekind\":\"Custom\",\"paperkind\":\"Custom\",\"width\":236,\"height\":322,\"units\":\"mm\"}]}');\n\n        // Step 2: Add the printer to the dictionary\n        Printers.Add('My Printer', Payload);\n    end;\n}\n```\n### Select the paper tray\nA printer can have several paper trays. If a report doesn't specify which paper tray to use or the specified paper tray isn't present in the printer's setup, a default paper tray is used. The default paper tray is the first one defined in the papertrays list.\nYou can change the paper tray for an existing report by subscribing to the OnAfterGetPaperTrayForReport event and setting a value for a DefaultPage parameter.\n```al\n[EventSubscriber(ObjectType::Codeunit, Codeunit::\"ReportManagement\", 'OnAfterGetPaperTrayForReport', '', true, true)]\nprocedure GetPaperTrayForReport(ReportID: Integer; var FirstPage: Integer; var DefaultPage: Integer; var LastPage: Integer)\n```\nAs an alternative, if you're creating a new report, you can set a paper tray by specifying PaperSourceDefaultPage property.\n```al\nreport 50103 MyReport\n{\n    PaperSourceDefaultPage = Upper;\n            ...\n}\n```\n## Handle print using the OnAfterDocumentPrintReady event\nThis section describes how to subscribe to the OnAfterDocumentPrintReady event. You subscribe to the OnAfterDocumentPrintReady event to define what happens when a user chooses to print a report. The event subscriber specifies how and where to send the report.\n### Getting started\n1. Create a codeunit to use for subscribing to the OnAfterDocumentPrintReady event.\n2. Create a method that subscribes to OnAfterDocumentPrintReady event.\n At this point, your code would look something like this:\n ```al\n codeunit 50102 HandlePrintAction\n {\n     [EventSubscriber(ObjectType::Codeunit, Codeunit::ReportManagement, 'OnAfterDocumentPrintReady', '', true, true)]\n     procedure OnDocumentPrintReady(ObjectType: Option \"Report\",\"Page\"; ObjectId: Integer; ObjectPayload: JsonObject; DocumentStream: InStream; var Success: Boolean)\n     var\n\n     begin\n\n     end;\n }\n ```\n For more information about subscribing to events, see devenv-subscribing-to-events.\n3. Now you can start adding code to the event subscriber method to handle the report payload and send the report.\n The following code sends a report by email to the printer that is named 'My Printer'. In this example, the printer's email address is 'myprinterb@businesscentral.onmicrosoft.com'.\n ```al\n codeunit 50101 SendReportByEmail\n {\n     [EventSubscriber(ObjectType::Codeunit, Codeunit::ReportManagement, 'OnAfterDocumentPrintReady', '', true, true)]\n     procedure OnDocumentPrintReady(ObjectType: Option \"Report\",\"Page\"; ObjectId: Integer; ObjectPayload: JsonObject; DocumentStream: InStream; var Success: Boolean)\n     var\n         SMTPMail: Codeunit \"SMTP Mail\";\n         PrinterNameToken: JsonToken;\n         PrinterName: Text;\n         ObjectNameToken: JsonToken;\n         ObjectName: Text;\n         DocumentTypeToken: JsonToken;\n         DocumentTypeParts: List of [Text];\n         FileExtension: Text;\n         MailManagement: Codeunit \"Mail Management\";\n         SendFrom: Text;\n         FileName: Text;\n         Recipients: List of [Text];\n     begin\n         begin\n             // Step 1: Before doing anything, it is important to check the current Success value\n             if Success then\n                 exit;\n\n             // Step 2: Make sure code only runs for reports\n             if ObjectType = ObjectType::Report then begin\n\n                 // Step 3: Get report object payload information\n                 ObjectPayload.Get('printername', PrinterNameToken);\n                 PrinterName := PrinterNameToken.AsValue().AsText();\n                 if PrinterName = 'My Printer' then begin\n                     ObjectPayload.Get('objectname', ObjectNameToken);\n                     ObjectName := ObjectNameToken.AsValue().AsText();\n                     ObjectPayload.Get('documenttype', DocumentTypeToken);\n\n                     // Step 4: Build the email message\n                     DocumentTypeParts := DocumentTypeToken.AsValue().AsText().Split('/');\n                     FileExtension := DocumentTypeParts.Get(DocumentTypeParts.Count);\n                     Recipients.Add('myprinterb@businesscentral.onmicrosoft.com');\n                     SendFrom := MailManagement.GetSenderEmailAddress();\n                     SMTPMail.CreateMessage('Sender', SendFrom, Recipients, 'Hello this is your report', 'Please take a look');\n                     SMTPMail.AddAttachmentStream(DocumentStream, ObjectName + '.' + FileExtension);\n\n                     // Step 5: Send the email for print\n                     SMTPMail.Send;\n                     Success := true;\n                     exit;\n                 end;\n             end;\n         end;\n     end;\n }\n ```\n4. At this point, you can compile and publish/install the extension on a tenant to test.\n First, make sure that SMTP email is set up on the tenant (see Set Up Email</admin-how-setup-email> in the Application Help).\n Then, on the Printer Selections page, set a report to use 'My Printer', and then run and print the report.\n### About the report payload\nThe event subscriber receives the printer payload and combines it with the report metadata, like the report's ID. This combination is the report payload. The content of the report itself is received as a stream object. You add code to define how and where to send the report payload for printing. In this example, it's sent as an email.\nThe report object payload is a JSON object that includes several parameters and values arranged in a specific structure, as shown in the following example\n```json\n{\n    \"filterviews\":\n    [\n        {\"name\":\"Header\",\"tableid\":112,\"view\":\"VERSION(1) SORTING(Field3) WHERE(Field3=1(103027))\"},\n        {\"name\":\"Line\",\"tableid\":113,\"view\":\"VERSION(1) SORTING(Field3,Field4) WHERE(Field4=1(0..10000))\"},\n        {\"name\":\"ShipmentLine\",\"tableid\":7190,\"view\":\"VERSION(1) SORTING(Field1,Field2,Field3) WHERE(Field2=1(10000))\"}\n    ],\n    \"version\":1,\n    \"objectname\":\"Standard Sales - Invoice\",\n    \"objectid\":1306,\n    \"documenttype\":\"application/pdf\",\n    \"invokedby\":\"00000000-0000-0000-0000-000000000001\",\n    \"invokeddatetime\":\"2020-01-17T15:33:52.48+01:00\",\n    \"companyname\":\"CRONUS International Ltd.\",\n    \"printername\":\"My Printer\",\n    \"duplex\":false,\n    \"color\":false,\n    \"defaultcopies\":1,\n    \"papertray\":\n    {\n        \"papersourcekind\":257,\n        \"paperkind\":0,\n        \"landscape\":false,\n        \"units\":0,\n        \"height\":1268,\n        \"width\":929\n    }\n}\n```\nThe parameters can be read but not modified at runtime. For more information about the report payload, see Report Payload<devenv-onafterdocumentprintready-event#reportpayload>.\n## Related information\nWorking With and Troubleshooting Payloads<devenv-reports-troubleshoot-printing>\nDeveloping Printer Extensions Overview<devenv-reports-printing>\ndevenv-events-in-al\ndevenv-publishing-events\ndevenv-raising-events\ndevenv-subscribing-to-events"}