Usina BRAdvPL Guide
Sign in
← All topics
PRACTICAL GUIDEUnder review

How to build Protheus reports: PDF and Excel

Choose TReport, FWMsPrinter or FWMsExcelXlsx and follow requirements, data selection, layout, generation, delivery and acceptance checks.

RelatóriosPDFExcelXLSXTReportTRSectionTRCellFWMsPrinterFWMsExcelXlsxPrintDialogGetXMLFileProtheus
01 · OVERVIEW

Overview

Start with the purpose: does the user need a paginated document or a spreadsheet for analysis? Consider TReport for structured listings with sections and totals, FWMsPrinter for a PDF with explicit drawing and positioning, and FWMsExcelXlsx for native .xlsx workbooks. They can share data selection, but use different generation lifecycles. No single method produces every format with an identical visual result. This lab uses two fictional items: code 0001, quantity 2, unit value 10.50; code 0002, quantity 1, unit value 25.00. The expected total is 46.00. It does not access ERP tables. Sources are editorial adaptations with attribution in each example; they have not been compiled or run in Protheus. This page remains Under review until acceptance in the target release, LIB, AppServer and client. TReport (the AdvPL class) and TReports/Smart View (the analytics and reporting product) are different concepts.

03 · PRACTICAL EXAMPLE

TReport: two fictional rows and an interactive dialog

#Include "Protheus.ch"
#Include "RPTDef.ch"

User Function EdRpt()
    // Fictional data: no ERP access.
    Local aData := { {"0001", 2, 10.50}, {"0002", 1, 25.00} }
    Local oReport := TReport():New("EDRPT", "Item report", Nil, ;
        {|oRep| EdRows(oRep, aData)})
    Local oSection := TRSection():New(oReport, "Items", {})

    // No real alias: assign values explicitly.
    TRCell():New(oSection, "CODE", "", "Code", "@!", 8)
    TRCell():New(oSection, "QTY", "", "Quantity", "999", 8)
    TRCell():New(oSection, "AMOUNT", "", "Total", "@E 999,999.99", 14)
    // Dialog confirmation triggers processing.
    oReport:PrintDialog()
    FreeObj(oReport)
Return Nil

Static Function EdRows(oReport, aData)
    Local oSection := oReport:Section(1)
    Local nRow := 0
    oReport:SetMeter(Len(aData))
    oSection:Init()
    For nRow := 1 To Len(aData)
        // Stop printing when cancellation is requested.
        If oReport:Cancel()
            Exit
        EndIf
        oSection:Cell("CODE"):SetValue(aData[nRow, 1])
        oSection:Cell("QTY"):SetValue(aData[nRow, 2])
        oSection:Cell("AMOUNT"):SetValue(aData[nRow, 2] * aData[nRow, 3])
        oSection:PrintLine()
        oReport:IncMeter()
    Next nRow
    // Finish the section even after user cancellation.
    oSection:Finish()
Return Nil
Expected result

Editorial adaptation of refs. 2–3. Expected after confirmation: two rows with line totals of 21.00 and 25.00. PDF/spreadsheet availability depends on the environment. Not compiled or run; also validate alias-free cells and cancellation.

04 · PRACTICAL EXAMPLE

FWMsPrinter: a single-page graphical PDF

#Include "Protheus.ch"
#Include "RPTDef.ch"
#Include "FWPrintSetup.ch"

User Function EdPdf()
    // Interactive lab; client temporary folder.
    Local cName := "edpdf_" + DToS(Date()) + "_" + StrTran(Time(), ":", "")
    Local oPrint := FWMsPrinter():New(cName, IMP_PDF, .F., , .T.)
    Local oFont := TFont():New("Arial", 9, -12, .T., .F., 5, .T., 5, .T., .F.)
    oPrint:cPathPDF := GetTempPath()
    // Configure paper before drawing.
    oPrint:SetResolution(72)
    oPrint:SetPortrait()
    oPrint:SetPaperSize(DMPAPER_A4)
    oPrint:SetMargin(0, 0, 0, 0)
    // One page only: implement pagination when expanding this example.
    oPrint:StartPage()
    oPrint:Say(30, 30, "Item report", oFont)
    oPrint:Say(60, 30, "0001     2 x 10.50 = 21.00", oFont)
    oPrint:Say(80, 30, "0002     1 x 25.00 = 25.00", oFont)
    oPrint:Say(110, 30, "Total: 46.00", oFont)
    oPrint:EndPage()
    oPrint:Preview()
    FreeObj(oPrint)
    FreeObj(oFont)
