3

I am working for some project development related to PDF generation using LibHaru. I plan to fit some text in a particular region. I used TextRect() for that but I have some trouble with the text wrapping.

  1. If the width of the text is more than that of the width of the rectangle, the rectangle goes blank. How do I get rid of that?
  2. I tried to write my own text wrapping or split string function which adds space after a particular number of characters but even that seems to fail after a particular limit. Any help regarding the text wrapping function.
  3. How go I calculate the width of the text which will fit inside a particular width of the rectangle?

Here is the code snippet for the split string function:

void SplitString(int iLength, string strInput, string& strOutput)
{

    int iSubstringsCnt;
    int iAddedCnt;


    iSubstringsCnt = strInput.length() / iLength;
    iAddedCnt = iSubstringsCnt / iLength;
    cout<<iSubstringsCnt<<endl;
    cout<<iAddedCnt<<endl;

    cout<<strInput.length()<<endl;
    for (int iCnt = 0; iCnt <= iSubstringsCnt+ iAddedCnt; iCnt++)
    {
            if (0 == iCnt)
                    continue;
                strInput.insert((iCnt * iLength)+(iCnt-1) , " ");
    }

    strOutput= strInput;

}
  • iLength: The length after which I want to split.
  • iAddedCnt: The count of the string after I added space after a few characters.
m00am
  • 5,910
  • 11
  • 53
  • 69

1 Answers1

2

Libharu is a rather low-level pdf library. Therefore, it doesn't have too many text formatting options, such as advanced text wrapping. However, it offers you some help:

  • The function HPDF_Page_TextRect writes the number of printed characters so you can check if the print was successful without checking the pdf file;
  • HPDF_Font_TextWidth returns the width of the text that is to be printed (in dots); and
  • the function HPDF_Font_MeasureText gives you the number of bytes that can be printed to a given width (answers 3).

With these functions, you could split the text into several lines. Example (for 2):

  • Use HPDF_Font_MeasureText to set iLength
  • Find possible linebreak position (such as hyphen, dot, colon or space) using strInput.rfind("-",iLength)
  • If a possible linebreak position was found, insert \n at that position; else: insert the linebreak at iLength.

Another problem you may encounter is the height of the box. If you have too many lines, they will not be printed. While splitting your text into several lines you can keep track of the required number of lines, while the possible number of lines in the box is obtained by the box height and the line spacing (set by HPDF_Page_SetTextLeading).

If you have too much text for the size of the box, libharu can't do anything. The only ways are increasing the box size and decreasing the font size (answers 1).

Gregor
  • 411
  • 1
  • 6
  • 12