javapdfitextopenpdf

How can I replace text in PDF with muliply lines?


I am using openPdf library (fork of iTextPdf) to replace placeholders like #{Address_name_1} with real values. My PDF file is not simple, so I use regular expression to find this placeholder:[{].*?[A].*?[d].*?[d].*?[r].*?[e].*?[s].*?[s].*?[L].*?[i].*?[n].*?[e].*?[1].*?[}]

and do something like

content = MY_REGEXP.replace(content, "Saint-P, Nevskiy pr."); obj.setData(content.toByteArray(CHARSET)).

The problem happens when my replacement line is too long and it is unfortunately cut from right end. Can I somehow make it carry over to the next line? Naive \n does not work.


Solution

  • PDF store strings in a different way. There are no next lines, there are lines.

    So you will need to add several placeholders on fields on your template for replacements that can get long enough, like:

    #{Address_name_1_line1}
    #{Address_name_1_line2}
    #{Address_name_1_line3}
    

    And place it in different lines on your template. The non-used empty placeholders (because replacement is not long enough) should be replaced by empty strings.

    For longer replacements you will need to use several placeholders. The number of placeholders to use and the replacement splitting should be determined by code.

    If your PDF is too complex to place different placeholders then you will need to placeholder everything, all your text contents should be inyected into placeholders, at least if you want to use this approach.