Return Nil
Expected result

Editorial adaptation of the lifecycle in ref. 5, with simplified settings. Expected: one page showing both items and a 46.00 total in preview/PDF. Not compiled or run; verify fonts, coordinates, paths and client/LIB behavior.

05 · PRACTICAL EXAMPLE

FWMsExcelXlsx: write a server workbook

#Include "Protheus.ch"

User Function EdXls(cServerFile)
    Local oExcel := Nil
    Local lOk := .F.
    // Caller must supply a new file in an approved server folder.
    If ValType(cServerFile) != "C"
        Return .F.
    EndIf
    If Empty(cServerFile) .Or. Lower(Right(cServerFile, 5)) != ".xlsx"
        Return .F.
    EndIf
    // Do not overwrite; reserve a unique execution filename in production.
    If File(cServerFile)
        Return .F.
    EndIf
    oExcel := FWMsExcelXlsx():New()
    oExcel:AddWorkSheet("Reports")
    oExcel:AddTable("Reports", "Data")
    oExcel:AddColumn("Reports", "Data", "Code", 1, 1, .F.)
    oExcel:AddColumn("Reports", "Data", "Quantity", 3, 2, .F.)
    oExcel:AddColumn("Reports", "Data", "Total", 3, 3, .F.)
    // Numbers remain numeric and codes remain text.
    oExcel:AddRow("Reports", "Data", {"0001", 2, 21.00})
    oExcel:AddRow("Reports", "Data", {"0002", 1, 25.00})
    If oExcel:Activate()
        // GetXMLFile writes XLSX in this class.
        lOk := oExcel:GetXMLFile(cServerFile)
    EndIf
    // Normal-path cleanup; add exception handling.
    oExcel:DeActivate()
    FreeObj(oExcel)
Return lOk
Expected result

Editorial adaptation of the official API in ref. 6. Expected: a logical result indicating XLSX writing, with two rows. It does not download or open the file. Not compiled or run; normal success does not replace failure, type and cleanup acceptance.

BEST PRACTICES
  • 1. Define the deliverable first. Record the audience, business question, row grain (item, receivable or document), columns, units, currency, period, filters, sorting, grouping and totals. Agree on destination, deadline, volume and access. Lab acceptance: two rows, three units, a total of 46.00, a readable PDF and numeric spreadsheet values usable in calculations.
  • 2. Choose a route. TReport organizes report → TRSection → TRCell; TRBreak and TRFunction add grouping and calculations according to the installed API. FWMsPrinter organizes pages and graphical elements and requires explicit line and page control. FWMsExcelXlsx organizes worksheet → table → columns → rows. FWMsExcel/FWMsExcelEx produce legacy XML rather than native XLSX; TOTVS identifies FWMsExcel as deprecated. Renaming XML to XLSX does not convert it. Do not assume identical layout across outputs or LIB versions. (Refs. 1–8.)
  • 3. Prepare a test environment. Record the release, LIB label, AppServer build, SmartClient/WebApp, operating system, includes and TOTVS Printer versions on both sides. The official FWMsExcelXlsx reference gives historical minimums of AppServer 17.3.0.0 and printer.exe 2.1.0; these do not replace the current compatibility matrix. Check approved folders, fonts, disk space and execution account. Compile the PRW with the includes for the test RPO through the TOTVS VS Code extension and inspect the log before adding a menu entry. (Refs. 6, 9.)
  • 4. Separate selection from presentation. Reproduce the fictional dataset first, then replace it with a validated query. Establish row grain before joining tables to avoid duplicate amounts. Respect company, branch, sharing rules, deleted records and authorization; use logical names/RetSQLName, a unique alias and bound parameters through compatible APIs instead of concatenating user input. Sort by grouping keys. Preserve work areas and close only aliases opened by this routine, including on cancellation or failure. Use the related query guides for real integration.
  • 5. TReport: run U_EDRPT in an interactive test session. Definition creates sections and cells; PrintDialog opens output selection and bAction processes rows after confirmation. SetValue avoids dependence on a real table. Processing follows Init → values → PrintLine → Finish and checks Cancel inside the loop. Add breaks and automatic totals only after checking a simple listing. The 46.00 check total comes from the data; this example adds no automatic totalizer and promises no universal output appearance. (Refs. 2, 3.)
  • 6. Graphical PDF: run U_EDPDF only in the interactive client used by this example. Set paper, orientation, resolution and margins before drawing. Follow StartPage → elements → EndPage → Preview. This single-page lab uses the client temporary folder; for many rows, implement a page limit, repeated headers and footers before drawing the next row. cPathInServer and cPathPDF are different settings. Preview does not prove unattended generation or browser delivery. (Refs. 4, 5, 9.)
  • 7. XLSX: U_EDXLS receives a complete path for a new server file from an authorized caller. Its folder must exist and be approved; never accept an arbitrary path from a web request. The example builds rows, calls Activate, checks GetXMLFile and releases the object. Despite its name, GetXMLFile writes XLSX in this class. Preserve leading-zero codes as text and amounts as numbers; dates need a verified type/format rather than DTOC applied indiscriminately. Do not copy FWMsExcelEx style methods into FWMsExcelXlsx. (Ref. 6.)
  • 8. Deliver for the actual client. Creating a server file does not download it. The official reference distinguishes CpyS2T for desktop SmartClient and CpyS2TW for WebApp without Web-Agent; check the supported mechanism and generation completion before copying. Use a unique execution filename and a restricted folder, log failures without sensitive data and apply temporary-file retention. Jobs require explicit context and destination without dialogs; do not automatically reuse these interactive callers. For TReport PDF, check MV_RELT: the official 12.1.17+ example ties its output directory to this setting. (Refs. 6, 9, 10.)
  • 9. Accept and publish. Test no records, one row, multiple pages, accents, long text, leading zeros, rounding, cancellation and missing permissions. Compare the same selection in PDF and XLSX without demanding identical pagination. Measure time and memory with realistic volume; test concurrent users and folder/Printer failures. Open files without format warnings and reconcile totals against an independent source. Then apply the patch or compile through the authorized process, add U_EDRPT/U_EDPDF to the appropriate menu and retain the previous source/version for rollback. U_EDXLS is a parameterized helper, not a ready-to-use menu action.
  • For quotes and work orders, see the guide to justified text and paragraph pagination.
