Usina BRAdvPL Guide
Sign in
← All topics
Practical solution guideUnder review

Justify text in a PDF with FWMsPrinter

Measure text in the PDF font, wrap paragraphs to the available width, and print with SayAlign.

AdvPLFWMsPrinterSayAlignGetTextWidthPDF

What you will achieve

Use FWMsPrinter to print terms in a quote or work order. The lab uses a fictional workshop that maintains bookshelves. Run U_EDPARPDF to preview the paragraph and use the wrapping helper when you need to calculate block height or paginate.

Intermediate lines flush with both margins, a left-aligned last line, and text contained in the box.

Before you start

  • Use a test environment with Protheus, TOTVS Printer, and the target font.
  • Set paper size, resolution, and margins before measuring. Use the same font for measuring and drawing.
Step 01

Measure and wrap the text

Normalize file line endings before measuring. Preserve paragraph breaks and join only breaks inside the same sentence. WrapPdf takes one paragraph at a time and uses GetTextWidth to test whether the prefix fits.

View code and commands · Wrap a paragraph by width
Static Function WrapPdf(oPrinter, oFont, cText, nWidth)
    Local aLines := {}
    Local cRest := AllTrim(cText)
    Local nCut := 0
    Local nSpace := 0

    While !Empty(cRest)
        nCut := Len(cRest)
        // Consume at least one character when wrapping a long word.
        While nCut > 1 .And. oPrinter:GetTextWidth(Left(cRest, nCut), oFont) > nWidth
            nCut--
        EndDo
        // If the cut falls inside a word, try the previous space.
        If nCut < Len(cRest) .And. SubStr(cRest, nCut + 1, 1) != " "
            nSpace := RAt(" ", Left(cRest, nCut))
            If nSpace > 1
                nCut := nSpace
            EndIf
        EndIf
        AAdd(aLines, AllTrim(Left(cRest, nCut)))
        cRest := AllTrim(SubStr(cRest, nCut + 1))
    EndDo
Return aLines
Expected result

The helper returns lines in reading order to calculate the block height. Pass one paragraph and use the same width unit that GetTextWidth returns.

Check before continuing

Reduce the width and check that the line count increases. Try a long unbroken word and verify that wrapping consumes all the text.

Step 02

Print a justified paragraph

Pass the full paragraph to SayAlign when it fits in a box. Use nAlignHorz = 3, measure the usable width between the inner edges, and allow enough height for all lines.

View code and commands · FWMsPrinter: justify a paragraph in a fictional work order
#Include "Protheus.ch"
#Include "RPTDef.ch"
#Include "FWPrintSetup.ch"

User Function EdParPdf()
    // Interactive lab; client temporary folder.
    Local cName := "edparpdf_" + 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.)
    Local cText := "Maple Workshop will inspect the shelves at Aurora Library. The crew will tighten the brackets, replace worn parts and record all adjustments. The work is scheduled to take two business days."
    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, "Service terms", oFont)
    oPrint:Box(55, 30, 180, 330)
    // Pass the whole paragraph so the renderer can wrap the lines.
    oPrint:SayAlign(63, 38, cText, oFont, 284, 109, , 3, 1)
    oPrint:EndPage()
    oPrint:Preview()
    FreeObj(oPrint)
    FreeObj(oFont)
Return Nil
Expected result

In the preview, check the right edge of intermediate lines, the left-aligned last line and all text. The box uses a fixed height for this one-page lab. The example was reviewed by reading. Compilation and execution in Protheus are pending.

Check before continuing

Check the right edge of intermediate lines, the left-aligned last line, and the text in the PDF.

Step 03

Reserve space and paginate

Paginate the box. Calculate height from the wrapped lines, line spacing and room for borders, headings and the signature. Check the limit above the footer before drawing. If the block exceeds a full page, split at the measured lines and repeat the header. In a narrow column, use left alignment and reserve the adjacent area for the amount.

Check before continuing

Force a break near the footer and check that the header repeats and every line appears once.

Validate the solution

  • Inspect the PDF and copy its text to check for accents, missing words, and auxiliary text.
  • Compare the metrics with the font actually used by the PDF. Test narrow margins and blocks longer than a full page.

Diagnose by symptom

SymptomWhat to checkHow to resolve it
An intermediate line stays left-alignedThe renderer received one line and treated it as the end of the paragraph.Pass the whole paragraph or validate the line-by-line technique above.
Text overlaps the next columnMeasured and drawn widths differ.Check the PDF font, size, and unit. Allow padding and recalculate using the output metrics.

Practical validation and scope

TOTVS documentation demonstrates GetTextWidth and SayAlign. The libHaru source explains the final-line behavior. The examples were reviewed by reading. Compilation and PDF generation in Protheus are pending.

Common pitfalls
  • Paragraphs from TXT files. Normalize CRLF and CR to LF, preserve paragraph separators and join only line breaks identified as continuations. When using FRead, work with the bytes actually read and decode the text before measuring it.

Continue reading

References

  1. TOTVS. FWMsPrinter (TDN).
  2. TOTVS. Official example with GetTextWidth and SayAlign.
  3. libHaru. HPDF_Page_TextRect in the public source. Final-line behavior depends on the installed renderer implementation.
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