COMMON PITFALLS
  • Only a .rel file: intermediate output does not prove completed PDF generation. Check the actual TOTVS Printer agent, versions, permissions and client/server paths. Do not call the binary directly as an improvised fix. (Ref. 9.)
  • Blank workbook or printer.exe error: check compatibility and generation results before reporting success. An .xlsx extension does not guarantee XLSX content; open and validate it. (Refs. 6, 7, 9.)
  • Duplicate total: investigate row grain and join cardinality before changing totalizers. Unit prices are not line amounts.
  • Large volume: the fictional array is a lab fixture. Do not load an entire production query into an array. Evaluate SetWriteinFile or SetWriteinDB for the installed LIB without assuming the two modes can be combined. (Refs. 6, 8.)
  • Examples show the normal lifecycle. Add guaranteed exception cleanup, directory validation, partial-file handling, delivery and auditing before production. They have not been tested in AppServer, SmartClient, WebApp or jobs.

Related content

REFERENCES
  1. TOTVS. TReport (TDN); direct access returned 403.
  2. TOTVS. TReport example with TRSection, TRCell and SetValue. June 18, 2024.
  3. Atilio. Example_505. Author-maintained GitHub source read in full; adapted report structure.
  4. TOTVS. FWMsPrinter (TDN); direct access returned 403.
  5. Atilio. Example_236. Author-maintained GitHub source read in full; adapted graphical lifecycle.
  6. TOTVS. FwMsExcelXlsx API reference, commit 41504805e419b72232885f7575d54dfd573fea1b; read in full.
  7. TOTVS. XML and XLSX are different formats. June 19, 2024.
  8. TOTVS. FWMsExcel memory usage and deprecation. May 16, 2024.
  9. TOTVS. Printer.exe errors and client/server/job differences. July 4, 2024.
  10. TOTVS. TReport PDF directory and MV_RELT. Historical example for 12.1.17+, April 24, 2024.
  11. TOTVS. FWMsExcelXlsx. Target-LIB reference; direct access unavailable during this review.
Status
Under review
Page created on
Last reviewed on
Original language
Portuguese
Reviewed by
Usina.BR

Was this content helpful?

👍 Like 0👎 Dislike 0

Sign in to rate this article.

0 approved comment(s)

Comments

There are no approved comments yet.

Sign in with Google or Microsoft to comment.

Powered by Usina Docs · Alpha